PackageManagerService.java revision 700e1e7ee8e4ed491768a35ed692a4e8f0ff0d4b
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_SKU_PROPERTY is set, search for runtime resource overlay APKs in 470 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_SKU_PROPERTY> rather than in 471 * VENDOR_OVERLAY_DIR. 472 */ 473 private static final String VENDOR_OVERLAY_SKU_PROPERTY = "ro.boot.vendor.overlay.sku"; 474 475 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000; 476 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5; 477 478 /** Permission grant: not grant the permission. */ 479 private static final int GRANT_DENIED = 1; 480 481 /** Permission grant: grant the permission as an install permission. */ 482 private static final int GRANT_INSTALL = 2; 483 484 /** Permission grant: grant the permission as a runtime one. */ 485 private static final int GRANT_RUNTIME = 3; 486 487 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 488 private static final int GRANT_UPGRADE = 4; 489 490 /** Canonical intent used to identify what counts as a "web browser" app */ 491 private static final Intent sBrowserIntent; 492 static { 493 sBrowserIntent = new Intent(); 494 sBrowserIntent.setAction(Intent.ACTION_VIEW); 495 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 496 sBrowserIntent.setData(Uri.parse("http:")); 497 } 498 499 /** 500 * The set of all protected actions [i.e. those actions for which a high priority 501 * intent filter is disallowed]. 502 */ 503 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 504 static { 505 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 506 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 507 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 508 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 509 } 510 511 // Compilation reasons. 512 public static final int REASON_FIRST_BOOT = 0; 513 public static final int REASON_BOOT = 1; 514 public static final int REASON_INSTALL = 2; 515 public static final int REASON_BACKGROUND_DEXOPT = 3; 516 public static final int REASON_AB_OTA = 4; 517 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 518 public static final int REASON_SHARED_APK = 6; 519 public static final int REASON_FORCED_DEXOPT = 7; 520 public static final int REASON_CORE_APP = 8; 521 522 public static final int REASON_LAST = REASON_CORE_APP; 523 524 /** Special library name that skips shared libraries check during compilation. */ 525 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 526 527 final ServiceThread mHandlerThread; 528 529 final PackageHandler mHandler; 530 531 private final ProcessLoggingHandler mProcessLoggingHandler; 532 533 /** 534 * Messages for {@link #mHandler} that need to wait for system ready before 535 * being dispatched. 536 */ 537 private ArrayList<Message> mPostSystemReadyMessages; 538 539 final int mSdkVersion = Build.VERSION.SDK_INT; 540 541 final Context mContext; 542 final boolean mFactoryTest; 543 final boolean mOnlyCore; 544 final DisplayMetrics mMetrics; 545 final int mDefParseFlags; 546 final String[] mSeparateProcesses; 547 final boolean mIsUpgrade; 548 final boolean mIsPreNUpgrade; 549 final boolean mIsPreNMR1Upgrade; 550 551 @GuardedBy("mPackages") 552 private boolean mDexOptDialogShown; 553 554 /** The location for ASEC container files on internal storage. */ 555 final String mAsecInternalPath; 556 557 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 558 // LOCK HELD. Can be called with mInstallLock held. 559 @GuardedBy("mInstallLock") 560 final Installer mInstaller; 561 562 /** Directory where installed third-party apps stored */ 563 final File mAppInstallDir; 564 final File mEphemeralInstallDir; 565 566 /** 567 * Directory to which applications installed internally have their 568 * 32 bit native libraries copied. 569 */ 570 private File mAppLib32InstallDir; 571 572 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 573 // apps. 574 final File mDrmAppPrivateInstallDir; 575 576 // ---------------------------------------------------------------- 577 578 // Lock for state used when installing and doing other long running 579 // operations. Methods that must be called with this lock held have 580 // the suffix "LI". 581 final Object mInstallLock = new Object(); 582 583 // ---------------------------------------------------------------- 584 585 // Keys are String (package name), values are Package. This also serves 586 // as the lock for the global state. Methods that must be called with 587 // this lock held have the prefix "LP". 588 @GuardedBy("mPackages") 589 final ArrayMap<String, PackageParser.Package> mPackages = 590 new ArrayMap<String, PackageParser.Package>(); 591 592 final ArrayMap<String, Set<String>> mKnownCodebase = 593 new ArrayMap<String, Set<String>>(); 594 595 // Tracks available target package names -> overlay package paths. 596 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 597 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 598 599 /** 600 * Tracks new system packages [received in an OTA] that we expect to 601 * find updated user-installed versions. Keys are package name, values 602 * are package location. 603 */ 604 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 605 /** 606 * Tracks high priority intent filters for protected actions. During boot, certain 607 * filter actions are protected and should never be allowed to have a high priority 608 * intent filter for them. However, there is one, and only one exception -- the 609 * setup wizard. It must be able to define a high priority intent filter for these 610 * actions to ensure there are no escapes from the wizard. We need to delay processing 611 * of these during boot as we need to look at all of the system packages in order 612 * to know which component is the setup wizard. 613 */ 614 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 615 /** 616 * Whether or not processing protected filters should be deferred. 617 */ 618 private boolean mDeferProtectedFilters = true; 619 620 /** 621 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 622 */ 623 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 624 /** 625 * Whether or not system app permissions should be promoted from install to runtime. 626 */ 627 boolean mPromoteSystemApps; 628 629 @GuardedBy("mPackages") 630 final Settings mSettings; 631 632 /** 633 * Set of package names that are currently "frozen", which means active 634 * surgery is being done on the code/data for that package. The platform 635 * will refuse to launch frozen packages to avoid race conditions. 636 * 637 * @see PackageFreezer 638 */ 639 @GuardedBy("mPackages") 640 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 641 642 final ProtectedPackages mProtectedPackages; 643 644 boolean mFirstBoot; 645 646 // System configuration read by SystemConfig. 647 final int[] mGlobalGids; 648 final SparseArray<ArraySet<String>> mSystemPermissions; 649 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 650 651 // If mac_permissions.xml was found for seinfo labeling. 652 boolean mFoundPolicyFile; 653 654 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 655 656 public static final class SharedLibraryEntry { 657 public final String path; 658 public final String apk; 659 660 SharedLibraryEntry(String _path, String _apk) { 661 path = _path; 662 apk = _apk; 663 } 664 } 665 666 // Currently known shared libraries. 667 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 668 new ArrayMap<String, SharedLibraryEntry>(); 669 670 // All available activities, for your resolving pleasure. 671 final ActivityIntentResolver mActivities = 672 new ActivityIntentResolver(); 673 674 // All available receivers, for your resolving pleasure. 675 final ActivityIntentResolver mReceivers = 676 new ActivityIntentResolver(); 677 678 // All available services, for your resolving pleasure. 679 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 680 681 // All available providers, for your resolving pleasure. 682 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 683 684 // Mapping from provider base names (first directory in content URI codePath) 685 // to the provider information. 686 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 687 new ArrayMap<String, PackageParser.Provider>(); 688 689 // Mapping from instrumentation class names to info about them. 690 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 691 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 692 693 // Mapping from permission names to info about them. 694 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 695 new ArrayMap<String, PackageParser.PermissionGroup>(); 696 697 // Packages whose data we have transfered into another package, thus 698 // should no longer exist. 699 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 700 701 // Broadcast actions that are only available to the system. 702 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 703 704 /** List of packages waiting for verification. */ 705 final SparseArray<PackageVerificationState> mPendingVerification 706 = new SparseArray<PackageVerificationState>(); 707 708 /** Set of packages associated with each app op permission. */ 709 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 710 711 final PackageInstallerService mInstallerService; 712 713 private final PackageDexOptimizer mPackageDexOptimizer; 714 715 private AtomicInteger mNextMoveId = new AtomicInteger(); 716 private final MoveCallbacks mMoveCallbacks; 717 718 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 719 720 // Cache of users who need badging. 721 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 722 723 /** Token for keys in mPendingVerification. */ 724 private int mPendingVerificationToken = 0; 725 726 volatile boolean mSystemReady; 727 volatile boolean mSafeMode; 728 volatile boolean mHasSystemUidErrors; 729 730 ApplicationInfo mAndroidApplication; 731 final ActivityInfo mResolveActivity = new ActivityInfo(); 732 final ResolveInfo mResolveInfo = new ResolveInfo(); 733 ComponentName mResolveComponentName; 734 PackageParser.Package mPlatformPackage; 735 ComponentName mCustomResolverComponentName; 736 737 boolean mResolverReplaced = false; 738 739 private final @Nullable ComponentName mIntentFilterVerifierComponent; 740 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 741 742 private int mIntentFilterVerificationToken = 0; 743 744 /** Component that knows whether or not an ephemeral application exists */ 745 final ComponentName mEphemeralResolverComponent; 746 /** The service connection to the ephemeral resolver */ 747 final EphemeralResolverConnection mEphemeralResolverConnection; 748 749 /** Component used to install ephemeral applications */ 750 final ComponentName mEphemeralInstallerComponent; 751 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 752 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 753 754 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 755 = new SparseArray<IntentFilterVerificationState>(); 756 757 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 758 759 // List of packages names to keep cached, even if they are uninstalled for all users 760 private List<String> mKeepUninstalledPackages; 761 762 private UserManagerInternal mUserManagerInternal; 763 764 private static class IFVerificationParams { 765 PackageParser.Package pkg; 766 boolean replacing; 767 int userId; 768 int verifierUid; 769 770 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 771 int _userId, int _verifierUid) { 772 pkg = _pkg; 773 replacing = _replacing; 774 userId = _userId; 775 replacing = _replacing; 776 verifierUid = _verifierUid; 777 } 778 } 779 780 private interface IntentFilterVerifier<T extends IntentFilter> { 781 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 782 T filter, String packageName); 783 void startVerifications(int userId); 784 void receiveVerificationResponse(int verificationId); 785 } 786 787 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 788 private Context mContext; 789 private ComponentName mIntentFilterVerifierComponent; 790 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 791 792 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 793 mContext = context; 794 mIntentFilterVerifierComponent = verifierComponent; 795 } 796 797 private String getDefaultScheme() { 798 return IntentFilter.SCHEME_HTTPS; 799 } 800 801 @Override 802 public void startVerifications(int userId) { 803 // Launch verifications requests 804 int count = mCurrentIntentFilterVerifications.size(); 805 for (int n=0; n<count; n++) { 806 int verificationId = mCurrentIntentFilterVerifications.get(n); 807 final IntentFilterVerificationState ivs = 808 mIntentFilterVerificationStates.get(verificationId); 809 810 String packageName = ivs.getPackageName(); 811 812 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 813 final int filterCount = filters.size(); 814 ArraySet<String> domainsSet = new ArraySet<>(); 815 for (int m=0; m<filterCount; m++) { 816 PackageParser.ActivityIntentInfo filter = filters.get(m); 817 domainsSet.addAll(filter.getHostsList()); 818 } 819 synchronized (mPackages) { 820 if (mSettings.createIntentFilterVerificationIfNeededLPw( 821 packageName, domainsSet) != null) { 822 scheduleWriteSettingsLocked(); 823 } 824 } 825 sendVerificationRequest(userId, verificationId, ivs); 826 } 827 mCurrentIntentFilterVerifications.clear(); 828 } 829 830 private void sendVerificationRequest(int userId, int verificationId, 831 IntentFilterVerificationState ivs) { 832 833 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 834 verificationIntent.putExtra( 835 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 836 verificationId); 837 verificationIntent.putExtra( 838 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 839 getDefaultScheme()); 840 verificationIntent.putExtra( 841 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 842 ivs.getHostsString()); 843 verificationIntent.putExtra( 844 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 845 ivs.getPackageName()); 846 verificationIntent.setComponent(mIntentFilterVerifierComponent); 847 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 848 849 UserHandle user = new UserHandle(userId); 850 mContext.sendBroadcastAsUser(verificationIntent, user); 851 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 852 "Sending IntentFilter verification broadcast"); 853 } 854 855 public void receiveVerificationResponse(int verificationId) { 856 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 857 858 final boolean verified = ivs.isVerified(); 859 860 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 861 final int count = filters.size(); 862 if (DEBUG_DOMAIN_VERIFICATION) { 863 Slog.i(TAG, "Received verification response " + verificationId 864 + " for " + count + " filters, verified=" + verified); 865 } 866 for (int n=0; n<count; n++) { 867 PackageParser.ActivityIntentInfo filter = filters.get(n); 868 filter.setVerified(verified); 869 870 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 871 + " verified with result:" + verified + " and hosts:" 872 + ivs.getHostsString()); 873 } 874 875 mIntentFilterVerificationStates.remove(verificationId); 876 877 final String packageName = ivs.getPackageName(); 878 IntentFilterVerificationInfo ivi = null; 879 880 synchronized (mPackages) { 881 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 882 } 883 if (ivi == null) { 884 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 885 + verificationId + " packageName:" + packageName); 886 return; 887 } 888 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 889 "Updating IntentFilterVerificationInfo for package " + packageName 890 +" verificationId:" + verificationId); 891 892 synchronized (mPackages) { 893 if (verified) { 894 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 895 } else { 896 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 897 } 898 scheduleWriteSettingsLocked(); 899 900 final int userId = ivs.getUserId(); 901 if (userId != UserHandle.USER_ALL) { 902 final int userStatus = 903 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 904 905 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 906 boolean needUpdate = false; 907 908 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 909 // already been set by the User thru the Disambiguation dialog 910 switch (userStatus) { 911 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 912 if (verified) { 913 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 914 } else { 915 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 916 } 917 needUpdate = true; 918 break; 919 920 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 921 if (verified) { 922 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 923 needUpdate = true; 924 } 925 break; 926 927 default: 928 // Nothing to do 929 } 930 931 if (needUpdate) { 932 mSettings.updateIntentFilterVerificationStatusLPw( 933 packageName, updatedStatus, userId); 934 scheduleWritePackageRestrictionsLocked(userId); 935 } 936 } 937 } 938 } 939 940 @Override 941 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 942 ActivityIntentInfo filter, String packageName) { 943 if (!hasValidDomains(filter)) { 944 return false; 945 } 946 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 947 if (ivs == null) { 948 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 949 packageName); 950 } 951 if (DEBUG_DOMAIN_VERIFICATION) { 952 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 953 } 954 ivs.addFilter(filter); 955 return true; 956 } 957 958 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 959 int userId, int verificationId, String packageName) { 960 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 961 verifierUid, userId, packageName); 962 ivs.setPendingState(); 963 synchronized (mPackages) { 964 mIntentFilterVerificationStates.append(verificationId, ivs); 965 mCurrentIntentFilterVerifications.add(verificationId); 966 } 967 return ivs; 968 } 969 } 970 971 private static boolean hasValidDomains(ActivityIntentInfo filter) { 972 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 973 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 974 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 975 } 976 977 // Set of pending broadcasts for aggregating enable/disable of components. 978 static class PendingPackageBroadcasts { 979 // for each user id, a map of <package name -> components within that package> 980 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 981 982 public PendingPackageBroadcasts() { 983 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 984 } 985 986 public ArrayList<String> get(int userId, String packageName) { 987 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 988 return packages.get(packageName); 989 } 990 991 public void put(int userId, String packageName, ArrayList<String> components) { 992 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 993 packages.put(packageName, components); 994 } 995 996 public void remove(int userId, String packageName) { 997 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 998 if (packages != null) { 999 packages.remove(packageName); 1000 } 1001 } 1002 1003 public void remove(int userId) { 1004 mUidMap.remove(userId); 1005 } 1006 1007 public int userIdCount() { 1008 return mUidMap.size(); 1009 } 1010 1011 public int userIdAt(int n) { 1012 return mUidMap.keyAt(n); 1013 } 1014 1015 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1016 return mUidMap.get(userId); 1017 } 1018 1019 public int size() { 1020 // total number of pending broadcast entries across all userIds 1021 int num = 0; 1022 for (int i = 0; i< mUidMap.size(); i++) { 1023 num += mUidMap.valueAt(i).size(); 1024 } 1025 return num; 1026 } 1027 1028 public void clear() { 1029 mUidMap.clear(); 1030 } 1031 1032 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1033 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1034 if (map == null) { 1035 map = new ArrayMap<String, ArrayList<String>>(); 1036 mUidMap.put(userId, map); 1037 } 1038 return map; 1039 } 1040 } 1041 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1042 1043 // Service Connection to remote media container service to copy 1044 // package uri's from external media onto secure containers 1045 // or internal storage. 1046 private IMediaContainerService mContainerService = null; 1047 1048 static final int SEND_PENDING_BROADCAST = 1; 1049 static final int MCS_BOUND = 3; 1050 static final int END_COPY = 4; 1051 static final int INIT_COPY = 5; 1052 static final int MCS_UNBIND = 6; 1053 static final int START_CLEANING_PACKAGE = 7; 1054 static final int FIND_INSTALL_LOC = 8; 1055 static final int POST_INSTALL = 9; 1056 static final int MCS_RECONNECT = 10; 1057 static final int MCS_GIVE_UP = 11; 1058 static final int UPDATED_MEDIA_STATUS = 12; 1059 static final int WRITE_SETTINGS = 13; 1060 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1061 static final int PACKAGE_VERIFIED = 15; 1062 static final int CHECK_PENDING_VERIFICATION = 16; 1063 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1064 static final int INTENT_FILTER_VERIFIED = 18; 1065 static final int WRITE_PACKAGE_LIST = 19; 1066 1067 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1068 1069 // Delay time in millisecs 1070 static final int BROADCAST_DELAY = 10 * 1000; 1071 1072 static UserManagerService sUserManager; 1073 1074 // Stores a list of users whose package restrictions file needs to be updated 1075 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1076 1077 final private DefaultContainerConnection mDefContainerConn = 1078 new DefaultContainerConnection(); 1079 class DefaultContainerConnection implements ServiceConnection { 1080 public void onServiceConnected(ComponentName name, IBinder service) { 1081 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1082 IMediaContainerService imcs = 1083 IMediaContainerService.Stub.asInterface(service); 1084 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1085 } 1086 1087 public void onServiceDisconnected(ComponentName name) { 1088 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1089 } 1090 } 1091 1092 // Recordkeeping of restore-after-install operations that are currently in flight 1093 // between the Package Manager and the Backup Manager 1094 static class PostInstallData { 1095 public InstallArgs args; 1096 public PackageInstalledInfo res; 1097 1098 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1099 args = _a; 1100 res = _r; 1101 } 1102 } 1103 1104 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1105 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1106 1107 // XML tags for backup/restore of various bits of state 1108 private static final String TAG_PREFERRED_BACKUP = "pa"; 1109 private static final String TAG_DEFAULT_APPS = "da"; 1110 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1111 1112 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1113 private static final String TAG_ALL_GRANTS = "rt-grants"; 1114 private static final String TAG_GRANT = "grant"; 1115 private static final String ATTR_PACKAGE_NAME = "pkg"; 1116 1117 private static final String TAG_PERMISSION = "perm"; 1118 private static final String ATTR_PERMISSION_NAME = "name"; 1119 private static final String ATTR_IS_GRANTED = "g"; 1120 private static final String ATTR_USER_SET = "set"; 1121 private static final String ATTR_USER_FIXED = "fixed"; 1122 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1123 1124 // System/policy permission grants are not backed up 1125 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1126 FLAG_PERMISSION_POLICY_FIXED 1127 | FLAG_PERMISSION_SYSTEM_FIXED 1128 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1129 1130 // And we back up these user-adjusted states 1131 private static final int USER_RUNTIME_GRANT_MASK = 1132 FLAG_PERMISSION_USER_SET 1133 | FLAG_PERMISSION_USER_FIXED 1134 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1135 1136 final @Nullable String mRequiredVerifierPackage; 1137 final @NonNull String mRequiredInstallerPackage; 1138 final @NonNull String mRequiredUninstallerPackage; 1139 final @Nullable String mSetupWizardPackage; 1140 final @Nullable String mStorageManagerPackage; 1141 final @NonNull String mServicesSystemSharedLibraryPackageName; 1142 final @NonNull String mSharedSystemSharedLibraryPackageName; 1143 1144 final boolean mPermissionReviewRequired; 1145 1146 private final PackageUsage mPackageUsage = new PackageUsage(); 1147 private final CompilerStats mCompilerStats = new CompilerStats(); 1148 1149 class PackageHandler extends Handler { 1150 private boolean mBound = false; 1151 final ArrayList<HandlerParams> mPendingInstalls = 1152 new ArrayList<HandlerParams>(); 1153 1154 private boolean connectToService() { 1155 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1156 " DefaultContainerService"); 1157 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1158 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1159 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1160 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1161 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1162 mBound = true; 1163 return true; 1164 } 1165 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1166 return false; 1167 } 1168 1169 private void disconnectService() { 1170 mContainerService = null; 1171 mBound = false; 1172 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1173 mContext.unbindService(mDefContainerConn); 1174 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1175 } 1176 1177 PackageHandler(Looper looper) { 1178 super(looper); 1179 } 1180 1181 public void handleMessage(Message msg) { 1182 try { 1183 doHandleMessage(msg); 1184 } finally { 1185 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1186 } 1187 } 1188 1189 void doHandleMessage(Message msg) { 1190 switch (msg.what) { 1191 case INIT_COPY: { 1192 HandlerParams params = (HandlerParams) msg.obj; 1193 int idx = mPendingInstalls.size(); 1194 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1195 // If a bind was already initiated we dont really 1196 // need to do anything. The pending install 1197 // will be processed later on. 1198 if (!mBound) { 1199 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1200 System.identityHashCode(mHandler)); 1201 // If this is the only one pending we might 1202 // have to bind to the service again. 1203 if (!connectToService()) { 1204 Slog.e(TAG, "Failed to bind to media container service"); 1205 params.serviceError(); 1206 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1207 System.identityHashCode(mHandler)); 1208 if (params.traceMethod != null) { 1209 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1210 params.traceCookie); 1211 } 1212 return; 1213 } else { 1214 // Once we bind to the service, the first 1215 // pending request will be processed. 1216 mPendingInstalls.add(idx, params); 1217 } 1218 } else { 1219 mPendingInstalls.add(idx, params); 1220 // Already bound to the service. Just make 1221 // sure we trigger off processing the first request. 1222 if (idx == 0) { 1223 mHandler.sendEmptyMessage(MCS_BOUND); 1224 } 1225 } 1226 break; 1227 } 1228 case MCS_BOUND: { 1229 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1230 if (msg.obj != null) { 1231 mContainerService = (IMediaContainerService) msg.obj; 1232 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1233 System.identityHashCode(mHandler)); 1234 } 1235 if (mContainerService == null) { 1236 if (!mBound) { 1237 // Something seriously wrong since we are not bound and we are not 1238 // waiting for connection. Bail out. 1239 Slog.e(TAG, "Cannot bind to media container service"); 1240 for (HandlerParams params : mPendingInstalls) { 1241 // Indicate service bind error 1242 params.serviceError(); 1243 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1244 System.identityHashCode(params)); 1245 if (params.traceMethod != null) { 1246 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1247 params.traceMethod, params.traceCookie); 1248 } 1249 return; 1250 } 1251 mPendingInstalls.clear(); 1252 } else { 1253 Slog.w(TAG, "Waiting to connect to media container service"); 1254 } 1255 } else if (mPendingInstalls.size() > 0) { 1256 HandlerParams params = mPendingInstalls.get(0); 1257 if (params != null) { 1258 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1259 System.identityHashCode(params)); 1260 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1261 if (params.startCopy()) { 1262 // We are done... look for more work or to 1263 // go idle. 1264 if (DEBUG_SD_INSTALL) Log.i(TAG, 1265 "Checking for more work or unbind..."); 1266 // Delete pending install 1267 if (mPendingInstalls.size() > 0) { 1268 mPendingInstalls.remove(0); 1269 } 1270 if (mPendingInstalls.size() == 0) { 1271 if (mBound) { 1272 if (DEBUG_SD_INSTALL) Log.i(TAG, 1273 "Posting delayed MCS_UNBIND"); 1274 removeMessages(MCS_UNBIND); 1275 Message ubmsg = obtainMessage(MCS_UNBIND); 1276 // Unbind after a little delay, to avoid 1277 // continual thrashing. 1278 sendMessageDelayed(ubmsg, 10000); 1279 } 1280 } else { 1281 // There are more pending requests in queue. 1282 // Just post MCS_BOUND message to trigger processing 1283 // of next pending install. 1284 if (DEBUG_SD_INSTALL) Log.i(TAG, 1285 "Posting MCS_BOUND for next work"); 1286 mHandler.sendEmptyMessage(MCS_BOUND); 1287 } 1288 } 1289 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1290 } 1291 } else { 1292 // Should never happen ideally. 1293 Slog.w(TAG, "Empty queue"); 1294 } 1295 break; 1296 } 1297 case MCS_RECONNECT: { 1298 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1299 if (mPendingInstalls.size() > 0) { 1300 if (mBound) { 1301 disconnectService(); 1302 } 1303 if (!connectToService()) { 1304 Slog.e(TAG, "Failed to bind to media container service"); 1305 for (HandlerParams params : mPendingInstalls) { 1306 // Indicate service bind error 1307 params.serviceError(); 1308 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1309 System.identityHashCode(params)); 1310 } 1311 mPendingInstalls.clear(); 1312 } 1313 } 1314 break; 1315 } 1316 case MCS_UNBIND: { 1317 // If there is no actual work left, then time to unbind. 1318 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1319 1320 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1321 if (mBound) { 1322 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1323 1324 disconnectService(); 1325 } 1326 } else if (mPendingInstalls.size() > 0) { 1327 // There are more pending requests in queue. 1328 // Just post MCS_BOUND message to trigger processing 1329 // of next pending install. 1330 mHandler.sendEmptyMessage(MCS_BOUND); 1331 } 1332 1333 break; 1334 } 1335 case MCS_GIVE_UP: { 1336 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1337 HandlerParams params = mPendingInstalls.remove(0); 1338 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1339 System.identityHashCode(params)); 1340 break; 1341 } 1342 case SEND_PENDING_BROADCAST: { 1343 String packages[]; 1344 ArrayList<String> components[]; 1345 int size = 0; 1346 int uids[]; 1347 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1348 synchronized (mPackages) { 1349 if (mPendingBroadcasts == null) { 1350 return; 1351 } 1352 size = mPendingBroadcasts.size(); 1353 if (size <= 0) { 1354 // Nothing to be done. Just return 1355 return; 1356 } 1357 packages = new String[size]; 1358 components = new ArrayList[size]; 1359 uids = new int[size]; 1360 int i = 0; // filling out the above arrays 1361 1362 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1363 int packageUserId = mPendingBroadcasts.userIdAt(n); 1364 Iterator<Map.Entry<String, ArrayList<String>>> it 1365 = mPendingBroadcasts.packagesForUserId(packageUserId) 1366 .entrySet().iterator(); 1367 while (it.hasNext() && i < size) { 1368 Map.Entry<String, ArrayList<String>> ent = it.next(); 1369 packages[i] = ent.getKey(); 1370 components[i] = ent.getValue(); 1371 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1372 uids[i] = (ps != null) 1373 ? UserHandle.getUid(packageUserId, ps.appId) 1374 : -1; 1375 i++; 1376 } 1377 } 1378 size = i; 1379 mPendingBroadcasts.clear(); 1380 } 1381 // Send broadcasts 1382 for (int i = 0; i < size; i++) { 1383 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1384 } 1385 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1386 break; 1387 } 1388 case START_CLEANING_PACKAGE: { 1389 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1390 final String packageName = (String)msg.obj; 1391 final int userId = msg.arg1; 1392 final boolean andCode = msg.arg2 != 0; 1393 synchronized (mPackages) { 1394 if (userId == UserHandle.USER_ALL) { 1395 int[] users = sUserManager.getUserIds(); 1396 for (int user : users) { 1397 mSettings.addPackageToCleanLPw( 1398 new PackageCleanItem(user, packageName, andCode)); 1399 } 1400 } else { 1401 mSettings.addPackageToCleanLPw( 1402 new PackageCleanItem(userId, packageName, andCode)); 1403 } 1404 } 1405 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1406 startCleaningPackages(); 1407 } break; 1408 case POST_INSTALL: { 1409 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1410 1411 PostInstallData data = mRunningInstalls.get(msg.arg1); 1412 final boolean didRestore = (msg.arg2 != 0); 1413 mRunningInstalls.delete(msg.arg1); 1414 1415 if (data != null) { 1416 InstallArgs args = data.args; 1417 PackageInstalledInfo parentRes = data.res; 1418 1419 final boolean grantPermissions = (args.installFlags 1420 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1421 final boolean killApp = (args.installFlags 1422 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1423 final String[] grantedPermissions = args.installGrantPermissions; 1424 1425 // Handle the parent package 1426 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1427 grantedPermissions, didRestore, args.installerPackageName, 1428 args.observer); 1429 1430 // Handle the child packages 1431 final int childCount = (parentRes.addedChildPackages != null) 1432 ? parentRes.addedChildPackages.size() : 0; 1433 for (int i = 0; i < childCount; i++) { 1434 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1435 handlePackagePostInstall(childRes, grantPermissions, killApp, 1436 grantedPermissions, false, args.installerPackageName, 1437 args.observer); 1438 } 1439 1440 // Log tracing if needed 1441 if (args.traceMethod != null) { 1442 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1443 args.traceCookie); 1444 } 1445 } else { 1446 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1447 } 1448 1449 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1450 } break; 1451 case UPDATED_MEDIA_STATUS: { 1452 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1453 boolean reportStatus = msg.arg1 == 1; 1454 boolean doGc = msg.arg2 == 1; 1455 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1456 if (doGc) { 1457 // Force a gc to clear up stale containers. 1458 Runtime.getRuntime().gc(); 1459 } 1460 if (msg.obj != null) { 1461 @SuppressWarnings("unchecked") 1462 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1463 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1464 // Unload containers 1465 unloadAllContainers(args); 1466 } 1467 if (reportStatus) { 1468 try { 1469 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1470 PackageHelper.getMountService().finishMediaUpdate(); 1471 } catch (RemoteException e) { 1472 Log.e(TAG, "MountService not running?"); 1473 } 1474 } 1475 } break; 1476 case WRITE_SETTINGS: { 1477 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1478 synchronized (mPackages) { 1479 removeMessages(WRITE_SETTINGS); 1480 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1481 mSettings.writeLPr(); 1482 mDirtyUsers.clear(); 1483 } 1484 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1485 } break; 1486 case WRITE_PACKAGE_RESTRICTIONS: { 1487 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1488 synchronized (mPackages) { 1489 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1490 for (int userId : mDirtyUsers) { 1491 mSettings.writePackageRestrictionsLPr(userId); 1492 } 1493 mDirtyUsers.clear(); 1494 } 1495 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1496 } break; 1497 case WRITE_PACKAGE_LIST: { 1498 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1499 synchronized (mPackages) { 1500 removeMessages(WRITE_PACKAGE_LIST); 1501 mSettings.writePackageListLPr(msg.arg1); 1502 } 1503 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1504 } break; 1505 case CHECK_PENDING_VERIFICATION: { 1506 final int verificationId = msg.arg1; 1507 final PackageVerificationState state = mPendingVerification.get(verificationId); 1508 1509 if ((state != null) && !state.timeoutExtended()) { 1510 final InstallArgs args = state.getInstallArgs(); 1511 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1512 1513 Slog.i(TAG, "Verification timed out for " + originUri); 1514 mPendingVerification.remove(verificationId); 1515 1516 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1517 1518 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1519 Slog.i(TAG, "Continuing with installation of " + originUri); 1520 state.setVerifierResponse(Binder.getCallingUid(), 1521 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1522 broadcastPackageVerified(verificationId, originUri, 1523 PackageManager.VERIFICATION_ALLOW, 1524 state.getInstallArgs().getUser()); 1525 try { 1526 ret = args.copyApk(mContainerService, true); 1527 } catch (RemoteException e) { 1528 Slog.e(TAG, "Could not contact the ContainerService"); 1529 } 1530 } else { 1531 broadcastPackageVerified(verificationId, originUri, 1532 PackageManager.VERIFICATION_REJECT, 1533 state.getInstallArgs().getUser()); 1534 } 1535 1536 Trace.asyncTraceEnd( 1537 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1538 1539 processPendingInstall(args, ret); 1540 mHandler.sendEmptyMessage(MCS_UNBIND); 1541 } 1542 break; 1543 } 1544 case PACKAGE_VERIFIED: { 1545 final int verificationId = msg.arg1; 1546 1547 final PackageVerificationState state = mPendingVerification.get(verificationId); 1548 if (state == null) { 1549 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1550 break; 1551 } 1552 1553 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1554 1555 state.setVerifierResponse(response.callerUid, response.code); 1556 1557 if (state.isVerificationComplete()) { 1558 mPendingVerification.remove(verificationId); 1559 1560 final InstallArgs args = state.getInstallArgs(); 1561 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1562 1563 int ret; 1564 if (state.isInstallAllowed()) { 1565 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1566 broadcastPackageVerified(verificationId, originUri, 1567 response.code, state.getInstallArgs().getUser()); 1568 try { 1569 ret = args.copyApk(mContainerService, true); 1570 } catch (RemoteException e) { 1571 Slog.e(TAG, "Could not contact the ContainerService"); 1572 } 1573 } else { 1574 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1575 } 1576 1577 Trace.asyncTraceEnd( 1578 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1579 1580 processPendingInstall(args, ret); 1581 mHandler.sendEmptyMessage(MCS_UNBIND); 1582 } 1583 1584 break; 1585 } 1586 case START_INTENT_FILTER_VERIFICATIONS: { 1587 IFVerificationParams params = (IFVerificationParams) msg.obj; 1588 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1589 params.replacing, params.pkg); 1590 break; 1591 } 1592 case INTENT_FILTER_VERIFIED: { 1593 final int verificationId = msg.arg1; 1594 1595 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1596 verificationId); 1597 if (state == null) { 1598 Slog.w(TAG, "Invalid IntentFilter verification token " 1599 + verificationId + " received"); 1600 break; 1601 } 1602 1603 final int userId = state.getUserId(); 1604 1605 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1606 "Processing IntentFilter verification with token:" 1607 + verificationId + " and userId:" + userId); 1608 1609 final IntentFilterVerificationResponse response = 1610 (IntentFilterVerificationResponse) msg.obj; 1611 1612 state.setVerifierResponse(response.callerUid, response.code); 1613 1614 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1615 "IntentFilter verification with token:" + verificationId 1616 + " and userId:" + userId 1617 + " is settings verifier response with response code:" 1618 + response.code); 1619 1620 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1621 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1622 + response.getFailedDomainsString()); 1623 } 1624 1625 if (state.isVerificationComplete()) { 1626 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1627 } else { 1628 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1629 "IntentFilter verification with token:" + verificationId 1630 + " was not said to be complete"); 1631 } 1632 1633 break; 1634 } 1635 } 1636 } 1637 } 1638 1639 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1640 boolean killApp, String[] grantedPermissions, 1641 boolean launchedForRestore, String installerPackage, 1642 IPackageInstallObserver2 installObserver) { 1643 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1644 // Send the removed broadcasts 1645 if (res.removedInfo != null) { 1646 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1647 } 1648 1649 // Now that we successfully installed the package, grant runtime 1650 // permissions if requested before broadcasting the install. 1651 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1652 >= Build.VERSION_CODES.M) { 1653 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1654 } 1655 1656 final boolean update = res.removedInfo != null 1657 && res.removedInfo.removedPackage != null; 1658 1659 // If this is the first time we have child packages for a disabled privileged 1660 // app that had no children, we grant requested runtime permissions to the new 1661 // children if the parent on the system image had them already granted. 1662 if (res.pkg.parentPackage != null) { 1663 synchronized (mPackages) { 1664 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1665 } 1666 } 1667 1668 synchronized (mPackages) { 1669 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1670 } 1671 1672 final String packageName = res.pkg.applicationInfo.packageName; 1673 Bundle extras = new Bundle(1); 1674 extras.putInt(Intent.EXTRA_UID, res.uid); 1675 1676 // Determine the set of users who are adding this package for 1677 // the first time vs. those who are seeing an update. 1678 int[] firstUsers = EMPTY_INT_ARRAY; 1679 int[] updateUsers = EMPTY_INT_ARRAY; 1680 if (res.origUsers == null || res.origUsers.length == 0) { 1681 firstUsers = res.newUsers; 1682 } else { 1683 for (int newUser : res.newUsers) { 1684 boolean isNew = true; 1685 for (int origUser : res.origUsers) { 1686 if (origUser == newUser) { 1687 isNew = false; 1688 break; 1689 } 1690 } 1691 if (isNew) { 1692 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1693 } else { 1694 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1695 } 1696 } 1697 } 1698 1699 // Send installed broadcasts if the install/update is not ephemeral 1700 if (!isEphemeral(res.pkg)) { 1701 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1702 1703 // Send added for users that see the package for the first time 1704 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1705 extras, 0 /*flags*/, null /*targetPackage*/, 1706 null /*finishedReceiver*/, firstUsers); 1707 1708 // Send added for users that don't see the package for the first time 1709 if (update) { 1710 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1711 } 1712 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1713 extras, 0 /*flags*/, null /*targetPackage*/, 1714 null /*finishedReceiver*/, updateUsers); 1715 1716 // Send replaced for users that don't see the package for the first time 1717 if (update) { 1718 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1719 packageName, extras, 0 /*flags*/, 1720 null /*targetPackage*/, null /*finishedReceiver*/, 1721 updateUsers); 1722 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1723 null /*package*/, null /*extras*/, 0 /*flags*/, 1724 packageName /*targetPackage*/, 1725 null /*finishedReceiver*/, updateUsers); 1726 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1727 // First-install and we did a restore, so we're responsible for the 1728 // first-launch broadcast. 1729 if (DEBUG_BACKUP) { 1730 Slog.i(TAG, "Post-restore of " + packageName 1731 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1732 } 1733 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1734 } 1735 1736 // Send broadcast package appeared if forward locked/external for all users 1737 // treat asec-hosted packages like removable media on upgrade 1738 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1739 if (DEBUG_INSTALL) { 1740 Slog.i(TAG, "upgrading pkg " + res.pkg 1741 + " is ASEC-hosted -> AVAILABLE"); 1742 } 1743 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1744 ArrayList<String> pkgList = new ArrayList<>(1); 1745 pkgList.add(packageName); 1746 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1747 } 1748 } 1749 1750 // Work that needs to happen on first install within each user 1751 if (firstUsers != null && firstUsers.length > 0) { 1752 synchronized (mPackages) { 1753 for (int userId : firstUsers) { 1754 // If this app is a browser and it's newly-installed for some 1755 // users, clear any default-browser state in those users. The 1756 // app's nature doesn't depend on the user, so we can just check 1757 // its browser nature in any user and generalize. 1758 if (packageIsBrowser(packageName, userId)) { 1759 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1760 } 1761 1762 // We may also need to apply pending (restored) runtime 1763 // permission grants within these users. 1764 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1765 } 1766 } 1767 } 1768 1769 // Log current value of "unknown sources" setting 1770 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1771 getUnknownSourcesSettings()); 1772 1773 // Force a gc to clear up things 1774 Runtime.getRuntime().gc(); 1775 1776 // Remove the replaced package's older resources safely now 1777 // We delete after a gc for applications on sdcard. 1778 if (res.removedInfo != null && res.removedInfo.args != null) { 1779 synchronized (mInstallLock) { 1780 res.removedInfo.args.doPostDeleteLI(true); 1781 } 1782 } 1783 } 1784 1785 // If someone is watching installs - notify them 1786 if (installObserver != null) { 1787 try { 1788 Bundle extras = extrasForInstallResult(res); 1789 installObserver.onPackageInstalled(res.name, res.returnCode, 1790 res.returnMsg, extras); 1791 } catch (RemoteException e) { 1792 Slog.i(TAG, "Observer no longer exists."); 1793 } 1794 } 1795 } 1796 1797 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1798 PackageParser.Package pkg) { 1799 if (pkg.parentPackage == null) { 1800 return; 1801 } 1802 if (pkg.requestedPermissions == null) { 1803 return; 1804 } 1805 final PackageSetting disabledSysParentPs = mSettings 1806 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1807 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1808 || !disabledSysParentPs.isPrivileged() 1809 || (disabledSysParentPs.childPackageNames != null 1810 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1811 return; 1812 } 1813 final int[] allUserIds = sUserManager.getUserIds(); 1814 final int permCount = pkg.requestedPermissions.size(); 1815 for (int i = 0; i < permCount; i++) { 1816 String permission = pkg.requestedPermissions.get(i); 1817 BasePermission bp = mSettings.mPermissions.get(permission); 1818 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1819 continue; 1820 } 1821 for (int userId : allUserIds) { 1822 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1823 permission, userId)) { 1824 grantRuntimePermission(pkg.packageName, permission, userId); 1825 } 1826 } 1827 } 1828 } 1829 1830 private StorageEventListener mStorageListener = new StorageEventListener() { 1831 @Override 1832 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1833 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1834 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1835 final String volumeUuid = vol.getFsUuid(); 1836 1837 // Clean up any users or apps that were removed or recreated 1838 // while this volume was missing 1839 reconcileUsers(volumeUuid); 1840 reconcileApps(volumeUuid); 1841 1842 // Clean up any install sessions that expired or were 1843 // cancelled while this volume was missing 1844 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1845 1846 loadPrivatePackages(vol); 1847 1848 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1849 unloadPrivatePackages(vol); 1850 } 1851 } 1852 1853 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1854 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1855 updateExternalMediaStatus(true, false); 1856 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1857 updateExternalMediaStatus(false, false); 1858 } 1859 } 1860 } 1861 1862 @Override 1863 public void onVolumeForgotten(String fsUuid) { 1864 if (TextUtils.isEmpty(fsUuid)) { 1865 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1866 return; 1867 } 1868 1869 // Remove any apps installed on the forgotten volume 1870 synchronized (mPackages) { 1871 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1872 for (PackageSetting ps : packages) { 1873 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1874 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1875 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1876 } 1877 1878 mSettings.onVolumeForgotten(fsUuid); 1879 mSettings.writeLPr(); 1880 } 1881 } 1882 }; 1883 1884 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1885 String[] grantedPermissions) { 1886 for (int userId : userIds) { 1887 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1888 } 1889 1890 // We could have touched GID membership, so flush out packages.list 1891 synchronized (mPackages) { 1892 mSettings.writePackageListLPr(); 1893 } 1894 } 1895 1896 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1897 String[] grantedPermissions) { 1898 SettingBase sb = (SettingBase) pkg.mExtras; 1899 if (sb == null) { 1900 return; 1901 } 1902 1903 PermissionsState permissionsState = sb.getPermissionsState(); 1904 1905 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1906 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1907 1908 for (String permission : pkg.requestedPermissions) { 1909 final BasePermission bp; 1910 synchronized (mPackages) { 1911 bp = mSettings.mPermissions.get(permission); 1912 } 1913 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1914 && (grantedPermissions == null 1915 || ArrayUtils.contains(grantedPermissions, permission))) { 1916 final int flags = permissionsState.getPermissionFlags(permission, userId); 1917 // Installer cannot change immutable permissions. 1918 if ((flags & immutableFlags) == 0) { 1919 grantRuntimePermission(pkg.packageName, permission, userId); 1920 } 1921 } 1922 } 1923 } 1924 1925 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1926 Bundle extras = null; 1927 switch (res.returnCode) { 1928 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1929 extras = new Bundle(); 1930 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1931 res.origPermission); 1932 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1933 res.origPackage); 1934 break; 1935 } 1936 case PackageManager.INSTALL_SUCCEEDED: { 1937 extras = new Bundle(); 1938 extras.putBoolean(Intent.EXTRA_REPLACING, 1939 res.removedInfo != null && res.removedInfo.removedPackage != null); 1940 break; 1941 } 1942 } 1943 return extras; 1944 } 1945 1946 void scheduleWriteSettingsLocked() { 1947 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1948 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1949 } 1950 } 1951 1952 void scheduleWritePackageListLocked(int userId) { 1953 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 1954 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 1955 msg.arg1 = userId; 1956 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 1957 } 1958 } 1959 1960 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1961 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1962 scheduleWritePackageRestrictionsLocked(userId); 1963 } 1964 1965 void scheduleWritePackageRestrictionsLocked(int userId) { 1966 final int[] userIds = (userId == UserHandle.USER_ALL) 1967 ? sUserManager.getUserIds() : new int[]{userId}; 1968 for (int nextUserId : userIds) { 1969 if (!sUserManager.exists(nextUserId)) return; 1970 mDirtyUsers.add(nextUserId); 1971 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1972 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1973 } 1974 } 1975 } 1976 1977 public static PackageManagerService main(Context context, Installer installer, 1978 boolean factoryTest, boolean onlyCore) { 1979 // Self-check for initial settings. 1980 PackageManagerServiceCompilerMapping.checkProperties(); 1981 1982 PackageManagerService m = new PackageManagerService(context, installer, 1983 factoryTest, onlyCore); 1984 m.enableSystemUserPackages(); 1985 ServiceManager.addService("package", m); 1986 return m; 1987 } 1988 1989 private void enableSystemUserPackages() { 1990 if (!UserManager.isSplitSystemUser()) { 1991 return; 1992 } 1993 // For system user, enable apps based on the following conditions: 1994 // - app is whitelisted or belong to one of these groups: 1995 // -- system app which has no launcher icons 1996 // -- system app which has INTERACT_ACROSS_USERS permission 1997 // -- system IME app 1998 // - app is not in the blacklist 1999 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2000 Set<String> enableApps = new ArraySet<>(); 2001 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2002 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2003 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2004 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2005 enableApps.addAll(wlApps); 2006 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2007 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2008 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2009 enableApps.removeAll(blApps); 2010 Log.i(TAG, "Applications installed for system user: " + enableApps); 2011 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2012 UserHandle.SYSTEM); 2013 final int allAppsSize = allAps.size(); 2014 synchronized (mPackages) { 2015 for (int i = 0; i < allAppsSize; i++) { 2016 String pName = allAps.get(i); 2017 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2018 // Should not happen, but we shouldn't be failing if it does 2019 if (pkgSetting == null) { 2020 continue; 2021 } 2022 boolean install = enableApps.contains(pName); 2023 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2024 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2025 + " for system user"); 2026 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2027 } 2028 } 2029 } 2030 } 2031 2032 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2033 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2034 Context.DISPLAY_SERVICE); 2035 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2036 } 2037 2038 /** 2039 * Requests that files preopted on a secondary system partition be copied to the data partition 2040 * if possible. Note that the actual copying of the files is accomplished by init for security 2041 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2042 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2043 */ 2044 private static void requestCopyPreoptedFiles() { 2045 final int WAIT_TIME_MS = 100; 2046 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2047 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2048 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2049 // We will wait for up to 100 seconds. 2050 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2051 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2052 try { 2053 Thread.sleep(WAIT_TIME_MS); 2054 } catch (InterruptedException e) { 2055 // Do nothing 2056 } 2057 if (SystemClock.uptimeMillis() > timeEnd) { 2058 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2059 Slog.wtf(TAG, "cppreopt did not finish!"); 2060 break; 2061 } 2062 } 2063 } 2064 } 2065 2066 public PackageManagerService(Context context, Installer installer, 2067 boolean factoryTest, boolean onlyCore) { 2068 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2069 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2070 SystemClock.uptimeMillis()); 2071 2072 if (mSdkVersion <= 0) { 2073 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2074 } 2075 2076 mContext = context; 2077 2078 mPermissionReviewRequired = context.getResources().getBoolean( 2079 R.bool.config_permissionReviewRequired); 2080 2081 mFactoryTest = factoryTest; 2082 mOnlyCore = onlyCore; 2083 mMetrics = new DisplayMetrics(); 2084 mSettings = new Settings(mPackages); 2085 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2086 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2087 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2088 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2089 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2090 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2091 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2092 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2093 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2094 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2095 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2096 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2097 2098 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2099 if (separateProcesses != null && separateProcesses.length() > 0) { 2100 if ("*".equals(separateProcesses)) { 2101 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2102 mSeparateProcesses = null; 2103 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2104 } else { 2105 mDefParseFlags = 0; 2106 mSeparateProcesses = separateProcesses.split(","); 2107 Slog.w(TAG, "Running with debug.separate_processes: " 2108 + separateProcesses); 2109 } 2110 } else { 2111 mDefParseFlags = 0; 2112 mSeparateProcesses = null; 2113 } 2114 2115 mInstaller = installer; 2116 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2117 "*dexopt*"); 2118 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2119 2120 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2121 FgThread.get().getLooper()); 2122 2123 getDefaultDisplayMetrics(context, mMetrics); 2124 2125 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2126 SystemConfig systemConfig = SystemConfig.getInstance(); 2127 mGlobalGids = systemConfig.getGlobalGids(); 2128 mSystemPermissions = systemConfig.getSystemPermissions(); 2129 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2130 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2131 2132 mProtectedPackages = new ProtectedPackages(mContext); 2133 2134 synchronized (mInstallLock) { 2135 // writer 2136 synchronized (mPackages) { 2137 mHandlerThread = new ServiceThread(TAG, 2138 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2139 mHandlerThread.start(); 2140 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2141 mProcessLoggingHandler = new ProcessLoggingHandler(); 2142 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2143 2144 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2145 2146 File dataDir = Environment.getDataDirectory(); 2147 mAppInstallDir = new File(dataDir, "app"); 2148 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2149 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2150 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2151 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2152 2153 sUserManager = new UserManagerService(context, this, mPackages); 2154 2155 // Propagate permission configuration in to package manager. 2156 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2157 = systemConfig.getPermissions(); 2158 for (int i=0; i<permConfig.size(); i++) { 2159 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2160 BasePermission bp = mSettings.mPermissions.get(perm.name); 2161 if (bp == null) { 2162 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2163 mSettings.mPermissions.put(perm.name, bp); 2164 } 2165 if (perm.gids != null) { 2166 bp.setGids(perm.gids, perm.perUser); 2167 } 2168 } 2169 2170 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2171 for (int i=0; i<libConfig.size(); i++) { 2172 mSharedLibraries.put(libConfig.keyAt(i), 2173 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2174 } 2175 2176 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2177 2178 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2179 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2180 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2181 2182 if (mFirstBoot) { 2183 requestCopyPreoptedFiles(); 2184 } 2185 2186 String customResolverActivity = Resources.getSystem().getString( 2187 R.string.config_customResolverActivity); 2188 if (TextUtils.isEmpty(customResolverActivity)) { 2189 customResolverActivity = null; 2190 } else { 2191 mCustomResolverComponentName = ComponentName.unflattenFromString( 2192 customResolverActivity); 2193 } 2194 2195 long startTime = SystemClock.uptimeMillis(); 2196 2197 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2198 startTime); 2199 2200 // Set flag to monitor and not change apk file paths when 2201 // scanning install directories. 2202 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2203 2204 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2205 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2206 2207 if (bootClassPath == null) { 2208 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2209 } 2210 2211 if (systemServerClassPath == null) { 2212 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2213 } 2214 2215 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2216 final String[] dexCodeInstructionSets = 2217 getDexCodeInstructionSets( 2218 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2219 2220 /** 2221 * Ensure all external libraries have had dexopt run on them. 2222 */ 2223 if (mSharedLibraries.size() > 0) { 2224 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2225 // NOTE: For now, we're compiling these system "shared libraries" 2226 // (and framework jars) into all available architectures. It's possible 2227 // to compile them only when we come across an app that uses them (there's 2228 // already logic for that in scanPackageLI) but that adds some complexity. 2229 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2230 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2231 final String lib = libEntry.path; 2232 if (lib == null) { 2233 continue; 2234 } 2235 2236 try { 2237 // Shared libraries do not have profiles so we perform a full 2238 // AOT compilation (if needed). 2239 int dexoptNeeded = DexFile.getDexOptNeeded( 2240 lib, dexCodeInstructionSet, 2241 getCompilerFilterForReason(REASON_SHARED_APK), 2242 false /* newProfile */); 2243 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2244 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2245 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2246 getCompilerFilterForReason(REASON_SHARED_APK), 2247 StorageManager.UUID_PRIVATE_INTERNAL, 2248 SKIP_SHARED_LIBRARY_CHECK); 2249 } 2250 } catch (FileNotFoundException e) { 2251 Slog.w(TAG, "Library not found: " + lib); 2252 } catch (IOException | InstallerException e) { 2253 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2254 + e.getMessage()); 2255 } 2256 } 2257 } 2258 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2259 } 2260 2261 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2262 2263 final VersionInfo ver = mSettings.getInternalVersion(); 2264 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2265 2266 // when upgrading from pre-M, promote system app permissions from install to runtime 2267 mPromoteSystemApps = 2268 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2269 2270 // When upgrading from pre-N, we need to handle package extraction like first boot, 2271 // as there is no profiling data available. 2272 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2273 2274 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2275 2276 // save off the names of pre-existing system packages prior to scanning; we don't 2277 // want to automatically grant runtime permissions for new system apps 2278 if (mPromoteSystemApps) { 2279 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2280 while (pkgSettingIter.hasNext()) { 2281 PackageSetting ps = pkgSettingIter.next(); 2282 if (isSystemApp(ps)) { 2283 mExistingSystemPackages.add(ps.name); 2284 } 2285 } 2286 } 2287 2288 // Collect vendor overlay packages. 2289 // (Do this before scanning any apps.) 2290 // For security and version matching reason, only consider 2291 // overlay packages if they reside in the right directory. 2292 File vendorOverlayDir; 2293 String overlaySkuDir = SystemProperties.get(VENDOR_OVERLAY_SKU_PROPERTY); 2294 if (!overlaySkuDir.isEmpty()) { 2295 vendorOverlayDir = new File(VENDOR_OVERLAY_DIR, overlaySkuDir); 2296 } else { 2297 vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2298 } 2299 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2300 | PackageParser.PARSE_IS_SYSTEM 2301 | PackageParser.PARSE_IS_SYSTEM_DIR 2302 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2303 2304 // Find base frameworks (resource packages without code). 2305 scanDirTracedLI(frameworkDir, mDefParseFlags 2306 | PackageParser.PARSE_IS_SYSTEM 2307 | PackageParser.PARSE_IS_SYSTEM_DIR 2308 | PackageParser.PARSE_IS_PRIVILEGED, 2309 scanFlags | SCAN_NO_DEX, 0); 2310 2311 // Collected privileged system packages. 2312 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2313 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2314 | PackageParser.PARSE_IS_SYSTEM 2315 | PackageParser.PARSE_IS_SYSTEM_DIR 2316 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2317 2318 // Collect ordinary system packages. 2319 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2320 scanDirTracedLI(systemAppDir, mDefParseFlags 2321 | PackageParser.PARSE_IS_SYSTEM 2322 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2323 2324 // Collect all vendor packages. 2325 File vendorAppDir = new File("/vendor/app"); 2326 try { 2327 vendorAppDir = vendorAppDir.getCanonicalFile(); 2328 } catch (IOException e) { 2329 // failed to look up canonical path, continue with original one 2330 } 2331 scanDirTracedLI(vendorAppDir, mDefParseFlags 2332 | PackageParser.PARSE_IS_SYSTEM 2333 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2334 2335 // Collect all OEM packages. 2336 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2337 scanDirTracedLI(oemAppDir, mDefParseFlags 2338 | PackageParser.PARSE_IS_SYSTEM 2339 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2340 2341 // Prune any system packages that no longer exist. 2342 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2343 if (!mOnlyCore) { 2344 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2345 while (psit.hasNext()) { 2346 PackageSetting ps = psit.next(); 2347 2348 /* 2349 * If this is not a system app, it can't be a 2350 * disable system app. 2351 */ 2352 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2353 continue; 2354 } 2355 2356 /* 2357 * If the package is scanned, it's not erased. 2358 */ 2359 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2360 if (scannedPkg != null) { 2361 /* 2362 * If the system app is both scanned and in the 2363 * disabled packages list, then it must have been 2364 * added via OTA. Remove it from the currently 2365 * scanned package so the previously user-installed 2366 * application can be scanned. 2367 */ 2368 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2369 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2370 + ps.name + "; removing system app. Last known codePath=" 2371 + ps.codePathString + ", installStatus=" + ps.installStatus 2372 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2373 + scannedPkg.mVersionCode); 2374 removePackageLI(scannedPkg, true); 2375 mExpectingBetter.put(ps.name, ps.codePath); 2376 } 2377 2378 continue; 2379 } 2380 2381 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2382 psit.remove(); 2383 logCriticalInfo(Log.WARN, "System package " + ps.name 2384 + " no longer exists; it's data will be wiped"); 2385 // Actual deletion of code and data will be handled by later 2386 // reconciliation step 2387 } else { 2388 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2389 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2390 possiblyDeletedUpdatedSystemApps.add(ps.name); 2391 } 2392 } 2393 } 2394 } 2395 2396 //look for any incomplete package installations 2397 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2398 for (int i = 0; i < deletePkgsList.size(); i++) { 2399 // Actual deletion of code and data will be handled by later 2400 // reconciliation step 2401 final String packageName = deletePkgsList.get(i).name; 2402 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2403 synchronized (mPackages) { 2404 mSettings.removePackageLPw(packageName); 2405 } 2406 } 2407 2408 //delete tmp files 2409 deleteTempPackageFiles(); 2410 2411 // Remove any shared userIDs that have no associated packages 2412 mSettings.pruneSharedUsersLPw(); 2413 2414 if (!mOnlyCore) { 2415 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2416 SystemClock.uptimeMillis()); 2417 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2418 2419 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2420 | PackageParser.PARSE_FORWARD_LOCK, 2421 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2422 2423 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2424 | PackageParser.PARSE_IS_EPHEMERAL, 2425 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2426 2427 /** 2428 * Remove disable package settings for any updated system 2429 * apps that were removed via an OTA. If they're not a 2430 * previously-updated app, remove them completely. 2431 * Otherwise, just revoke their system-level permissions. 2432 */ 2433 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2434 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2435 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2436 2437 String msg; 2438 if (deletedPkg == null) { 2439 msg = "Updated system package " + deletedAppName 2440 + " no longer exists; it's data will be wiped"; 2441 // Actual deletion of code and data will be handled by later 2442 // reconciliation step 2443 } else { 2444 msg = "Updated system app + " + deletedAppName 2445 + " no longer present; removing system privileges for " 2446 + deletedAppName; 2447 2448 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2449 2450 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2451 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2452 } 2453 logCriticalInfo(Log.WARN, msg); 2454 } 2455 2456 /** 2457 * Make sure all system apps that we expected to appear on 2458 * the userdata partition actually showed up. If they never 2459 * appeared, crawl back and revive the system version. 2460 */ 2461 for (int i = 0; i < mExpectingBetter.size(); i++) { 2462 final String packageName = mExpectingBetter.keyAt(i); 2463 if (!mPackages.containsKey(packageName)) { 2464 final File scanFile = mExpectingBetter.valueAt(i); 2465 2466 logCriticalInfo(Log.WARN, "Expected better " + packageName 2467 + " but never showed up; reverting to system"); 2468 2469 int reparseFlags = mDefParseFlags; 2470 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2471 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2472 | PackageParser.PARSE_IS_SYSTEM_DIR 2473 | PackageParser.PARSE_IS_PRIVILEGED; 2474 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2475 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2476 | PackageParser.PARSE_IS_SYSTEM_DIR; 2477 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2478 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2479 | PackageParser.PARSE_IS_SYSTEM_DIR; 2480 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2481 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2482 | PackageParser.PARSE_IS_SYSTEM_DIR; 2483 } else { 2484 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2485 continue; 2486 } 2487 2488 mSettings.enableSystemPackageLPw(packageName); 2489 2490 try { 2491 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2492 } catch (PackageManagerException e) { 2493 Slog.e(TAG, "Failed to parse original system package: " 2494 + e.getMessage()); 2495 } 2496 } 2497 } 2498 } 2499 mExpectingBetter.clear(); 2500 2501 // Resolve the storage manager. 2502 mStorageManagerPackage = getStorageManagerPackageName(); 2503 2504 // Resolve protected action filters. Only the setup wizard is allowed to 2505 // have a high priority filter for these actions. 2506 mSetupWizardPackage = getSetupWizardPackageName(); 2507 if (mProtectedFilters.size() > 0) { 2508 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2509 Slog.i(TAG, "No setup wizard;" 2510 + " All protected intents capped to priority 0"); 2511 } 2512 for (ActivityIntentInfo filter : mProtectedFilters) { 2513 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2514 if (DEBUG_FILTERS) { 2515 Slog.i(TAG, "Found setup wizard;" 2516 + " allow priority " + filter.getPriority() + ";" 2517 + " package: " + filter.activity.info.packageName 2518 + " activity: " + filter.activity.className 2519 + " priority: " + filter.getPriority()); 2520 } 2521 // skip setup wizard; allow it to keep the high priority filter 2522 continue; 2523 } 2524 Slog.w(TAG, "Protected action; cap priority to 0;" 2525 + " package: " + filter.activity.info.packageName 2526 + " activity: " + filter.activity.className 2527 + " origPrio: " + filter.getPriority()); 2528 filter.setPriority(0); 2529 } 2530 } 2531 mDeferProtectedFilters = false; 2532 mProtectedFilters.clear(); 2533 2534 // Now that we know all of the shared libraries, update all clients to have 2535 // the correct library paths. 2536 updateAllSharedLibrariesLPw(); 2537 2538 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2539 // NOTE: We ignore potential failures here during a system scan (like 2540 // the rest of the commands above) because there's precious little we 2541 // can do about it. A settings error is reported, though. 2542 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2543 false /* boot complete */); 2544 } 2545 2546 // Now that we know all the packages we are keeping, 2547 // read and update their last usage times. 2548 mPackageUsage.read(mPackages); 2549 mCompilerStats.read(); 2550 2551 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2552 SystemClock.uptimeMillis()); 2553 Slog.i(TAG, "Time to scan packages: " 2554 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2555 + " seconds"); 2556 2557 // If the platform SDK has changed since the last time we booted, 2558 // we need to re-grant app permission to catch any new ones that 2559 // appear. This is really a hack, and means that apps can in some 2560 // cases get permissions that the user didn't initially explicitly 2561 // allow... it would be nice to have some better way to handle 2562 // this situation. 2563 int updateFlags = UPDATE_PERMISSIONS_ALL; 2564 if (ver.sdkVersion != mSdkVersion) { 2565 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2566 + mSdkVersion + "; regranting permissions for internal storage"); 2567 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2568 } 2569 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2570 ver.sdkVersion = mSdkVersion; 2571 2572 // If this is the first boot or an update from pre-M, and it is a normal 2573 // boot, then we need to initialize the default preferred apps across 2574 // all defined users. 2575 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2576 for (UserInfo user : sUserManager.getUsers(true)) { 2577 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2578 applyFactoryDefaultBrowserLPw(user.id); 2579 primeDomainVerificationsLPw(user.id); 2580 } 2581 } 2582 2583 // Prepare storage for system user really early during boot, 2584 // since core system apps like SettingsProvider and SystemUI 2585 // can't wait for user to start 2586 final int storageFlags; 2587 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2588 storageFlags = StorageManager.FLAG_STORAGE_DE; 2589 } else { 2590 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2591 } 2592 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2593 storageFlags, true /* migrateAppData */); 2594 2595 // If this is first boot after an OTA, and a normal boot, then 2596 // we need to clear code cache directories. 2597 // Note that we do *not* clear the application profiles. These remain valid 2598 // across OTAs and are used to drive profile verification (post OTA) and 2599 // profile compilation (without waiting to collect a fresh set of profiles). 2600 if (mIsUpgrade && !onlyCore) { 2601 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2602 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2603 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2604 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2605 // No apps are running this early, so no need to freeze 2606 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2607 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2608 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2609 } 2610 } 2611 ver.fingerprint = Build.FINGERPRINT; 2612 } 2613 2614 checkDefaultBrowser(); 2615 2616 // clear only after permissions and other defaults have been updated 2617 mExistingSystemPackages.clear(); 2618 mPromoteSystemApps = false; 2619 2620 // All the changes are done during package scanning. 2621 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2622 2623 // can downgrade to reader 2624 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2625 mSettings.writeLPr(); 2626 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2627 2628 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2629 // early on (before the package manager declares itself as early) because other 2630 // components in the system server might ask for package contexts for these apps. 2631 // 2632 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2633 // (i.e, that the data partition is unavailable). 2634 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2635 long start = System.nanoTime(); 2636 List<PackageParser.Package> coreApps = new ArrayList<>(); 2637 for (PackageParser.Package pkg : mPackages.values()) { 2638 if (pkg.coreApp) { 2639 coreApps.add(pkg); 2640 } 2641 } 2642 2643 int[] stats = performDexOptUpgrade(coreApps, false, 2644 getCompilerFilterForReason(REASON_CORE_APP)); 2645 2646 final int elapsedTimeSeconds = 2647 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2648 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2649 2650 if (DEBUG_DEXOPT) { 2651 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2652 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2653 } 2654 2655 2656 // TODO: Should we log these stats to tron too ? 2657 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2658 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2659 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2660 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2661 } 2662 2663 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2664 SystemClock.uptimeMillis()); 2665 2666 if (!mOnlyCore) { 2667 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2668 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2669 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2670 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2671 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2672 mIntentFilterVerifierComponent); 2673 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2674 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2675 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2676 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2677 } else { 2678 mRequiredVerifierPackage = null; 2679 mRequiredInstallerPackage = null; 2680 mRequiredUninstallerPackage = null; 2681 mIntentFilterVerifierComponent = null; 2682 mIntentFilterVerifier = null; 2683 mServicesSystemSharedLibraryPackageName = null; 2684 mSharedSystemSharedLibraryPackageName = null; 2685 } 2686 2687 mInstallerService = new PackageInstallerService(context, this); 2688 2689 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2690 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2691 // both the installer and resolver must be present to enable ephemeral 2692 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2693 if (DEBUG_EPHEMERAL) { 2694 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2695 + " installer:" + ephemeralInstallerComponent); 2696 } 2697 mEphemeralResolverComponent = ephemeralResolverComponent; 2698 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2699 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2700 mEphemeralResolverConnection = 2701 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2702 } else { 2703 if (DEBUG_EPHEMERAL) { 2704 final String missingComponent = 2705 (ephemeralResolverComponent == null) 2706 ? (ephemeralInstallerComponent == null) 2707 ? "resolver and installer" 2708 : "resolver" 2709 : "installer"; 2710 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2711 } 2712 mEphemeralResolverComponent = null; 2713 mEphemeralInstallerComponent = null; 2714 mEphemeralResolverConnection = null; 2715 } 2716 2717 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2718 } // synchronized (mPackages) 2719 } // synchronized (mInstallLock) 2720 2721 // Now after opening every single application zip, make sure they 2722 // are all flushed. Not really needed, but keeps things nice and 2723 // tidy. 2724 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2725 Runtime.getRuntime().gc(); 2726 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2727 2728 // The initial scanning above does many calls into installd while 2729 // holding the mPackages lock, but we're mostly interested in yelling 2730 // once we have a booted system. 2731 mInstaller.setWarnIfHeld(mPackages); 2732 2733 // Expose private service for system components to use. 2734 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2735 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2736 } 2737 2738 @Override 2739 public boolean isFirstBoot() { 2740 return mFirstBoot; 2741 } 2742 2743 @Override 2744 public boolean isOnlyCoreApps() { 2745 return mOnlyCore; 2746 } 2747 2748 @Override 2749 public boolean isUpgrade() { 2750 return mIsUpgrade; 2751 } 2752 2753 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2754 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2755 2756 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2757 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2758 UserHandle.USER_SYSTEM); 2759 if (matches.size() == 1) { 2760 return matches.get(0).getComponentInfo().packageName; 2761 } else if (matches.size() == 0) { 2762 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2763 return null; 2764 } 2765 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2766 } 2767 2768 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2769 synchronized (mPackages) { 2770 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2771 if (libraryEntry == null) { 2772 throw new IllegalStateException("Missing required shared library:" + libraryName); 2773 } 2774 return libraryEntry.apk; 2775 } 2776 } 2777 2778 private @NonNull String getRequiredInstallerLPr() { 2779 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2780 intent.addCategory(Intent.CATEGORY_DEFAULT); 2781 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2782 2783 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2784 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2785 UserHandle.USER_SYSTEM); 2786 if (matches.size() == 1) { 2787 ResolveInfo resolveInfo = matches.get(0); 2788 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2789 throw new RuntimeException("The installer must be a privileged app"); 2790 } 2791 return matches.get(0).getComponentInfo().packageName; 2792 } else { 2793 throw new RuntimeException("There must be exactly one installer; found " + matches); 2794 } 2795 } 2796 2797 private @NonNull String getRequiredUninstallerLPr() { 2798 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2799 intent.addCategory(Intent.CATEGORY_DEFAULT); 2800 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2801 2802 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2803 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2804 UserHandle.USER_SYSTEM); 2805 if (resolveInfo == null || 2806 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2807 throw new RuntimeException("There must be exactly one uninstaller; found " 2808 + resolveInfo); 2809 } 2810 return resolveInfo.getComponentInfo().packageName; 2811 } 2812 2813 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2814 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2815 2816 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2817 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2818 UserHandle.USER_SYSTEM); 2819 ResolveInfo best = null; 2820 final int N = matches.size(); 2821 for (int i = 0; i < N; i++) { 2822 final ResolveInfo cur = matches.get(i); 2823 final String packageName = cur.getComponentInfo().packageName; 2824 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2825 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2826 continue; 2827 } 2828 2829 if (best == null || cur.priority > best.priority) { 2830 best = cur; 2831 } 2832 } 2833 2834 if (best != null) { 2835 return best.getComponentInfo().getComponentName(); 2836 } else { 2837 throw new RuntimeException("There must be at least one intent filter verifier"); 2838 } 2839 } 2840 2841 private @Nullable ComponentName getEphemeralResolverLPr() { 2842 final String[] packageArray = 2843 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2844 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2845 if (DEBUG_EPHEMERAL) { 2846 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2847 } 2848 return null; 2849 } 2850 2851 final int resolveFlags = 2852 MATCH_DIRECT_BOOT_AWARE 2853 | MATCH_DIRECT_BOOT_UNAWARE 2854 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2855 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2856 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2857 resolveFlags, UserHandle.USER_SYSTEM); 2858 2859 final int N = resolvers.size(); 2860 if (N == 0) { 2861 if (DEBUG_EPHEMERAL) { 2862 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2863 } 2864 return null; 2865 } 2866 2867 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2868 for (int i = 0; i < N; i++) { 2869 final ResolveInfo info = resolvers.get(i); 2870 2871 if (info.serviceInfo == null) { 2872 continue; 2873 } 2874 2875 final String packageName = info.serviceInfo.packageName; 2876 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2877 if (DEBUG_EPHEMERAL) { 2878 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2879 + " pkg: " + packageName + ", info:" + info); 2880 } 2881 continue; 2882 } 2883 2884 if (DEBUG_EPHEMERAL) { 2885 Slog.v(TAG, "Ephemeral resolver found;" 2886 + " pkg: " + packageName + ", info:" + info); 2887 } 2888 return new ComponentName(packageName, info.serviceInfo.name); 2889 } 2890 if (DEBUG_EPHEMERAL) { 2891 Slog.v(TAG, "Ephemeral resolver NOT found"); 2892 } 2893 return null; 2894 } 2895 2896 private @Nullable ComponentName getEphemeralInstallerLPr() { 2897 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2898 intent.addCategory(Intent.CATEGORY_DEFAULT); 2899 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2900 2901 final int resolveFlags = 2902 MATCH_DIRECT_BOOT_AWARE 2903 | MATCH_DIRECT_BOOT_UNAWARE 2904 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2905 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2906 resolveFlags, UserHandle.USER_SYSTEM); 2907 if (matches.size() == 0) { 2908 return null; 2909 } else if (matches.size() == 1) { 2910 return matches.get(0).getComponentInfo().getComponentName(); 2911 } else { 2912 throw new RuntimeException( 2913 "There must be at most one ephemeral installer; found " + matches); 2914 } 2915 } 2916 2917 private void primeDomainVerificationsLPw(int userId) { 2918 if (DEBUG_DOMAIN_VERIFICATION) { 2919 Slog.d(TAG, "Priming domain verifications in user " + userId); 2920 } 2921 2922 SystemConfig systemConfig = SystemConfig.getInstance(); 2923 ArraySet<String> packages = systemConfig.getLinkedApps(); 2924 2925 for (String packageName : packages) { 2926 PackageParser.Package pkg = mPackages.get(packageName); 2927 if (pkg != null) { 2928 if (!pkg.isSystemApp()) { 2929 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2930 continue; 2931 } 2932 2933 ArraySet<String> domains = null; 2934 for (PackageParser.Activity a : pkg.activities) { 2935 for (ActivityIntentInfo filter : a.intents) { 2936 if (hasValidDomains(filter)) { 2937 if (domains == null) { 2938 domains = new ArraySet<String>(); 2939 } 2940 domains.addAll(filter.getHostsList()); 2941 } 2942 } 2943 } 2944 2945 if (domains != null && domains.size() > 0) { 2946 if (DEBUG_DOMAIN_VERIFICATION) { 2947 Slog.v(TAG, " + " + packageName); 2948 } 2949 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2950 // state w.r.t. the formal app-linkage "no verification attempted" state; 2951 // and then 'always' in the per-user state actually used for intent resolution. 2952 final IntentFilterVerificationInfo ivi; 2953 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 2954 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2955 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2956 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2957 } else { 2958 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2959 + "' does not handle web links"); 2960 } 2961 } else { 2962 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2963 } 2964 } 2965 2966 scheduleWritePackageRestrictionsLocked(userId); 2967 scheduleWriteSettingsLocked(); 2968 } 2969 2970 private void applyFactoryDefaultBrowserLPw(int userId) { 2971 // The default browser app's package name is stored in a string resource, 2972 // with a product-specific overlay used for vendor customization. 2973 String browserPkg = mContext.getResources().getString( 2974 com.android.internal.R.string.default_browser); 2975 if (!TextUtils.isEmpty(browserPkg)) { 2976 // non-empty string => required to be a known package 2977 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2978 if (ps == null) { 2979 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2980 browserPkg = null; 2981 } else { 2982 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2983 } 2984 } 2985 2986 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2987 // default. If there's more than one, just leave everything alone. 2988 if (browserPkg == null) { 2989 calculateDefaultBrowserLPw(userId); 2990 } 2991 } 2992 2993 private void calculateDefaultBrowserLPw(int userId) { 2994 List<String> allBrowsers = resolveAllBrowserApps(userId); 2995 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2996 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2997 } 2998 2999 private List<String> resolveAllBrowserApps(int userId) { 3000 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3001 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3002 PackageManager.MATCH_ALL, userId); 3003 3004 final int count = list.size(); 3005 List<String> result = new ArrayList<String>(count); 3006 for (int i=0; i<count; i++) { 3007 ResolveInfo info = list.get(i); 3008 if (info.activityInfo == null 3009 || !info.handleAllWebDataURI 3010 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3011 || result.contains(info.activityInfo.packageName)) { 3012 continue; 3013 } 3014 result.add(info.activityInfo.packageName); 3015 } 3016 3017 return result; 3018 } 3019 3020 private boolean packageIsBrowser(String packageName, int userId) { 3021 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3022 PackageManager.MATCH_ALL, userId); 3023 final int N = list.size(); 3024 for (int i = 0; i < N; i++) { 3025 ResolveInfo info = list.get(i); 3026 if (packageName.equals(info.activityInfo.packageName)) { 3027 return true; 3028 } 3029 } 3030 return false; 3031 } 3032 3033 private void checkDefaultBrowser() { 3034 final int myUserId = UserHandle.myUserId(); 3035 final String packageName = getDefaultBrowserPackageName(myUserId); 3036 if (packageName != null) { 3037 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3038 if (info == null) { 3039 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3040 synchronized (mPackages) { 3041 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3042 } 3043 } 3044 } 3045 } 3046 3047 @Override 3048 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3049 throws RemoteException { 3050 try { 3051 return super.onTransact(code, data, reply, flags); 3052 } catch (RuntimeException e) { 3053 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3054 Slog.wtf(TAG, "Package Manager Crash", e); 3055 } 3056 throw e; 3057 } 3058 } 3059 3060 static int[] appendInts(int[] cur, int[] add) { 3061 if (add == null) return cur; 3062 if (cur == null) return add; 3063 final int N = add.length; 3064 for (int i=0; i<N; i++) { 3065 cur = appendInt(cur, add[i]); 3066 } 3067 return cur; 3068 } 3069 3070 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3071 if (!sUserManager.exists(userId)) return null; 3072 if (ps == null) { 3073 return null; 3074 } 3075 final PackageParser.Package p = ps.pkg; 3076 if (p == null) { 3077 return null; 3078 } 3079 3080 final PermissionsState permissionsState = ps.getPermissionsState(); 3081 3082 // Compute GIDs only if requested 3083 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3084 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3085 // Compute granted permissions only if package has requested permissions 3086 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3087 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3088 final PackageUserState state = ps.readUserState(userId); 3089 3090 return PackageParser.generatePackageInfo(p, gids, flags, 3091 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3092 } 3093 3094 @Override 3095 public void checkPackageStartable(String packageName, int userId) { 3096 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3097 3098 synchronized (mPackages) { 3099 final PackageSetting ps = mSettings.mPackages.get(packageName); 3100 if (ps == null) { 3101 throw new SecurityException("Package " + packageName + " was not found!"); 3102 } 3103 3104 if (!ps.getInstalled(userId)) { 3105 throw new SecurityException( 3106 "Package " + packageName + " was not installed for user " + userId + "!"); 3107 } 3108 3109 if (mSafeMode && !ps.isSystem()) { 3110 throw new SecurityException("Package " + packageName + " not a system app!"); 3111 } 3112 3113 if (mFrozenPackages.contains(packageName)) { 3114 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3115 } 3116 3117 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3118 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3119 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3120 } 3121 } 3122 } 3123 3124 @Override 3125 public boolean isPackageAvailable(String packageName, int userId) { 3126 if (!sUserManager.exists(userId)) return false; 3127 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3128 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3129 synchronized (mPackages) { 3130 PackageParser.Package p = mPackages.get(packageName); 3131 if (p != null) { 3132 final PackageSetting ps = (PackageSetting) p.mExtras; 3133 if (ps != null) { 3134 final PackageUserState state = ps.readUserState(userId); 3135 if (state != null) { 3136 return PackageParser.isAvailable(state); 3137 } 3138 } 3139 } 3140 } 3141 return false; 3142 } 3143 3144 @Override 3145 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3146 if (!sUserManager.exists(userId)) return null; 3147 flags = updateFlagsForPackage(flags, userId, packageName); 3148 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3149 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3150 // reader 3151 synchronized (mPackages) { 3152 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3153 PackageParser.Package p = null; 3154 if (matchFactoryOnly) { 3155 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3156 if (ps != null) { 3157 return generatePackageInfo(ps, flags, userId); 3158 } 3159 } 3160 if (p == null) { 3161 p = mPackages.get(packageName); 3162 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3163 return null; 3164 } 3165 } 3166 if (DEBUG_PACKAGE_INFO) 3167 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3168 if (p != null) { 3169 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3170 } 3171 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3172 final PackageSetting ps = mSettings.mPackages.get(packageName); 3173 return generatePackageInfo(ps, flags, userId); 3174 } 3175 } 3176 return null; 3177 } 3178 3179 @Override 3180 public String[] currentToCanonicalPackageNames(String[] names) { 3181 String[] out = new String[names.length]; 3182 // reader 3183 synchronized (mPackages) { 3184 for (int i=names.length-1; i>=0; i--) { 3185 PackageSetting ps = mSettings.mPackages.get(names[i]); 3186 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3187 } 3188 } 3189 return out; 3190 } 3191 3192 @Override 3193 public String[] canonicalToCurrentPackageNames(String[] names) { 3194 String[] out = new String[names.length]; 3195 // reader 3196 synchronized (mPackages) { 3197 for (int i=names.length-1; i>=0; i--) { 3198 String cur = mSettings.getRenamedPackageLPr(names[i]); 3199 out[i] = cur != null ? cur : names[i]; 3200 } 3201 } 3202 return out; 3203 } 3204 3205 @Override 3206 public int getPackageUid(String packageName, int flags, int userId) { 3207 if (!sUserManager.exists(userId)) return -1; 3208 flags = updateFlagsForPackage(flags, userId, packageName); 3209 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3210 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3211 3212 // reader 3213 synchronized (mPackages) { 3214 final PackageParser.Package p = mPackages.get(packageName); 3215 if (p != null && p.isMatch(flags)) { 3216 return UserHandle.getUid(userId, p.applicationInfo.uid); 3217 } 3218 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3219 final PackageSetting ps = mSettings.mPackages.get(packageName); 3220 if (ps != null && ps.isMatch(flags)) { 3221 return UserHandle.getUid(userId, ps.appId); 3222 } 3223 } 3224 } 3225 3226 return -1; 3227 } 3228 3229 @Override 3230 public int[] getPackageGids(String packageName, int flags, int userId) { 3231 if (!sUserManager.exists(userId)) return null; 3232 flags = updateFlagsForPackage(flags, userId, packageName); 3233 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3234 false /* requireFullPermission */, false /* checkShell */, 3235 "getPackageGids"); 3236 3237 // reader 3238 synchronized (mPackages) { 3239 final PackageParser.Package p = mPackages.get(packageName); 3240 if (p != null && p.isMatch(flags)) { 3241 PackageSetting ps = (PackageSetting) p.mExtras; 3242 return ps.getPermissionsState().computeGids(userId); 3243 } 3244 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3245 final PackageSetting ps = mSettings.mPackages.get(packageName); 3246 if (ps != null && ps.isMatch(flags)) { 3247 return ps.getPermissionsState().computeGids(userId); 3248 } 3249 } 3250 } 3251 3252 return null; 3253 } 3254 3255 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3256 if (bp.perm != null) { 3257 return PackageParser.generatePermissionInfo(bp.perm, flags); 3258 } 3259 PermissionInfo pi = new PermissionInfo(); 3260 pi.name = bp.name; 3261 pi.packageName = bp.sourcePackage; 3262 pi.nonLocalizedLabel = bp.name; 3263 pi.protectionLevel = bp.protectionLevel; 3264 return pi; 3265 } 3266 3267 @Override 3268 public PermissionInfo getPermissionInfo(String name, int flags) { 3269 // reader 3270 synchronized (mPackages) { 3271 final BasePermission p = mSettings.mPermissions.get(name); 3272 if (p != null) { 3273 return generatePermissionInfo(p, flags); 3274 } 3275 return null; 3276 } 3277 } 3278 3279 @Override 3280 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3281 int flags) { 3282 // reader 3283 synchronized (mPackages) { 3284 if (group != null && !mPermissionGroups.containsKey(group)) { 3285 // This is thrown as NameNotFoundException 3286 return null; 3287 } 3288 3289 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3290 for (BasePermission p : mSettings.mPermissions.values()) { 3291 if (group == null) { 3292 if (p.perm == null || p.perm.info.group == null) { 3293 out.add(generatePermissionInfo(p, flags)); 3294 } 3295 } else { 3296 if (p.perm != null && group.equals(p.perm.info.group)) { 3297 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3298 } 3299 } 3300 } 3301 return new ParceledListSlice<>(out); 3302 } 3303 } 3304 3305 @Override 3306 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3307 // reader 3308 synchronized (mPackages) { 3309 return PackageParser.generatePermissionGroupInfo( 3310 mPermissionGroups.get(name), flags); 3311 } 3312 } 3313 3314 @Override 3315 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3316 // reader 3317 synchronized (mPackages) { 3318 final int N = mPermissionGroups.size(); 3319 ArrayList<PermissionGroupInfo> out 3320 = new ArrayList<PermissionGroupInfo>(N); 3321 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3322 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3323 } 3324 return new ParceledListSlice<>(out); 3325 } 3326 } 3327 3328 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3329 int userId) { 3330 if (!sUserManager.exists(userId)) return null; 3331 PackageSetting ps = mSettings.mPackages.get(packageName); 3332 if (ps != null) { 3333 if (ps.pkg == null) { 3334 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3335 if (pInfo != null) { 3336 return pInfo.applicationInfo; 3337 } 3338 return null; 3339 } 3340 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3341 ps.readUserState(userId), userId); 3342 } 3343 return null; 3344 } 3345 3346 @Override 3347 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3348 if (!sUserManager.exists(userId)) return null; 3349 flags = updateFlagsForApplication(flags, userId, packageName); 3350 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3351 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3352 // writer 3353 synchronized (mPackages) { 3354 PackageParser.Package p = mPackages.get(packageName); 3355 if (DEBUG_PACKAGE_INFO) Log.v( 3356 TAG, "getApplicationInfo " + packageName 3357 + ": " + p); 3358 if (p != null) { 3359 PackageSetting ps = mSettings.mPackages.get(packageName); 3360 if (ps == null) return null; 3361 // Note: isEnabledLP() does not apply here - always return info 3362 return PackageParser.generateApplicationInfo( 3363 p, flags, ps.readUserState(userId), userId); 3364 } 3365 if ("android".equals(packageName)||"system".equals(packageName)) { 3366 return mAndroidApplication; 3367 } 3368 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3369 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3370 } 3371 } 3372 return null; 3373 } 3374 3375 @Override 3376 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3377 final IPackageDataObserver observer) { 3378 mContext.enforceCallingOrSelfPermission( 3379 android.Manifest.permission.CLEAR_APP_CACHE, null); 3380 // Queue up an async operation since clearing cache may take a little while. 3381 mHandler.post(new Runnable() { 3382 public void run() { 3383 mHandler.removeCallbacks(this); 3384 boolean success = true; 3385 synchronized (mInstallLock) { 3386 try { 3387 mInstaller.freeCache(volumeUuid, freeStorageSize); 3388 } catch (InstallerException e) { 3389 Slog.w(TAG, "Couldn't clear application caches: " + e); 3390 success = false; 3391 } 3392 } 3393 if (observer != null) { 3394 try { 3395 observer.onRemoveCompleted(null, success); 3396 } catch (RemoteException e) { 3397 Slog.w(TAG, "RemoveException when invoking call back"); 3398 } 3399 } 3400 } 3401 }); 3402 } 3403 3404 @Override 3405 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3406 final IntentSender pi) { 3407 mContext.enforceCallingOrSelfPermission( 3408 android.Manifest.permission.CLEAR_APP_CACHE, null); 3409 // Queue up an async operation since clearing cache may take a little while. 3410 mHandler.post(new Runnable() { 3411 public void run() { 3412 mHandler.removeCallbacks(this); 3413 boolean success = true; 3414 synchronized (mInstallLock) { 3415 try { 3416 mInstaller.freeCache(volumeUuid, freeStorageSize); 3417 } catch (InstallerException e) { 3418 Slog.w(TAG, "Couldn't clear application caches: " + e); 3419 success = false; 3420 } 3421 } 3422 if(pi != null) { 3423 try { 3424 // Callback via pending intent 3425 int code = success ? 1 : 0; 3426 pi.sendIntent(null, code, null, 3427 null, null); 3428 } catch (SendIntentException e1) { 3429 Slog.i(TAG, "Failed to send pending intent"); 3430 } 3431 } 3432 } 3433 }); 3434 } 3435 3436 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3437 synchronized (mInstallLock) { 3438 try { 3439 mInstaller.freeCache(volumeUuid, freeStorageSize); 3440 } catch (InstallerException e) { 3441 throw new IOException("Failed to free enough space", e); 3442 } 3443 } 3444 } 3445 3446 /** 3447 * Update given flags based on encryption status of current user. 3448 */ 3449 private int updateFlags(int flags, int userId) { 3450 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3451 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3452 // Caller expressed an explicit opinion about what encryption 3453 // aware/unaware components they want to see, so fall through and 3454 // give them what they want 3455 } else { 3456 // Caller expressed no opinion, so match based on user state 3457 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3458 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3459 } else { 3460 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3461 } 3462 } 3463 return flags; 3464 } 3465 3466 private UserManagerInternal getUserManagerInternal() { 3467 if (mUserManagerInternal == null) { 3468 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3469 } 3470 return mUserManagerInternal; 3471 } 3472 3473 /** 3474 * Update given flags when being used to request {@link PackageInfo}. 3475 */ 3476 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3477 boolean triaged = true; 3478 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3479 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3480 // Caller is asking for component details, so they'd better be 3481 // asking for specific encryption matching behavior, or be triaged 3482 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3483 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3484 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3485 triaged = false; 3486 } 3487 } 3488 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3489 | PackageManager.MATCH_SYSTEM_ONLY 3490 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3491 triaged = false; 3492 } 3493 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3494 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3495 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3496 } 3497 return updateFlags(flags, userId); 3498 } 3499 3500 /** 3501 * Update given flags when being used to request {@link ApplicationInfo}. 3502 */ 3503 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3504 return updateFlagsForPackage(flags, userId, cookie); 3505 } 3506 3507 /** 3508 * Update given flags when being used to request {@link ComponentInfo}. 3509 */ 3510 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3511 if (cookie instanceof Intent) { 3512 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3513 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3514 } 3515 } 3516 3517 boolean triaged = true; 3518 // Caller is asking for component details, so they'd better be 3519 // asking for specific encryption matching behavior, or be triaged 3520 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3521 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3522 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3523 triaged = false; 3524 } 3525 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3526 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3527 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3528 } 3529 3530 return updateFlags(flags, userId); 3531 } 3532 3533 /** 3534 * Update given flags when being used to request {@link ResolveInfo}. 3535 */ 3536 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3537 // Safe mode means we shouldn't match any third-party components 3538 if (mSafeMode) { 3539 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3540 } 3541 3542 return updateFlagsForComponent(flags, userId, cookie); 3543 } 3544 3545 @Override 3546 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3547 if (!sUserManager.exists(userId)) return null; 3548 flags = updateFlagsForComponent(flags, userId, component); 3549 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3550 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3551 synchronized (mPackages) { 3552 PackageParser.Activity a = mActivities.mActivities.get(component); 3553 3554 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3555 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3556 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3557 if (ps == null) return null; 3558 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3559 userId); 3560 } 3561 if (mResolveComponentName.equals(component)) { 3562 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3563 new PackageUserState(), userId); 3564 } 3565 } 3566 return null; 3567 } 3568 3569 @Override 3570 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3571 String resolvedType) { 3572 synchronized (mPackages) { 3573 if (component.equals(mResolveComponentName)) { 3574 // The resolver supports EVERYTHING! 3575 return true; 3576 } 3577 PackageParser.Activity a = mActivities.mActivities.get(component); 3578 if (a == null) { 3579 return false; 3580 } 3581 for (int i=0; i<a.intents.size(); i++) { 3582 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3583 intent.getData(), intent.getCategories(), TAG) >= 0) { 3584 return true; 3585 } 3586 } 3587 return false; 3588 } 3589 } 3590 3591 @Override 3592 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3593 if (!sUserManager.exists(userId)) return null; 3594 flags = updateFlagsForComponent(flags, userId, component); 3595 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3596 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3597 synchronized (mPackages) { 3598 PackageParser.Activity a = mReceivers.mActivities.get(component); 3599 if (DEBUG_PACKAGE_INFO) Log.v( 3600 TAG, "getReceiverInfo " + component + ": " + a); 3601 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3602 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3603 if (ps == null) return null; 3604 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3605 userId); 3606 } 3607 } 3608 return null; 3609 } 3610 3611 @Override 3612 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3613 if (!sUserManager.exists(userId)) return null; 3614 flags = updateFlagsForComponent(flags, userId, component); 3615 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3616 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3617 synchronized (mPackages) { 3618 PackageParser.Service s = mServices.mServices.get(component); 3619 if (DEBUG_PACKAGE_INFO) Log.v( 3620 TAG, "getServiceInfo " + component + ": " + s); 3621 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3622 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3623 if (ps == null) return null; 3624 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3625 userId); 3626 } 3627 } 3628 return null; 3629 } 3630 3631 @Override 3632 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3633 if (!sUserManager.exists(userId)) return null; 3634 flags = updateFlagsForComponent(flags, userId, component); 3635 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3636 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3637 synchronized (mPackages) { 3638 PackageParser.Provider p = mProviders.mProviders.get(component); 3639 if (DEBUG_PACKAGE_INFO) Log.v( 3640 TAG, "getProviderInfo " + component + ": " + p); 3641 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3642 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3643 if (ps == null) return null; 3644 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3645 userId); 3646 } 3647 } 3648 return null; 3649 } 3650 3651 @Override 3652 public String[] getSystemSharedLibraryNames() { 3653 Set<String> libSet; 3654 synchronized (mPackages) { 3655 libSet = mSharedLibraries.keySet(); 3656 int size = libSet.size(); 3657 if (size > 0) { 3658 String[] libs = new String[size]; 3659 libSet.toArray(libs); 3660 return libs; 3661 } 3662 } 3663 return null; 3664 } 3665 3666 @Override 3667 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3668 synchronized (mPackages) { 3669 return mServicesSystemSharedLibraryPackageName; 3670 } 3671 } 3672 3673 @Override 3674 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3675 synchronized (mPackages) { 3676 return mSharedSystemSharedLibraryPackageName; 3677 } 3678 } 3679 3680 @Override 3681 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3682 synchronized (mPackages) { 3683 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3684 3685 final FeatureInfo fi = new FeatureInfo(); 3686 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3687 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3688 res.add(fi); 3689 3690 return new ParceledListSlice<>(res); 3691 } 3692 } 3693 3694 @Override 3695 public boolean hasSystemFeature(String name, int version) { 3696 synchronized (mPackages) { 3697 final FeatureInfo feat = mAvailableFeatures.get(name); 3698 if (feat == null) { 3699 return false; 3700 } else { 3701 return feat.version >= version; 3702 } 3703 } 3704 } 3705 3706 @Override 3707 public int checkPermission(String permName, String pkgName, int userId) { 3708 if (!sUserManager.exists(userId)) { 3709 return PackageManager.PERMISSION_DENIED; 3710 } 3711 3712 synchronized (mPackages) { 3713 final PackageParser.Package p = mPackages.get(pkgName); 3714 if (p != null && p.mExtras != null) { 3715 final PackageSetting ps = (PackageSetting) p.mExtras; 3716 final PermissionsState permissionsState = ps.getPermissionsState(); 3717 if (permissionsState.hasPermission(permName, userId)) { 3718 return PackageManager.PERMISSION_GRANTED; 3719 } 3720 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3721 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3722 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3723 return PackageManager.PERMISSION_GRANTED; 3724 } 3725 } 3726 } 3727 3728 return PackageManager.PERMISSION_DENIED; 3729 } 3730 3731 @Override 3732 public int checkUidPermission(String permName, int uid) { 3733 final int userId = UserHandle.getUserId(uid); 3734 3735 if (!sUserManager.exists(userId)) { 3736 return PackageManager.PERMISSION_DENIED; 3737 } 3738 3739 synchronized (mPackages) { 3740 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3741 if (obj != null) { 3742 final SettingBase ps = (SettingBase) obj; 3743 final PermissionsState permissionsState = ps.getPermissionsState(); 3744 if (permissionsState.hasPermission(permName, userId)) { 3745 return PackageManager.PERMISSION_GRANTED; 3746 } 3747 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3748 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3749 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3750 return PackageManager.PERMISSION_GRANTED; 3751 } 3752 } else { 3753 ArraySet<String> perms = mSystemPermissions.get(uid); 3754 if (perms != null) { 3755 if (perms.contains(permName)) { 3756 return PackageManager.PERMISSION_GRANTED; 3757 } 3758 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3759 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3760 return PackageManager.PERMISSION_GRANTED; 3761 } 3762 } 3763 } 3764 } 3765 3766 return PackageManager.PERMISSION_DENIED; 3767 } 3768 3769 @Override 3770 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3771 if (UserHandle.getCallingUserId() != userId) { 3772 mContext.enforceCallingPermission( 3773 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3774 "isPermissionRevokedByPolicy for user " + userId); 3775 } 3776 3777 if (checkPermission(permission, packageName, userId) 3778 == PackageManager.PERMISSION_GRANTED) { 3779 return false; 3780 } 3781 3782 final long identity = Binder.clearCallingIdentity(); 3783 try { 3784 final int flags = getPermissionFlags(permission, packageName, userId); 3785 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3786 } finally { 3787 Binder.restoreCallingIdentity(identity); 3788 } 3789 } 3790 3791 @Override 3792 public String getPermissionControllerPackageName() { 3793 synchronized (mPackages) { 3794 return mRequiredInstallerPackage; 3795 } 3796 } 3797 3798 /** 3799 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3800 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3801 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3802 * @param message the message to log on security exception 3803 */ 3804 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3805 boolean checkShell, String message) { 3806 if (userId < 0) { 3807 throw new IllegalArgumentException("Invalid userId " + userId); 3808 } 3809 if (checkShell) { 3810 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3811 } 3812 if (userId == UserHandle.getUserId(callingUid)) return; 3813 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3814 if (requireFullPermission) { 3815 mContext.enforceCallingOrSelfPermission( 3816 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3817 } else { 3818 try { 3819 mContext.enforceCallingOrSelfPermission( 3820 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3821 } catch (SecurityException se) { 3822 mContext.enforceCallingOrSelfPermission( 3823 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3824 } 3825 } 3826 } 3827 } 3828 3829 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3830 if (callingUid == Process.SHELL_UID) { 3831 if (userHandle >= 0 3832 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3833 throw new SecurityException("Shell does not have permission to access user " 3834 + userHandle); 3835 } else if (userHandle < 0) { 3836 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3837 + Debug.getCallers(3)); 3838 } 3839 } 3840 } 3841 3842 private BasePermission findPermissionTreeLP(String permName) { 3843 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3844 if (permName.startsWith(bp.name) && 3845 permName.length() > bp.name.length() && 3846 permName.charAt(bp.name.length()) == '.') { 3847 return bp; 3848 } 3849 } 3850 return null; 3851 } 3852 3853 private BasePermission checkPermissionTreeLP(String permName) { 3854 if (permName != null) { 3855 BasePermission bp = findPermissionTreeLP(permName); 3856 if (bp != null) { 3857 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3858 return bp; 3859 } 3860 throw new SecurityException("Calling uid " 3861 + Binder.getCallingUid() 3862 + " is not allowed to add to permission tree " 3863 + bp.name + " owned by uid " + bp.uid); 3864 } 3865 } 3866 throw new SecurityException("No permission tree found for " + permName); 3867 } 3868 3869 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3870 if (s1 == null) { 3871 return s2 == null; 3872 } 3873 if (s2 == null) { 3874 return false; 3875 } 3876 if (s1.getClass() != s2.getClass()) { 3877 return false; 3878 } 3879 return s1.equals(s2); 3880 } 3881 3882 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3883 if (pi1.icon != pi2.icon) return false; 3884 if (pi1.logo != pi2.logo) return false; 3885 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3886 if (!compareStrings(pi1.name, pi2.name)) return false; 3887 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3888 // We'll take care of setting this one. 3889 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3890 // These are not currently stored in settings. 3891 //if (!compareStrings(pi1.group, pi2.group)) return false; 3892 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3893 //if (pi1.labelRes != pi2.labelRes) return false; 3894 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3895 return true; 3896 } 3897 3898 int permissionInfoFootprint(PermissionInfo info) { 3899 int size = info.name.length(); 3900 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3901 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3902 return size; 3903 } 3904 3905 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3906 int size = 0; 3907 for (BasePermission perm : mSettings.mPermissions.values()) { 3908 if (perm.uid == tree.uid) { 3909 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3910 } 3911 } 3912 return size; 3913 } 3914 3915 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3916 // We calculate the max size of permissions defined by this uid and throw 3917 // if that plus the size of 'info' would exceed our stated maximum. 3918 if (tree.uid != Process.SYSTEM_UID) { 3919 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3920 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3921 throw new SecurityException("Permission tree size cap exceeded"); 3922 } 3923 } 3924 } 3925 3926 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3927 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3928 throw new SecurityException("Label must be specified in permission"); 3929 } 3930 BasePermission tree = checkPermissionTreeLP(info.name); 3931 BasePermission bp = mSettings.mPermissions.get(info.name); 3932 boolean added = bp == null; 3933 boolean changed = true; 3934 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3935 if (added) { 3936 enforcePermissionCapLocked(info, tree); 3937 bp = new BasePermission(info.name, tree.sourcePackage, 3938 BasePermission.TYPE_DYNAMIC); 3939 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3940 throw new SecurityException( 3941 "Not allowed to modify non-dynamic permission " 3942 + info.name); 3943 } else { 3944 if (bp.protectionLevel == fixedLevel 3945 && bp.perm.owner.equals(tree.perm.owner) 3946 && bp.uid == tree.uid 3947 && comparePermissionInfos(bp.perm.info, info)) { 3948 changed = false; 3949 } 3950 } 3951 bp.protectionLevel = fixedLevel; 3952 info = new PermissionInfo(info); 3953 info.protectionLevel = fixedLevel; 3954 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3955 bp.perm.info.packageName = tree.perm.info.packageName; 3956 bp.uid = tree.uid; 3957 if (added) { 3958 mSettings.mPermissions.put(info.name, bp); 3959 } 3960 if (changed) { 3961 if (!async) { 3962 mSettings.writeLPr(); 3963 } else { 3964 scheduleWriteSettingsLocked(); 3965 } 3966 } 3967 return added; 3968 } 3969 3970 @Override 3971 public boolean addPermission(PermissionInfo info) { 3972 synchronized (mPackages) { 3973 return addPermissionLocked(info, false); 3974 } 3975 } 3976 3977 @Override 3978 public boolean addPermissionAsync(PermissionInfo info) { 3979 synchronized (mPackages) { 3980 return addPermissionLocked(info, true); 3981 } 3982 } 3983 3984 @Override 3985 public void removePermission(String name) { 3986 synchronized (mPackages) { 3987 checkPermissionTreeLP(name); 3988 BasePermission bp = mSettings.mPermissions.get(name); 3989 if (bp != null) { 3990 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3991 throw new SecurityException( 3992 "Not allowed to modify non-dynamic permission " 3993 + name); 3994 } 3995 mSettings.mPermissions.remove(name); 3996 mSettings.writeLPr(); 3997 } 3998 } 3999 } 4000 4001 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4002 BasePermission bp) { 4003 int index = pkg.requestedPermissions.indexOf(bp.name); 4004 if (index == -1) { 4005 throw new SecurityException("Package " + pkg.packageName 4006 + " has not requested permission " + bp.name); 4007 } 4008 if (!bp.isRuntime() && !bp.isDevelopment()) { 4009 throw new SecurityException("Permission " + bp.name 4010 + " is not a changeable permission type"); 4011 } 4012 } 4013 4014 @Override 4015 public void grantRuntimePermission(String packageName, String name, final int userId) { 4016 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4017 } 4018 4019 private void grantRuntimePermission(String packageName, String name, final int userId, 4020 boolean overridePolicy) { 4021 if (!sUserManager.exists(userId)) { 4022 Log.e(TAG, "No such user:" + userId); 4023 return; 4024 } 4025 4026 mContext.enforceCallingOrSelfPermission( 4027 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4028 "grantRuntimePermission"); 4029 4030 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4031 true /* requireFullPermission */, true /* checkShell */, 4032 "grantRuntimePermission"); 4033 4034 final int uid; 4035 final SettingBase sb; 4036 4037 synchronized (mPackages) { 4038 final PackageParser.Package pkg = mPackages.get(packageName); 4039 if (pkg == null) { 4040 throw new IllegalArgumentException("Unknown package: " + packageName); 4041 } 4042 4043 final BasePermission bp = mSettings.mPermissions.get(name); 4044 if (bp == null) { 4045 throw new IllegalArgumentException("Unknown permission: " + name); 4046 } 4047 4048 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4049 4050 // If a permission review is required for legacy apps we represent 4051 // their permissions as always granted runtime ones since we need 4052 // to keep the review required permission flag per user while an 4053 // install permission's state is shared across all users. 4054 if (mPermissionReviewRequired 4055 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4056 && bp.isRuntime()) { 4057 return; 4058 } 4059 4060 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4061 sb = (SettingBase) pkg.mExtras; 4062 if (sb == null) { 4063 throw new IllegalArgumentException("Unknown package: " + packageName); 4064 } 4065 4066 final PermissionsState permissionsState = sb.getPermissionsState(); 4067 4068 final int flags = permissionsState.getPermissionFlags(name, userId); 4069 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4070 throw new SecurityException("Cannot grant system fixed permission " 4071 + name + " for package " + packageName); 4072 } 4073 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4074 throw new SecurityException("Cannot grant policy fixed permission " 4075 + name + " for package " + packageName); 4076 } 4077 4078 if (bp.isDevelopment()) { 4079 // Development permissions must be handled specially, since they are not 4080 // normal runtime permissions. For now they apply to all users. 4081 if (permissionsState.grantInstallPermission(bp) != 4082 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4083 scheduleWriteSettingsLocked(); 4084 } 4085 return; 4086 } 4087 4088 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4089 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4090 return; 4091 } 4092 4093 final int result = permissionsState.grantRuntimePermission(bp, userId); 4094 switch (result) { 4095 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4096 return; 4097 } 4098 4099 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4100 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4101 mHandler.post(new Runnable() { 4102 @Override 4103 public void run() { 4104 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4105 } 4106 }); 4107 } 4108 break; 4109 } 4110 4111 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4112 4113 // Not critical if that is lost - app has to request again. 4114 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4115 } 4116 4117 // Only need to do this if user is initialized. Otherwise it's a new user 4118 // and there are no processes running as the user yet and there's no need 4119 // to make an expensive call to remount processes for the changed permissions. 4120 if (READ_EXTERNAL_STORAGE.equals(name) 4121 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4122 final long token = Binder.clearCallingIdentity(); 4123 try { 4124 if (sUserManager.isInitialized(userId)) { 4125 MountServiceInternal mountServiceInternal = LocalServices.getService( 4126 MountServiceInternal.class); 4127 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4128 } 4129 } finally { 4130 Binder.restoreCallingIdentity(token); 4131 } 4132 } 4133 } 4134 4135 @Override 4136 public void revokeRuntimePermission(String packageName, String name, int userId) { 4137 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4138 } 4139 4140 private void revokeRuntimePermission(String packageName, String name, int userId, 4141 boolean overridePolicy) { 4142 if (!sUserManager.exists(userId)) { 4143 Log.e(TAG, "No such user:" + userId); 4144 return; 4145 } 4146 4147 mContext.enforceCallingOrSelfPermission( 4148 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4149 "revokeRuntimePermission"); 4150 4151 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4152 true /* requireFullPermission */, true /* checkShell */, 4153 "revokeRuntimePermission"); 4154 4155 final int appId; 4156 4157 synchronized (mPackages) { 4158 final PackageParser.Package pkg = mPackages.get(packageName); 4159 if (pkg == null) { 4160 throw new IllegalArgumentException("Unknown package: " + packageName); 4161 } 4162 4163 final BasePermission bp = mSettings.mPermissions.get(name); 4164 if (bp == null) { 4165 throw new IllegalArgumentException("Unknown permission: " + name); 4166 } 4167 4168 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4169 4170 // If a permission review is required for legacy apps we represent 4171 // their permissions as always granted runtime ones since we need 4172 // to keep the review required permission flag per user while an 4173 // install permission's state is shared across all users. 4174 if (mPermissionReviewRequired 4175 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4176 && bp.isRuntime()) { 4177 return; 4178 } 4179 4180 SettingBase sb = (SettingBase) pkg.mExtras; 4181 if (sb == null) { 4182 throw new IllegalArgumentException("Unknown package: " + packageName); 4183 } 4184 4185 final PermissionsState permissionsState = sb.getPermissionsState(); 4186 4187 final int flags = permissionsState.getPermissionFlags(name, userId); 4188 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4189 throw new SecurityException("Cannot revoke system fixed permission " 4190 + name + " for package " + packageName); 4191 } 4192 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4193 throw new SecurityException("Cannot revoke policy fixed permission " 4194 + name + " for package " + packageName); 4195 } 4196 4197 if (bp.isDevelopment()) { 4198 // Development permissions must be handled specially, since they are not 4199 // normal runtime permissions. For now they apply to all users. 4200 if (permissionsState.revokeInstallPermission(bp) != 4201 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4202 scheduleWriteSettingsLocked(); 4203 } 4204 return; 4205 } 4206 4207 if (permissionsState.revokeRuntimePermission(bp, userId) == 4208 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4209 return; 4210 } 4211 4212 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4213 4214 // Critical, after this call app should never have the permission. 4215 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4216 4217 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4218 } 4219 4220 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4221 } 4222 4223 @Override 4224 public void resetRuntimePermissions() { 4225 mContext.enforceCallingOrSelfPermission( 4226 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4227 "revokeRuntimePermission"); 4228 4229 int callingUid = Binder.getCallingUid(); 4230 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4231 mContext.enforceCallingOrSelfPermission( 4232 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4233 "resetRuntimePermissions"); 4234 } 4235 4236 synchronized (mPackages) { 4237 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4238 for (int userId : UserManagerService.getInstance().getUserIds()) { 4239 final int packageCount = mPackages.size(); 4240 for (int i = 0; i < packageCount; i++) { 4241 PackageParser.Package pkg = mPackages.valueAt(i); 4242 if (!(pkg.mExtras instanceof PackageSetting)) { 4243 continue; 4244 } 4245 PackageSetting ps = (PackageSetting) pkg.mExtras; 4246 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4247 } 4248 } 4249 } 4250 } 4251 4252 @Override 4253 public int getPermissionFlags(String name, String packageName, int userId) { 4254 if (!sUserManager.exists(userId)) { 4255 return 0; 4256 } 4257 4258 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4259 4260 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4261 true /* requireFullPermission */, false /* checkShell */, 4262 "getPermissionFlags"); 4263 4264 synchronized (mPackages) { 4265 final PackageParser.Package pkg = mPackages.get(packageName); 4266 if (pkg == null) { 4267 return 0; 4268 } 4269 4270 final BasePermission bp = mSettings.mPermissions.get(name); 4271 if (bp == null) { 4272 return 0; 4273 } 4274 4275 SettingBase sb = (SettingBase) pkg.mExtras; 4276 if (sb == null) { 4277 return 0; 4278 } 4279 4280 PermissionsState permissionsState = sb.getPermissionsState(); 4281 return permissionsState.getPermissionFlags(name, userId); 4282 } 4283 } 4284 4285 @Override 4286 public void updatePermissionFlags(String name, String packageName, int flagMask, 4287 int flagValues, int userId) { 4288 if (!sUserManager.exists(userId)) { 4289 return; 4290 } 4291 4292 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4293 4294 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4295 true /* requireFullPermission */, true /* checkShell */, 4296 "updatePermissionFlags"); 4297 4298 // Only the system can change these flags and nothing else. 4299 if (getCallingUid() != Process.SYSTEM_UID) { 4300 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4301 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4302 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4303 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4304 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4305 } 4306 4307 synchronized (mPackages) { 4308 final PackageParser.Package pkg = mPackages.get(packageName); 4309 if (pkg == null) { 4310 throw new IllegalArgumentException("Unknown package: " + packageName); 4311 } 4312 4313 final BasePermission bp = mSettings.mPermissions.get(name); 4314 if (bp == null) { 4315 throw new IllegalArgumentException("Unknown permission: " + name); 4316 } 4317 4318 SettingBase sb = (SettingBase) pkg.mExtras; 4319 if (sb == null) { 4320 throw new IllegalArgumentException("Unknown package: " + packageName); 4321 } 4322 4323 PermissionsState permissionsState = sb.getPermissionsState(); 4324 4325 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4326 4327 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4328 // Install and runtime permissions are stored in different places, 4329 // so figure out what permission changed and persist the change. 4330 if (permissionsState.getInstallPermissionState(name) != null) { 4331 scheduleWriteSettingsLocked(); 4332 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4333 || hadState) { 4334 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4335 } 4336 } 4337 } 4338 } 4339 4340 /** 4341 * Update the permission flags for all packages and runtime permissions of a user in order 4342 * to allow device or profile owner to remove POLICY_FIXED. 4343 */ 4344 @Override 4345 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4346 if (!sUserManager.exists(userId)) { 4347 return; 4348 } 4349 4350 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4351 4352 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4353 true /* requireFullPermission */, true /* checkShell */, 4354 "updatePermissionFlagsForAllApps"); 4355 4356 // Only the system can change system fixed flags. 4357 if (getCallingUid() != Process.SYSTEM_UID) { 4358 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4359 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4360 } 4361 4362 synchronized (mPackages) { 4363 boolean changed = false; 4364 final int packageCount = mPackages.size(); 4365 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4366 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4367 SettingBase sb = (SettingBase) pkg.mExtras; 4368 if (sb == null) { 4369 continue; 4370 } 4371 PermissionsState permissionsState = sb.getPermissionsState(); 4372 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4373 userId, flagMask, flagValues); 4374 } 4375 if (changed) { 4376 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4377 } 4378 } 4379 } 4380 4381 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4382 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4383 != PackageManager.PERMISSION_GRANTED 4384 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4385 != PackageManager.PERMISSION_GRANTED) { 4386 throw new SecurityException(message + " requires " 4387 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4388 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4389 } 4390 } 4391 4392 @Override 4393 public boolean shouldShowRequestPermissionRationale(String permissionName, 4394 String packageName, int userId) { 4395 if (UserHandle.getCallingUserId() != userId) { 4396 mContext.enforceCallingPermission( 4397 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4398 "canShowRequestPermissionRationale for user " + userId); 4399 } 4400 4401 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4402 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4403 return false; 4404 } 4405 4406 if (checkPermission(permissionName, packageName, userId) 4407 == PackageManager.PERMISSION_GRANTED) { 4408 return false; 4409 } 4410 4411 final int flags; 4412 4413 final long identity = Binder.clearCallingIdentity(); 4414 try { 4415 flags = getPermissionFlags(permissionName, 4416 packageName, userId); 4417 } finally { 4418 Binder.restoreCallingIdentity(identity); 4419 } 4420 4421 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4422 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4423 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4424 4425 if ((flags & fixedFlags) != 0) { 4426 return false; 4427 } 4428 4429 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4430 } 4431 4432 @Override 4433 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4434 mContext.enforceCallingOrSelfPermission( 4435 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4436 "addOnPermissionsChangeListener"); 4437 4438 synchronized (mPackages) { 4439 mOnPermissionChangeListeners.addListenerLocked(listener); 4440 } 4441 } 4442 4443 @Override 4444 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4445 synchronized (mPackages) { 4446 mOnPermissionChangeListeners.removeListenerLocked(listener); 4447 } 4448 } 4449 4450 @Override 4451 public boolean isProtectedBroadcast(String actionName) { 4452 synchronized (mPackages) { 4453 if (mProtectedBroadcasts.contains(actionName)) { 4454 return true; 4455 } else if (actionName != null) { 4456 // TODO: remove these terrible hacks 4457 if (actionName.startsWith("android.net.netmon.lingerExpired") 4458 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4459 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4460 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4461 return true; 4462 } 4463 } 4464 } 4465 return false; 4466 } 4467 4468 @Override 4469 public int checkSignatures(String pkg1, String pkg2) { 4470 synchronized (mPackages) { 4471 final PackageParser.Package p1 = mPackages.get(pkg1); 4472 final PackageParser.Package p2 = mPackages.get(pkg2); 4473 if (p1 == null || p1.mExtras == null 4474 || p2 == null || p2.mExtras == null) { 4475 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4476 } 4477 return compareSignatures(p1.mSignatures, p2.mSignatures); 4478 } 4479 } 4480 4481 @Override 4482 public int checkUidSignatures(int uid1, int uid2) { 4483 // Map to base uids. 4484 uid1 = UserHandle.getAppId(uid1); 4485 uid2 = UserHandle.getAppId(uid2); 4486 // reader 4487 synchronized (mPackages) { 4488 Signature[] s1; 4489 Signature[] s2; 4490 Object obj = mSettings.getUserIdLPr(uid1); 4491 if (obj != null) { 4492 if (obj instanceof SharedUserSetting) { 4493 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4494 } else if (obj instanceof PackageSetting) { 4495 s1 = ((PackageSetting)obj).signatures.mSignatures; 4496 } else { 4497 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4498 } 4499 } else { 4500 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4501 } 4502 obj = mSettings.getUserIdLPr(uid2); 4503 if (obj != null) { 4504 if (obj instanceof SharedUserSetting) { 4505 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4506 } else if (obj instanceof PackageSetting) { 4507 s2 = ((PackageSetting)obj).signatures.mSignatures; 4508 } else { 4509 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4510 } 4511 } else { 4512 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4513 } 4514 return compareSignatures(s1, s2); 4515 } 4516 } 4517 4518 /** 4519 * This method should typically only be used when granting or revoking 4520 * permissions, since the app may immediately restart after this call. 4521 * <p> 4522 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4523 * guard your work against the app being relaunched. 4524 */ 4525 private void killUid(int appId, int userId, String reason) { 4526 final long identity = Binder.clearCallingIdentity(); 4527 try { 4528 IActivityManager am = ActivityManagerNative.getDefault(); 4529 if (am != null) { 4530 try { 4531 am.killUid(appId, userId, reason); 4532 } catch (RemoteException e) { 4533 /* ignore - same process */ 4534 } 4535 } 4536 } finally { 4537 Binder.restoreCallingIdentity(identity); 4538 } 4539 } 4540 4541 /** 4542 * Compares two sets of signatures. Returns: 4543 * <br /> 4544 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4545 * <br /> 4546 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4547 * <br /> 4548 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4549 * <br /> 4550 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4551 * <br /> 4552 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4553 */ 4554 static int compareSignatures(Signature[] s1, Signature[] s2) { 4555 if (s1 == null) { 4556 return s2 == null 4557 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4558 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4559 } 4560 4561 if (s2 == null) { 4562 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4563 } 4564 4565 if (s1.length != s2.length) { 4566 return PackageManager.SIGNATURE_NO_MATCH; 4567 } 4568 4569 // Since both signature sets are of size 1, we can compare without HashSets. 4570 if (s1.length == 1) { 4571 return s1[0].equals(s2[0]) ? 4572 PackageManager.SIGNATURE_MATCH : 4573 PackageManager.SIGNATURE_NO_MATCH; 4574 } 4575 4576 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4577 for (Signature sig : s1) { 4578 set1.add(sig); 4579 } 4580 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4581 for (Signature sig : s2) { 4582 set2.add(sig); 4583 } 4584 // Make sure s2 contains all signatures in s1. 4585 if (set1.equals(set2)) { 4586 return PackageManager.SIGNATURE_MATCH; 4587 } 4588 return PackageManager.SIGNATURE_NO_MATCH; 4589 } 4590 4591 /** 4592 * If the database version for this type of package (internal storage or 4593 * external storage) is less than the version where package signatures 4594 * were updated, return true. 4595 */ 4596 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4597 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4598 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4599 } 4600 4601 /** 4602 * Used for backward compatibility to make sure any packages with 4603 * certificate chains get upgraded to the new style. {@code existingSigs} 4604 * will be in the old format (since they were stored on disk from before the 4605 * system upgrade) and {@code scannedSigs} will be in the newer format. 4606 */ 4607 private int compareSignaturesCompat(PackageSignatures existingSigs, 4608 PackageParser.Package scannedPkg) { 4609 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4610 return PackageManager.SIGNATURE_NO_MATCH; 4611 } 4612 4613 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4614 for (Signature sig : existingSigs.mSignatures) { 4615 existingSet.add(sig); 4616 } 4617 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4618 for (Signature sig : scannedPkg.mSignatures) { 4619 try { 4620 Signature[] chainSignatures = sig.getChainSignatures(); 4621 for (Signature chainSig : chainSignatures) { 4622 scannedCompatSet.add(chainSig); 4623 } 4624 } catch (CertificateEncodingException e) { 4625 scannedCompatSet.add(sig); 4626 } 4627 } 4628 /* 4629 * Make sure the expanded scanned set contains all signatures in the 4630 * existing one. 4631 */ 4632 if (scannedCompatSet.equals(existingSet)) { 4633 // Migrate the old signatures to the new scheme. 4634 existingSigs.assignSignatures(scannedPkg.mSignatures); 4635 // The new KeySets will be re-added later in the scanning process. 4636 synchronized (mPackages) { 4637 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4638 } 4639 return PackageManager.SIGNATURE_MATCH; 4640 } 4641 return PackageManager.SIGNATURE_NO_MATCH; 4642 } 4643 4644 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4645 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4646 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4647 } 4648 4649 private int compareSignaturesRecover(PackageSignatures existingSigs, 4650 PackageParser.Package scannedPkg) { 4651 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4652 return PackageManager.SIGNATURE_NO_MATCH; 4653 } 4654 4655 String msg = null; 4656 try { 4657 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4658 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4659 + scannedPkg.packageName); 4660 return PackageManager.SIGNATURE_MATCH; 4661 } 4662 } catch (CertificateException e) { 4663 msg = e.getMessage(); 4664 } 4665 4666 logCriticalInfo(Log.INFO, 4667 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4668 return PackageManager.SIGNATURE_NO_MATCH; 4669 } 4670 4671 @Override 4672 public List<String> getAllPackages() { 4673 synchronized (mPackages) { 4674 return new ArrayList<String>(mPackages.keySet()); 4675 } 4676 } 4677 4678 @Override 4679 public String[] getPackagesForUid(int uid) { 4680 final int userId = UserHandle.getUserId(uid); 4681 uid = UserHandle.getAppId(uid); 4682 // reader 4683 synchronized (mPackages) { 4684 Object obj = mSettings.getUserIdLPr(uid); 4685 if (obj instanceof SharedUserSetting) { 4686 final SharedUserSetting sus = (SharedUserSetting) obj; 4687 final int N = sus.packages.size(); 4688 String[] res = new String[N]; 4689 final Iterator<PackageSetting> it = sus.packages.iterator(); 4690 int i = 0; 4691 while (it.hasNext()) { 4692 PackageSetting ps = it.next(); 4693 if (ps.getInstalled(userId)) { 4694 res[i++] = ps.name; 4695 } else { 4696 res = ArrayUtils.removeElement(String.class, res, res[i]); 4697 } 4698 } 4699 return res; 4700 } else if (obj instanceof PackageSetting) { 4701 final PackageSetting ps = (PackageSetting) obj; 4702 return new String[] { ps.name }; 4703 } 4704 } 4705 return null; 4706 } 4707 4708 @Override 4709 public String getNameForUid(int uid) { 4710 // reader 4711 synchronized (mPackages) { 4712 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4713 if (obj instanceof SharedUserSetting) { 4714 final SharedUserSetting sus = (SharedUserSetting) obj; 4715 return sus.name + ":" + sus.userId; 4716 } else if (obj instanceof PackageSetting) { 4717 final PackageSetting ps = (PackageSetting) obj; 4718 return ps.name; 4719 } 4720 } 4721 return null; 4722 } 4723 4724 @Override 4725 public int getUidForSharedUser(String sharedUserName) { 4726 if(sharedUserName == null) { 4727 return -1; 4728 } 4729 // reader 4730 synchronized (mPackages) { 4731 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4732 if (suid == null) { 4733 return -1; 4734 } 4735 return suid.userId; 4736 } 4737 } 4738 4739 @Override 4740 public int getFlagsForUid(int uid) { 4741 synchronized (mPackages) { 4742 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4743 if (obj instanceof SharedUserSetting) { 4744 final SharedUserSetting sus = (SharedUserSetting) obj; 4745 return sus.pkgFlags; 4746 } else if (obj instanceof PackageSetting) { 4747 final PackageSetting ps = (PackageSetting) obj; 4748 return ps.pkgFlags; 4749 } 4750 } 4751 return 0; 4752 } 4753 4754 @Override 4755 public int getPrivateFlagsForUid(int uid) { 4756 synchronized (mPackages) { 4757 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4758 if (obj instanceof SharedUserSetting) { 4759 final SharedUserSetting sus = (SharedUserSetting) obj; 4760 return sus.pkgPrivateFlags; 4761 } else if (obj instanceof PackageSetting) { 4762 final PackageSetting ps = (PackageSetting) obj; 4763 return ps.pkgPrivateFlags; 4764 } 4765 } 4766 return 0; 4767 } 4768 4769 @Override 4770 public boolean isUidPrivileged(int uid) { 4771 uid = UserHandle.getAppId(uid); 4772 // reader 4773 synchronized (mPackages) { 4774 Object obj = mSettings.getUserIdLPr(uid); 4775 if (obj instanceof SharedUserSetting) { 4776 final SharedUserSetting sus = (SharedUserSetting) obj; 4777 final Iterator<PackageSetting> it = sus.packages.iterator(); 4778 while (it.hasNext()) { 4779 if (it.next().isPrivileged()) { 4780 return true; 4781 } 4782 } 4783 } else if (obj instanceof PackageSetting) { 4784 final PackageSetting ps = (PackageSetting) obj; 4785 return ps.isPrivileged(); 4786 } 4787 } 4788 return false; 4789 } 4790 4791 @Override 4792 public String[] getAppOpPermissionPackages(String permissionName) { 4793 synchronized (mPackages) { 4794 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4795 if (pkgs == null) { 4796 return null; 4797 } 4798 return pkgs.toArray(new String[pkgs.size()]); 4799 } 4800 } 4801 4802 @Override 4803 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4804 int flags, int userId) { 4805 try { 4806 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4807 4808 if (!sUserManager.exists(userId)) return null; 4809 flags = updateFlagsForResolve(flags, userId, intent); 4810 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4811 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4812 4813 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4814 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4815 flags, userId); 4816 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4817 4818 final ResolveInfo bestChoice = 4819 chooseBestActivity(intent, resolvedType, flags, query, userId); 4820 return bestChoice; 4821 } finally { 4822 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4823 } 4824 } 4825 4826 @Override 4827 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4828 IntentFilter filter, int match, ComponentName activity) { 4829 final int userId = UserHandle.getCallingUserId(); 4830 if (DEBUG_PREFERRED) { 4831 Log.v(TAG, "setLastChosenActivity intent=" + intent 4832 + " resolvedType=" + resolvedType 4833 + " flags=" + flags 4834 + " filter=" + filter 4835 + " match=" + match 4836 + " activity=" + activity); 4837 filter.dump(new PrintStreamPrinter(System.out), " "); 4838 } 4839 intent.setComponent(null); 4840 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4841 userId); 4842 // Find any earlier preferred or last chosen entries and nuke them 4843 findPreferredActivity(intent, resolvedType, 4844 flags, query, 0, false, true, false, userId); 4845 // Add the new activity as the last chosen for this filter 4846 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4847 "Setting last chosen"); 4848 } 4849 4850 @Override 4851 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4852 final int userId = UserHandle.getCallingUserId(); 4853 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4854 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4855 userId); 4856 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4857 false, false, false, userId); 4858 } 4859 4860 private boolean isEphemeralDisabled() { 4861 // ephemeral apps have been disabled across the board 4862 if (DISABLE_EPHEMERAL_APPS) { 4863 return true; 4864 } 4865 // system isn't up yet; can't read settings, so, assume no ephemeral apps 4866 if (!mSystemReady) { 4867 return true; 4868 } 4869 // we can't get a content resolver until the system is ready; these checks must happen last 4870 final ContentResolver resolver = mContext.getContentResolver(); 4871 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 4872 return true; 4873 } 4874 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 4875 } 4876 4877 private boolean isEphemeralAllowed( 4878 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 4879 boolean skipPackageCheck) { 4880 // Short circuit and return early if possible. 4881 if (isEphemeralDisabled()) { 4882 return false; 4883 } 4884 final int callingUser = UserHandle.getCallingUserId(); 4885 if (callingUser != UserHandle.USER_SYSTEM) { 4886 return false; 4887 } 4888 if (mEphemeralResolverConnection == null) { 4889 return false; 4890 } 4891 if (intent.getComponent() != null) { 4892 return false; 4893 } 4894 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 4895 return false; 4896 } 4897 if (!skipPackageCheck && intent.getPackage() != null) { 4898 return false; 4899 } 4900 final boolean isWebUri = hasWebURI(intent); 4901 if (!isWebUri || intent.getData().getHost() == null) { 4902 return false; 4903 } 4904 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4905 synchronized (mPackages) { 4906 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 4907 for (int n = 0; n < count; n++) { 4908 ResolveInfo info = resolvedActivities.get(n); 4909 String packageName = info.activityInfo.packageName; 4910 PackageSetting ps = mSettings.mPackages.get(packageName); 4911 if (ps != null) { 4912 // Try to get the status from User settings first 4913 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4914 int status = (int) (packedStatus >> 32); 4915 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4916 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4917 if (DEBUG_EPHEMERAL) { 4918 Slog.v(TAG, "DENY ephemeral apps;" 4919 + " pkg: " + packageName + ", status: " + status); 4920 } 4921 return false; 4922 } 4923 } 4924 } 4925 } 4926 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4927 return true; 4928 } 4929 4930 private static EphemeralResolveInfo getEphemeralResolveInfo( 4931 Context context, EphemeralResolverConnection resolverConnection, Intent intent, 4932 String resolvedType, int userId, String packageName) { 4933 final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(), 4934 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 4935 final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(), 4936 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 4937 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 4938 ephemeralPrefixCount); 4939 final int[] shaPrefix = digest.getDigestPrefix(); 4940 final byte[][] digestBytes = digest.getDigestBytes(); 4941 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4942 resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask); 4943 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4944 // No hash prefix match; there are no ephemeral apps for this domain. 4945 return null; 4946 } 4947 4948 // Go in reverse order so we match the narrowest scope first. 4949 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 4950 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 4951 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 4952 continue; 4953 } 4954 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4955 // No filters; this should never happen. 4956 if (filters.isEmpty()) { 4957 continue; 4958 } 4959 if (packageName != null 4960 && !packageName.equals(ephemeralApplication.getPackageName())) { 4961 continue; 4962 } 4963 // We have a domain match; resolve the filters to see if anything matches. 4964 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4965 for (int j = filters.size() - 1; j >= 0; --j) { 4966 final EphemeralResolveIntentInfo intentInfo = 4967 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4968 ephemeralResolver.addFilter(intentInfo); 4969 } 4970 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4971 intent, resolvedType, false /*defaultOnly*/, userId); 4972 if (!matchedResolveInfoList.isEmpty()) { 4973 return matchedResolveInfoList.get(0); 4974 } 4975 } 4976 } 4977 // Hash or filter mis-match; no ephemeral apps for this domain. 4978 return null; 4979 } 4980 4981 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4982 int flags, List<ResolveInfo> query, int userId) { 4983 if (query != null) { 4984 final int N = query.size(); 4985 if (N == 1) { 4986 return query.get(0); 4987 } else if (N > 1) { 4988 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4989 // If there is more than one activity with the same priority, 4990 // then let the user decide between them. 4991 ResolveInfo r0 = query.get(0); 4992 ResolveInfo r1 = query.get(1); 4993 if (DEBUG_INTENT_MATCHING || debug) { 4994 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4995 + r1.activityInfo.name + "=" + r1.priority); 4996 } 4997 // If the first activity has a higher priority, or a different 4998 // default, then it is always desirable to pick it. 4999 if (r0.priority != r1.priority 5000 || r0.preferredOrder != r1.preferredOrder 5001 || r0.isDefault != r1.isDefault) { 5002 return query.get(0); 5003 } 5004 // If we have saved a preference for a preferred activity for 5005 // this Intent, use that. 5006 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5007 flags, query, r0.priority, true, false, debug, userId); 5008 if (ri != null) { 5009 return ri; 5010 } 5011 ri = new ResolveInfo(mResolveInfo); 5012 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5013 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5014 // If all of the options come from the same package, show the application's 5015 // label and icon instead of the generic resolver's. 5016 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5017 // and then throw away the ResolveInfo itself, meaning that the caller loses 5018 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5019 // a fallback for this case; we only set the target package's resources on 5020 // the ResolveInfo, not the ActivityInfo. 5021 final String intentPackage = intent.getPackage(); 5022 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5023 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5024 ri.resolvePackageName = intentPackage; 5025 if (userNeedsBadging(userId)) { 5026 ri.noResourceId = true; 5027 } else { 5028 ri.icon = appi.icon; 5029 } 5030 ri.iconResourceId = appi.icon; 5031 ri.labelRes = appi.labelRes; 5032 } 5033 ri.activityInfo.applicationInfo = new ApplicationInfo( 5034 ri.activityInfo.applicationInfo); 5035 if (userId != 0) { 5036 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5037 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5038 } 5039 // Make sure that the resolver is displayable in car mode 5040 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5041 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5042 return ri; 5043 } 5044 } 5045 return null; 5046 } 5047 5048 /** 5049 * Return true if the given list is not empty and all of its contents have 5050 * an activityInfo with the given package name. 5051 */ 5052 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5053 if (ArrayUtils.isEmpty(list)) { 5054 return false; 5055 } 5056 for (int i = 0, N = list.size(); i < N; i++) { 5057 final ResolveInfo ri = list.get(i); 5058 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5059 if (ai == null || !packageName.equals(ai.packageName)) { 5060 return false; 5061 } 5062 } 5063 return true; 5064 } 5065 5066 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5067 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5068 final int N = query.size(); 5069 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5070 .get(userId); 5071 // Get the list of persistent preferred activities that handle the intent 5072 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5073 List<PersistentPreferredActivity> pprefs = ppir != null 5074 ? ppir.queryIntent(intent, resolvedType, 5075 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5076 : null; 5077 if (pprefs != null && pprefs.size() > 0) { 5078 final int M = pprefs.size(); 5079 for (int i=0; i<M; i++) { 5080 final PersistentPreferredActivity ppa = pprefs.get(i); 5081 if (DEBUG_PREFERRED || debug) { 5082 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5083 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5084 + "\n component=" + ppa.mComponent); 5085 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5086 } 5087 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5088 flags | MATCH_DISABLED_COMPONENTS, userId); 5089 if (DEBUG_PREFERRED || debug) { 5090 Slog.v(TAG, "Found persistent preferred activity:"); 5091 if (ai != null) { 5092 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5093 } else { 5094 Slog.v(TAG, " null"); 5095 } 5096 } 5097 if (ai == null) { 5098 // This previously registered persistent preferred activity 5099 // component is no longer known. Ignore it and do NOT remove it. 5100 continue; 5101 } 5102 for (int j=0; j<N; j++) { 5103 final ResolveInfo ri = query.get(j); 5104 if (!ri.activityInfo.applicationInfo.packageName 5105 .equals(ai.applicationInfo.packageName)) { 5106 continue; 5107 } 5108 if (!ri.activityInfo.name.equals(ai.name)) { 5109 continue; 5110 } 5111 // Found a persistent preference that can handle the intent. 5112 if (DEBUG_PREFERRED || debug) { 5113 Slog.v(TAG, "Returning persistent preferred activity: " + 5114 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5115 } 5116 return ri; 5117 } 5118 } 5119 } 5120 return null; 5121 } 5122 5123 // TODO: handle preferred activities missing while user has amnesia 5124 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5125 List<ResolveInfo> query, int priority, boolean always, 5126 boolean removeMatches, boolean debug, int userId) { 5127 if (!sUserManager.exists(userId)) return null; 5128 flags = updateFlagsForResolve(flags, userId, intent); 5129 // writer 5130 synchronized (mPackages) { 5131 if (intent.getSelector() != null) { 5132 intent = intent.getSelector(); 5133 } 5134 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5135 5136 // Try to find a matching persistent preferred activity. 5137 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5138 debug, userId); 5139 5140 // If a persistent preferred activity matched, use it. 5141 if (pri != null) { 5142 return pri; 5143 } 5144 5145 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5146 // Get the list of preferred activities that handle the intent 5147 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5148 List<PreferredActivity> prefs = pir != null 5149 ? pir.queryIntent(intent, resolvedType, 5150 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5151 : null; 5152 if (prefs != null && prefs.size() > 0) { 5153 boolean changed = false; 5154 try { 5155 // First figure out how good the original match set is. 5156 // We will only allow preferred activities that came 5157 // from the same match quality. 5158 int match = 0; 5159 5160 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5161 5162 final int N = query.size(); 5163 for (int j=0; j<N; j++) { 5164 final ResolveInfo ri = query.get(j); 5165 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5166 + ": 0x" + Integer.toHexString(match)); 5167 if (ri.match > match) { 5168 match = ri.match; 5169 } 5170 } 5171 5172 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5173 + Integer.toHexString(match)); 5174 5175 match &= IntentFilter.MATCH_CATEGORY_MASK; 5176 final int M = prefs.size(); 5177 for (int i=0; i<M; i++) { 5178 final PreferredActivity pa = prefs.get(i); 5179 if (DEBUG_PREFERRED || debug) { 5180 Slog.v(TAG, "Checking PreferredActivity ds=" 5181 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5182 + "\n component=" + pa.mPref.mComponent); 5183 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5184 } 5185 if (pa.mPref.mMatch != match) { 5186 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5187 + Integer.toHexString(pa.mPref.mMatch)); 5188 continue; 5189 } 5190 // If it's not an "always" type preferred activity and that's what we're 5191 // looking for, skip it. 5192 if (always && !pa.mPref.mAlways) { 5193 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5194 continue; 5195 } 5196 final ActivityInfo ai = getActivityInfo( 5197 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5198 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5199 userId); 5200 if (DEBUG_PREFERRED || debug) { 5201 Slog.v(TAG, "Found preferred activity:"); 5202 if (ai != null) { 5203 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5204 } else { 5205 Slog.v(TAG, " null"); 5206 } 5207 } 5208 if (ai == null) { 5209 // This previously registered preferred activity 5210 // component is no longer known. Most likely an update 5211 // to the app was installed and in the new version this 5212 // component no longer exists. Clean it up by removing 5213 // it from the preferred activities list, and skip it. 5214 Slog.w(TAG, "Removing dangling preferred activity: " 5215 + pa.mPref.mComponent); 5216 pir.removeFilter(pa); 5217 changed = true; 5218 continue; 5219 } 5220 for (int j=0; j<N; j++) { 5221 final ResolveInfo ri = query.get(j); 5222 if (!ri.activityInfo.applicationInfo.packageName 5223 .equals(ai.applicationInfo.packageName)) { 5224 continue; 5225 } 5226 if (!ri.activityInfo.name.equals(ai.name)) { 5227 continue; 5228 } 5229 5230 if (removeMatches) { 5231 pir.removeFilter(pa); 5232 changed = true; 5233 if (DEBUG_PREFERRED) { 5234 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5235 } 5236 break; 5237 } 5238 5239 // Okay we found a previously set preferred or last chosen app. 5240 // If the result set is different from when this 5241 // was created, we need to clear it and re-ask the 5242 // user their preference, if we're looking for an "always" type entry. 5243 if (always && !pa.mPref.sameSet(query)) { 5244 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5245 + intent + " type " + resolvedType); 5246 if (DEBUG_PREFERRED) { 5247 Slog.v(TAG, "Removing preferred activity since set changed " 5248 + pa.mPref.mComponent); 5249 } 5250 pir.removeFilter(pa); 5251 // Re-add the filter as a "last chosen" entry (!always) 5252 PreferredActivity lastChosen = new PreferredActivity( 5253 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5254 pir.addFilter(lastChosen); 5255 changed = true; 5256 return null; 5257 } 5258 5259 // Yay! Either the set matched or we're looking for the last chosen 5260 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5261 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5262 return ri; 5263 } 5264 } 5265 } finally { 5266 if (changed) { 5267 if (DEBUG_PREFERRED) { 5268 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5269 } 5270 scheduleWritePackageRestrictionsLocked(userId); 5271 } 5272 } 5273 } 5274 } 5275 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5276 return null; 5277 } 5278 5279 /* 5280 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5281 */ 5282 @Override 5283 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5284 int targetUserId) { 5285 mContext.enforceCallingOrSelfPermission( 5286 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5287 List<CrossProfileIntentFilter> matches = 5288 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5289 if (matches != null) { 5290 int size = matches.size(); 5291 for (int i = 0; i < size; i++) { 5292 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5293 } 5294 } 5295 if (hasWebURI(intent)) { 5296 // cross-profile app linking works only towards the parent. 5297 final UserInfo parent = getProfileParent(sourceUserId); 5298 synchronized(mPackages) { 5299 int flags = updateFlagsForResolve(0, parent.id, intent); 5300 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5301 intent, resolvedType, flags, sourceUserId, parent.id); 5302 return xpDomainInfo != null; 5303 } 5304 } 5305 return false; 5306 } 5307 5308 private UserInfo getProfileParent(int userId) { 5309 final long identity = Binder.clearCallingIdentity(); 5310 try { 5311 return sUserManager.getProfileParent(userId); 5312 } finally { 5313 Binder.restoreCallingIdentity(identity); 5314 } 5315 } 5316 5317 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5318 String resolvedType, int userId) { 5319 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5320 if (resolver != null) { 5321 return resolver.queryIntent(intent, resolvedType, false, userId); 5322 } 5323 return null; 5324 } 5325 5326 @Override 5327 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5328 String resolvedType, int flags, int userId) { 5329 try { 5330 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5331 5332 return new ParceledListSlice<>( 5333 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5334 } finally { 5335 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5336 } 5337 } 5338 5339 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5340 String resolvedType, int flags, int userId) { 5341 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5342 flags = updateFlagsForResolve(flags, userId, intent); 5343 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5344 false /* requireFullPermission */, false /* checkShell */, 5345 "query intent activities"); 5346 ComponentName comp = intent.getComponent(); 5347 if (comp == null) { 5348 if (intent.getSelector() != null) { 5349 intent = intent.getSelector(); 5350 comp = intent.getComponent(); 5351 } 5352 } 5353 5354 if (comp != null) { 5355 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5356 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5357 if (ai != null) { 5358 final ResolveInfo ri = new ResolveInfo(); 5359 ri.activityInfo = ai; 5360 list.add(ri); 5361 } 5362 return list; 5363 } 5364 5365 // reader 5366 boolean sortResult = false; 5367 boolean addEphemeral = false; 5368 boolean matchEphemeralPackage = false; 5369 List<ResolveInfo> result; 5370 final String pkgName = intent.getPackage(); 5371 synchronized (mPackages) { 5372 if (pkgName == null) { 5373 List<CrossProfileIntentFilter> matchingFilters = 5374 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5375 // Check for results that need to skip the current profile. 5376 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5377 resolvedType, flags, userId); 5378 if (xpResolveInfo != null) { 5379 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5380 xpResult.add(xpResolveInfo); 5381 return filterIfNotSystemUser(xpResult, userId); 5382 } 5383 5384 // Check for results in the current profile. 5385 result = filterIfNotSystemUser(mActivities.queryIntent( 5386 intent, resolvedType, flags, userId), userId); 5387 addEphemeral = 5388 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5389 5390 // Check for cross profile results. 5391 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5392 xpResolveInfo = queryCrossProfileIntents( 5393 matchingFilters, intent, resolvedType, flags, userId, 5394 hasNonNegativePriorityResult); 5395 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5396 boolean isVisibleToUser = filterIfNotSystemUser( 5397 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5398 if (isVisibleToUser) { 5399 result.add(xpResolveInfo); 5400 sortResult = true; 5401 } 5402 } 5403 if (hasWebURI(intent)) { 5404 CrossProfileDomainInfo xpDomainInfo = null; 5405 final UserInfo parent = getProfileParent(userId); 5406 if (parent != null) { 5407 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5408 flags, userId, parent.id); 5409 } 5410 if (xpDomainInfo != null) { 5411 if (xpResolveInfo != null) { 5412 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5413 // in the result. 5414 result.remove(xpResolveInfo); 5415 } 5416 if (result.size() == 0 && !addEphemeral) { 5417 result.add(xpDomainInfo.resolveInfo); 5418 return result; 5419 } 5420 } 5421 if (result.size() > 1 || addEphemeral) { 5422 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5423 intent, flags, result, xpDomainInfo, userId); 5424 sortResult = true; 5425 } 5426 } 5427 } else { 5428 final PackageParser.Package pkg = mPackages.get(pkgName); 5429 if (pkg != null) { 5430 result = filterIfNotSystemUser( 5431 mActivities.queryIntentForPackage( 5432 intent, resolvedType, flags, pkg.activities, userId), 5433 userId); 5434 } else { 5435 // the caller wants to resolve for a particular package; however, there 5436 // were no installed results, so, try to find an ephemeral result 5437 addEphemeral = isEphemeralAllowed( 5438 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5439 matchEphemeralPackage = true; 5440 result = new ArrayList<ResolveInfo>(); 5441 } 5442 } 5443 } 5444 if (addEphemeral) { 5445 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5446 final EphemeralResolveInfo ai = getEphemeralResolveInfo( 5447 mContext, mEphemeralResolverConnection, intent, resolvedType, userId, 5448 matchEphemeralPackage ? pkgName : null); 5449 if (ai != null) { 5450 if (DEBUG_EPHEMERAL) { 5451 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5452 } 5453 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5454 ephemeralInstaller.ephemeralResolveInfo = ai; 5455 // make sure this resolver is the default 5456 ephemeralInstaller.isDefault = true; 5457 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5458 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5459 // add a non-generic filter 5460 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5461 ephemeralInstaller.filter.addDataPath( 5462 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5463 result.add(ephemeralInstaller); 5464 } 5465 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5466 } 5467 if (sortResult) { 5468 Collections.sort(result, mResolvePrioritySorter); 5469 } 5470 return result; 5471 } 5472 5473 private static class CrossProfileDomainInfo { 5474 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5475 ResolveInfo resolveInfo; 5476 /* Best domain verification status of the activities found in the other profile */ 5477 int bestDomainVerificationStatus; 5478 } 5479 5480 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5481 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5482 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5483 sourceUserId)) { 5484 return null; 5485 } 5486 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5487 resolvedType, flags, parentUserId); 5488 5489 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5490 return null; 5491 } 5492 CrossProfileDomainInfo result = null; 5493 int size = resultTargetUser.size(); 5494 for (int i = 0; i < size; i++) { 5495 ResolveInfo riTargetUser = resultTargetUser.get(i); 5496 // Intent filter verification is only for filters that specify a host. So don't return 5497 // those that handle all web uris. 5498 if (riTargetUser.handleAllWebDataURI) { 5499 continue; 5500 } 5501 String packageName = riTargetUser.activityInfo.packageName; 5502 PackageSetting ps = mSettings.mPackages.get(packageName); 5503 if (ps == null) { 5504 continue; 5505 } 5506 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5507 int status = (int)(verificationState >> 32); 5508 if (result == null) { 5509 result = new CrossProfileDomainInfo(); 5510 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5511 sourceUserId, parentUserId); 5512 result.bestDomainVerificationStatus = status; 5513 } else { 5514 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5515 result.bestDomainVerificationStatus); 5516 } 5517 } 5518 // Don't consider matches with status NEVER across profiles. 5519 if (result != null && result.bestDomainVerificationStatus 5520 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5521 return null; 5522 } 5523 return result; 5524 } 5525 5526 /** 5527 * Verification statuses are ordered from the worse to the best, except for 5528 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5529 */ 5530 private int bestDomainVerificationStatus(int status1, int status2) { 5531 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5532 return status2; 5533 } 5534 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5535 return status1; 5536 } 5537 return (int) MathUtils.max(status1, status2); 5538 } 5539 5540 private boolean isUserEnabled(int userId) { 5541 long callingId = Binder.clearCallingIdentity(); 5542 try { 5543 UserInfo userInfo = sUserManager.getUserInfo(userId); 5544 return userInfo != null && userInfo.isEnabled(); 5545 } finally { 5546 Binder.restoreCallingIdentity(callingId); 5547 } 5548 } 5549 5550 /** 5551 * Filter out activities with systemUserOnly flag set, when current user is not System. 5552 * 5553 * @return filtered list 5554 */ 5555 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5556 if (userId == UserHandle.USER_SYSTEM) { 5557 return resolveInfos; 5558 } 5559 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5560 ResolveInfo info = resolveInfos.get(i); 5561 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5562 resolveInfos.remove(i); 5563 } 5564 } 5565 return resolveInfos; 5566 } 5567 5568 /** 5569 * @param resolveInfos list of resolve infos in descending priority order 5570 * @return if the list contains a resolve info with non-negative priority 5571 */ 5572 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5573 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5574 } 5575 5576 private static boolean hasWebURI(Intent intent) { 5577 if (intent.getData() == null) { 5578 return false; 5579 } 5580 final String scheme = intent.getScheme(); 5581 if (TextUtils.isEmpty(scheme)) { 5582 return false; 5583 } 5584 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5585 } 5586 5587 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5588 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5589 int userId) { 5590 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5591 5592 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5593 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5594 candidates.size()); 5595 } 5596 5597 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5598 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5599 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5600 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5601 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5602 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5603 5604 synchronized (mPackages) { 5605 final int count = candidates.size(); 5606 // First, try to use linked apps. Partition the candidates into four lists: 5607 // one for the final results, one for the "do not use ever", one for "undefined status" 5608 // and finally one for "browser app type". 5609 for (int n=0; n<count; n++) { 5610 ResolveInfo info = candidates.get(n); 5611 String packageName = info.activityInfo.packageName; 5612 PackageSetting ps = mSettings.mPackages.get(packageName); 5613 if (ps != null) { 5614 // Add to the special match all list (Browser use case) 5615 if (info.handleAllWebDataURI) { 5616 matchAllList.add(info); 5617 continue; 5618 } 5619 // Try to get the status from User settings first 5620 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5621 int status = (int)(packedStatus >> 32); 5622 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5623 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5624 if (DEBUG_DOMAIN_VERIFICATION) { 5625 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5626 + " : linkgen=" + linkGeneration); 5627 } 5628 // Use link-enabled generation as preferredOrder, i.e. 5629 // prefer newly-enabled over earlier-enabled. 5630 info.preferredOrder = linkGeneration; 5631 alwaysList.add(info); 5632 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5633 if (DEBUG_DOMAIN_VERIFICATION) { 5634 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5635 } 5636 neverList.add(info); 5637 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5638 if (DEBUG_DOMAIN_VERIFICATION) { 5639 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5640 } 5641 alwaysAskList.add(info); 5642 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5643 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5644 if (DEBUG_DOMAIN_VERIFICATION) { 5645 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5646 } 5647 undefinedList.add(info); 5648 } 5649 } 5650 } 5651 5652 // We'll want to include browser possibilities in a few cases 5653 boolean includeBrowser = false; 5654 5655 // First try to add the "always" resolution(s) for the current user, if any 5656 if (alwaysList.size() > 0) { 5657 result.addAll(alwaysList); 5658 } else { 5659 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5660 result.addAll(undefinedList); 5661 // Maybe add one for the other profile. 5662 if (xpDomainInfo != null && ( 5663 xpDomainInfo.bestDomainVerificationStatus 5664 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5665 result.add(xpDomainInfo.resolveInfo); 5666 } 5667 includeBrowser = true; 5668 } 5669 5670 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5671 // If there were 'always' entries their preferred order has been set, so we also 5672 // back that off to make the alternatives equivalent 5673 if (alwaysAskList.size() > 0) { 5674 for (ResolveInfo i : result) { 5675 i.preferredOrder = 0; 5676 } 5677 result.addAll(alwaysAskList); 5678 includeBrowser = true; 5679 } 5680 5681 if (includeBrowser) { 5682 // Also add browsers (all of them or only the default one) 5683 if (DEBUG_DOMAIN_VERIFICATION) { 5684 Slog.v(TAG, " ...including browsers in candidate set"); 5685 } 5686 if ((matchFlags & MATCH_ALL) != 0) { 5687 result.addAll(matchAllList); 5688 } else { 5689 // Browser/generic handling case. If there's a default browser, go straight 5690 // to that (but only if there is no other higher-priority match). 5691 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5692 int maxMatchPrio = 0; 5693 ResolveInfo defaultBrowserMatch = null; 5694 final int numCandidates = matchAllList.size(); 5695 for (int n = 0; n < numCandidates; n++) { 5696 ResolveInfo info = matchAllList.get(n); 5697 // track the highest overall match priority... 5698 if (info.priority > maxMatchPrio) { 5699 maxMatchPrio = info.priority; 5700 } 5701 // ...and the highest-priority default browser match 5702 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5703 if (defaultBrowserMatch == null 5704 || (defaultBrowserMatch.priority < info.priority)) { 5705 if (debug) { 5706 Slog.v(TAG, "Considering default browser match " + info); 5707 } 5708 defaultBrowserMatch = info; 5709 } 5710 } 5711 } 5712 if (defaultBrowserMatch != null 5713 && defaultBrowserMatch.priority >= maxMatchPrio 5714 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5715 { 5716 if (debug) { 5717 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5718 } 5719 result.add(defaultBrowserMatch); 5720 } else { 5721 result.addAll(matchAllList); 5722 } 5723 } 5724 5725 // If there is nothing selected, add all candidates and remove the ones that the user 5726 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5727 if (result.size() == 0) { 5728 result.addAll(candidates); 5729 result.removeAll(neverList); 5730 } 5731 } 5732 } 5733 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5734 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5735 result.size()); 5736 for (ResolveInfo info : result) { 5737 Slog.v(TAG, " + " + info.activityInfo); 5738 } 5739 } 5740 return result; 5741 } 5742 5743 // Returns a packed value as a long: 5744 // 5745 // high 'int'-sized word: link status: undefined/ask/never/always. 5746 // low 'int'-sized word: relative priority among 'always' results. 5747 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5748 long result = ps.getDomainVerificationStatusForUser(userId); 5749 // if none available, get the master status 5750 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5751 if (ps.getIntentFilterVerificationInfo() != null) { 5752 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5753 } 5754 } 5755 return result; 5756 } 5757 5758 private ResolveInfo querySkipCurrentProfileIntents( 5759 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5760 int flags, int sourceUserId) { 5761 if (matchingFilters != null) { 5762 int size = matchingFilters.size(); 5763 for (int i = 0; i < size; i ++) { 5764 CrossProfileIntentFilter filter = matchingFilters.get(i); 5765 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5766 // Checking if there are activities in the target user that can handle the 5767 // intent. 5768 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5769 resolvedType, flags, sourceUserId); 5770 if (resolveInfo != null) { 5771 return resolveInfo; 5772 } 5773 } 5774 } 5775 } 5776 return null; 5777 } 5778 5779 // Return matching ResolveInfo in target user if any. 5780 private ResolveInfo queryCrossProfileIntents( 5781 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5782 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5783 if (matchingFilters != null) { 5784 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5785 // match the same intent. For performance reasons, it is better not to 5786 // run queryIntent twice for the same userId 5787 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5788 int size = matchingFilters.size(); 5789 for (int i = 0; i < size; i++) { 5790 CrossProfileIntentFilter filter = matchingFilters.get(i); 5791 int targetUserId = filter.getTargetUserId(); 5792 boolean skipCurrentProfile = 5793 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5794 boolean skipCurrentProfileIfNoMatchFound = 5795 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5796 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5797 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5798 // Checking if there are activities in the target user that can handle the 5799 // intent. 5800 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5801 resolvedType, flags, sourceUserId); 5802 if (resolveInfo != null) return resolveInfo; 5803 alreadyTriedUserIds.put(targetUserId, true); 5804 } 5805 } 5806 } 5807 return null; 5808 } 5809 5810 /** 5811 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5812 * will forward the intent to the filter's target user. 5813 * Otherwise, returns null. 5814 */ 5815 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5816 String resolvedType, int flags, int sourceUserId) { 5817 int targetUserId = filter.getTargetUserId(); 5818 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5819 resolvedType, flags, targetUserId); 5820 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5821 // If all the matches in the target profile are suspended, return null. 5822 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5823 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5824 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5825 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5826 targetUserId); 5827 } 5828 } 5829 } 5830 return null; 5831 } 5832 5833 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5834 int sourceUserId, int targetUserId) { 5835 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5836 long ident = Binder.clearCallingIdentity(); 5837 boolean targetIsProfile; 5838 try { 5839 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5840 } finally { 5841 Binder.restoreCallingIdentity(ident); 5842 } 5843 String className; 5844 if (targetIsProfile) { 5845 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5846 } else { 5847 className = FORWARD_INTENT_TO_PARENT; 5848 } 5849 ComponentName forwardingActivityComponentName = new ComponentName( 5850 mAndroidApplication.packageName, className); 5851 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5852 sourceUserId); 5853 if (!targetIsProfile) { 5854 forwardingActivityInfo.showUserIcon = targetUserId; 5855 forwardingResolveInfo.noResourceId = true; 5856 } 5857 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5858 forwardingResolveInfo.priority = 0; 5859 forwardingResolveInfo.preferredOrder = 0; 5860 forwardingResolveInfo.match = 0; 5861 forwardingResolveInfo.isDefault = true; 5862 forwardingResolveInfo.filter = filter; 5863 forwardingResolveInfo.targetUserId = targetUserId; 5864 return forwardingResolveInfo; 5865 } 5866 5867 @Override 5868 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5869 Intent[] specifics, String[] specificTypes, Intent intent, 5870 String resolvedType, int flags, int userId) { 5871 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5872 specificTypes, intent, resolvedType, flags, userId)); 5873 } 5874 5875 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5876 Intent[] specifics, String[] specificTypes, Intent intent, 5877 String resolvedType, int flags, int userId) { 5878 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5879 flags = updateFlagsForResolve(flags, userId, intent); 5880 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5881 false /* requireFullPermission */, false /* checkShell */, 5882 "query intent activity options"); 5883 final String resultsAction = intent.getAction(); 5884 5885 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5886 | PackageManager.GET_RESOLVED_FILTER, userId); 5887 5888 if (DEBUG_INTENT_MATCHING) { 5889 Log.v(TAG, "Query " + intent + ": " + results); 5890 } 5891 5892 int specificsPos = 0; 5893 int N; 5894 5895 // todo: note that the algorithm used here is O(N^2). This 5896 // isn't a problem in our current environment, but if we start running 5897 // into situations where we have more than 5 or 10 matches then this 5898 // should probably be changed to something smarter... 5899 5900 // First we go through and resolve each of the specific items 5901 // that were supplied, taking care of removing any corresponding 5902 // duplicate items in the generic resolve list. 5903 if (specifics != null) { 5904 for (int i=0; i<specifics.length; i++) { 5905 final Intent sintent = specifics[i]; 5906 if (sintent == null) { 5907 continue; 5908 } 5909 5910 if (DEBUG_INTENT_MATCHING) { 5911 Log.v(TAG, "Specific #" + i + ": " + sintent); 5912 } 5913 5914 String action = sintent.getAction(); 5915 if (resultsAction != null && resultsAction.equals(action)) { 5916 // If this action was explicitly requested, then don't 5917 // remove things that have it. 5918 action = null; 5919 } 5920 5921 ResolveInfo ri = null; 5922 ActivityInfo ai = null; 5923 5924 ComponentName comp = sintent.getComponent(); 5925 if (comp == null) { 5926 ri = resolveIntent( 5927 sintent, 5928 specificTypes != null ? specificTypes[i] : null, 5929 flags, userId); 5930 if (ri == null) { 5931 continue; 5932 } 5933 if (ri == mResolveInfo) { 5934 // ACK! Must do something better with this. 5935 } 5936 ai = ri.activityInfo; 5937 comp = new ComponentName(ai.applicationInfo.packageName, 5938 ai.name); 5939 } else { 5940 ai = getActivityInfo(comp, flags, userId); 5941 if (ai == null) { 5942 continue; 5943 } 5944 } 5945 5946 // Look for any generic query activities that are duplicates 5947 // of this specific one, and remove them from the results. 5948 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5949 N = results.size(); 5950 int j; 5951 for (j=specificsPos; j<N; j++) { 5952 ResolveInfo sri = results.get(j); 5953 if ((sri.activityInfo.name.equals(comp.getClassName()) 5954 && sri.activityInfo.applicationInfo.packageName.equals( 5955 comp.getPackageName())) 5956 || (action != null && sri.filter.matchAction(action))) { 5957 results.remove(j); 5958 if (DEBUG_INTENT_MATCHING) Log.v( 5959 TAG, "Removing duplicate item from " + j 5960 + " due to specific " + specificsPos); 5961 if (ri == null) { 5962 ri = sri; 5963 } 5964 j--; 5965 N--; 5966 } 5967 } 5968 5969 // Add this specific item to its proper place. 5970 if (ri == null) { 5971 ri = new ResolveInfo(); 5972 ri.activityInfo = ai; 5973 } 5974 results.add(specificsPos, ri); 5975 ri.specificIndex = i; 5976 specificsPos++; 5977 } 5978 } 5979 5980 // Now we go through the remaining generic results and remove any 5981 // duplicate actions that are found here. 5982 N = results.size(); 5983 for (int i=specificsPos; i<N-1; i++) { 5984 final ResolveInfo rii = results.get(i); 5985 if (rii.filter == null) { 5986 continue; 5987 } 5988 5989 // Iterate over all of the actions of this result's intent 5990 // filter... typically this should be just one. 5991 final Iterator<String> it = rii.filter.actionsIterator(); 5992 if (it == null) { 5993 continue; 5994 } 5995 while (it.hasNext()) { 5996 final String action = it.next(); 5997 if (resultsAction != null && resultsAction.equals(action)) { 5998 // If this action was explicitly requested, then don't 5999 // remove things that have it. 6000 continue; 6001 } 6002 for (int j=i+1; j<N; j++) { 6003 final ResolveInfo rij = results.get(j); 6004 if (rij.filter != null && rij.filter.hasAction(action)) { 6005 results.remove(j); 6006 if (DEBUG_INTENT_MATCHING) Log.v( 6007 TAG, "Removing duplicate item from " + j 6008 + " due to action " + action + " at " + i); 6009 j--; 6010 N--; 6011 } 6012 } 6013 } 6014 6015 // If the caller didn't request filter information, drop it now 6016 // so we don't have to marshall/unmarshall it. 6017 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6018 rii.filter = null; 6019 } 6020 } 6021 6022 // Filter out the caller activity if so requested. 6023 if (caller != null) { 6024 N = results.size(); 6025 for (int i=0; i<N; i++) { 6026 ActivityInfo ainfo = results.get(i).activityInfo; 6027 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6028 && caller.getClassName().equals(ainfo.name)) { 6029 results.remove(i); 6030 break; 6031 } 6032 } 6033 } 6034 6035 // If the caller didn't request filter information, 6036 // drop them now so we don't have to 6037 // marshall/unmarshall it. 6038 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6039 N = results.size(); 6040 for (int i=0; i<N; i++) { 6041 results.get(i).filter = null; 6042 } 6043 } 6044 6045 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6046 return results; 6047 } 6048 6049 @Override 6050 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6051 String resolvedType, int flags, int userId) { 6052 return new ParceledListSlice<>( 6053 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6054 } 6055 6056 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6057 String resolvedType, int flags, int userId) { 6058 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6059 flags = updateFlagsForResolve(flags, userId, intent); 6060 ComponentName comp = intent.getComponent(); 6061 if (comp == null) { 6062 if (intent.getSelector() != null) { 6063 intent = intent.getSelector(); 6064 comp = intent.getComponent(); 6065 } 6066 } 6067 if (comp != null) { 6068 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6069 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6070 if (ai != null) { 6071 ResolveInfo ri = new ResolveInfo(); 6072 ri.activityInfo = ai; 6073 list.add(ri); 6074 } 6075 return list; 6076 } 6077 6078 // reader 6079 synchronized (mPackages) { 6080 String pkgName = intent.getPackage(); 6081 if (pkgName == null) { 6082 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6083 } 6084 final PackageParser.Package pkg = mPackages.get(pkgName); 6085 if (pkg != null) { 6086 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6087 userId); 6088 } 6089 return Collections.emptyList(); 6090 } 6091 } 6092 6093 @Override 6094 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6095 if (!sUserManager.exists(userId)) return null; 6096 flags = updateFlagsForResolve(flags, userId, intent); 6097 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6098 if (query != null) { 6099 if (query.size() >= 1) { 6100 // If there is more than one service with the same priority, 6101 // just arbitrarily pick the first one. 6102 return query.get(0); 6103 } 6104 } 6105 return null; 6106 } 6107 6108 @Override 6109 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6110 String resolvedType, int flags, int userId) { 6111 return new ParceledListSlice<>( 6112 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6113 } 6114 6115 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6116 String resolvedType, int flags, int userId) { 6117 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6118 flags = updateFlagsForResolve(flags, userId, intent); 6119 ComponentName comp = intent.getComponent(); 6120 if (comp == null) { 6121 if (intent.getSelector() != null) { 6122 intent = intent.getSelector(); 6123 comp = intent.getComponent(); 6124 } 6125 } 6126 if (comp != null) { 6127 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6128 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6129 if (si != null) { 6130 final ResolveInfo ri = new ResolveInfo(); 6131 ri.serviceInfo = si; 6132 list.add(ri); 6133 } 6134 return list; 6135 } 6136 6137 // reader 6138 synchronized (mPackages) { 6139 String pkgName = intent.getPackage(); 6140 if (pkgName == null) { 6141 return mServices.queryIntent(intent, resolvedType, flags, userId); 6142 } 6143 final PackageParser.Package pkg = mPackages.get(pkgName); 6144 if (pkg != null) { 6145 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6146 userId); 6147 } 6148 return Collections.emptyList(); 6149 } 6150 } 6151 6152 @Override 6153 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6154 String resolvedType, int flags, int userId) { 6155 return new ParceledListSlice<>( 6156 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6157 } 6158 6159 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6160 Intent intent, String resolvedType, int flags, int userId) { 6161 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6162 flags = updateFlagsForResolve(flags, userId, intent); 6163 ComponentName comp = intent.getComponent(); 6164 if (comp == null) { 6165 if (intent.getSelector() != null) { 6166 intent = intent.getSelector(); 6167 comp = intent.getComponent(); 6168 } 6169 } 6170 if (comp != null) { 6171 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6172 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6173 if (pi != null) { 6174 final ResolveInfo ri = new ResolveInfo(); 6175 ri.providerInfo = pi; 6176 list.add(ri); 6177 } 6178 return list; 6179 } 6180 6181 // reader 6182 synchronized (mPackages) { 6183 String pkgName = intent.getPackage(); 6184 if (pkgName == null) { 6185 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6186 } 6187 final PackageParser.Package pkg = mPackages.get(pkgName); 6188 if (pkg != null) { 6189 return mProviders.queryIntentForPackage( 6190 intent, resolvedType, flags, pkg.providers, userId); 6191 } 6192 return Collections.emptyList(); 6193 } 6194 } 6195 6196 @Override 6197 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6198 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6199 flags = updateFlagsForPackage(flags, userId, null); 6200 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6201 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6202 true /* requireFullPermission */, false /* checkShell */, 6203 "get installed packages"); 6204 6205 // writer 6206 synchronized (mPackages) { 6207 ArrayList<PackageInfo> list; 6208 if (listUninstalled) { 6209 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6210 for (PackageSetting ps : mSettings.mPackages.values()) { 6211 final PackageInfo pi; 6212 if (ps.pkg != null) { 6213 pi = generatePackageInfo(ps, flags, userId); 6214 } else { 6215 pi = generatePackageInfo(ps, flags, userId); 6216 } 6217 if (pi != null) { 6218 list.add(pi); 6219 } 6220 } 6221 } else { 6222 list = new ArrayList<PackageInfo>(mPackages.size()); 6223 for (PackageParser.Package p : mPackages.values()) { 6224 final PackageInfo pi = 6225 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6226 if (pi != null) { 6227 list.add(pi); 6228 } 6229 } 6230 } 6231 6232 return new ParceledListSlice<PackageInfo>(list); 6233 } 6234 } 6235 6236 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6237 String[] permissions, boolean[] tmp, int flags, int userId) { 6238 int numMatch = 0; 6239 final PermissionsState permissionsState = ps.getPermissionsState(); 6240 for (int i=0; i<permissions.length; i++) { 6241 final String permission = permissions[i]; 6242 if (permissionsState.hasPermission(permission, userId)) { 6243 tmp[i] = true; 6244 numMatch++; 6245 } else { 6246 tmp[i] = false; 6247 } 6248 } 6249 if (numMatch == 0) { 6250 return; 6251 } 6252 final PackageInfo pi; 6253 if (ps.pkg != null) { 6254 pi = generatePackageInfo(ps, flags, userId); 6255 } else { 6256 pi = generatePackageInfo(ps, flags, userId); 6257 } 6258 // The above might return null in cases of uninstalled apps or install-state 6259 // skew across users/profiles. 6260 if (pi != null) { 6261 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6262 if (numMatch == permissions.length) { 6263 pi.requestedPermissions = permissions; 6264 } else { 6265 pi.requestedPermissions = new String[numMatch]; 6266 numMatch = 0; 6267 for (int i=0; i<permissions.length; i++) { 6268 if (tmp[i]) { 6269 pi.requestedPermissions[numMatch] = permissions[i]; 6270 numMatch++; 6271 } 6272 } 6273 } 6274 } 6275 list.add(pi); 6276 } 6277 } 6278 6279 @Override 6280 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6281 String[] permissions, int flags, int userId) { 6282 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6283 flags = updateFlagsForPackage(flags, userId, permissions); 6284 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6285 6286 // writer 6287 synchronized (mPackages) { 6288 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6289 boolean[] tmpBools = new boolean[permissions.length]; 6290 if (listUninstalled) { 6291 for (PackageSetting ps : mSettings.mPackages.values()) { 6292 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6293 } 6294 } else { 6295 for (PackageParser.Package pkg : mPackages.values()) { 6296 PackageSetting ps = (PackageSetting)pkg.mExtras; 6297 if (ps != null) { 6298 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6299 userId); 6300 } 6301 } 6302 } 6303 6304 return new ParceledListSlice<PackageInfo>(list); 6305 } 6306 } 6307 6308 @Override 6309 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6310 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6311 flags = updateFlagsForApplication(flags, userId, null); 6312 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6313 6314 // writer 6315 synchronized (mPackages) { 6316 ArrayList<ApplicationInfo> list; 6317 if (listUninstalled) { 6318 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6319 for (PackageSetting ps : mSettings.mPackages.values()) { 6320 ApplicationInfo ai; 6321 if (ps.pkg != null) { 6322 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6323 ps.readUserState(userId), userId); 6324 } else { 6325 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6326 } 6327 if (ai != null) { 6328 list.add(ai); 6329 } 6330 } 6331 } else { 6332 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6333 for (PackageParser.Package p : mPackages.values()) { 6334 if (p.mExtras != null) { 6335 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6336 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6337 if (ai != null) { 6338 list.add(ai); 6339 } 6340 } 6341 } 6342 } 6343 6344 return new ParceledListSlice<ApplicationInfo>(list); 6345 } 6346 } 6347 6348 @Override 6349 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6350 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6351 return null; 6352 } 6353 6354 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6355 "getEphemeralApplications"); 6356 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6357 true /* requireFullPermission */, false /* checkShell */, 6358 "getEphemeralApplications"); 6359 synchronized (mPackages) { 6360 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6361 .getEphemeralApplicationsLPw(userId); 6362 if (ephemeralApps != null) { 6363 return new ParceledListSlice<>(ephemeralApps); 6364 } 6365 } 6366 return null; 6367 } 6368 6369 @Override 6370 public boolean isEphemeralApplication(String packageName, int userId) { 6371 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6372 true /* requireFullPermission */, false /* checkShell */, 6373 "isEphemeral"); 6374 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6375 return false; 6376 } 6377 6378 if (!isCallerSameApp(packageName)) { 6379 return false; 6380 } 6381 synchronized (mPackages) { 6382 PackageParser.Package pkg = mPackages.get(packageName); 6383 if (pkg != null) { 6384 return pkg.applicationInfo.isEphemeralApp(); 6385 } 6386 } 6387 return false; 6388 } 6389 6390 @Override 6391 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6392 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6393 return null; 6394 } 6395 6396 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6397 true /* requireFullPermission */, false /* checkShell */, 6398 "getCookie"); 6399 if (!isCallerSameApp(packageName)) { 6400 return null; 6401 } 6402 synchronized (mPackages) { 6403 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6404 packageName, userId); 6405 } 6406 } 6407 6408 @Override 6409 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6410 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6411 return true; 6412 } 6413 6414 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6415 true /* requireFullPermission */, true /* checkShell */, 6416 "setCookie"); 6417 if (!isCallerSameApp(packageName)) { 6418 return false; 6419 } 6420 synchronized (mPackages) { 6421 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6422 packageName, cookie, userId); 6423 } 6424 } 6425 6426 @Override 6427 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6428 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6429 return null; 6430 } 6431 6432 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6433 "getEphemeralApplicationIcon"); 6434 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6435 true /* requireFullPermission */, false /* checkShell */, 6436 "getEphemeralApplicationIcon"); 6437 synchronized (mPackages) { 6438 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6439 packageName, userId); 6440 } 6441 } 6442 6443 private boolean isCallerSameApp(String packageName) { 6444 PackageParser.Package pkg = mPackages.get(packageName); 6445 return pkg != null 6446 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6447 } 6448 6449 @Override 6450 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6451 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6452 } 6453 6454 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6455 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6456 6457 // reader 6458 synchronized (mPackages) { 6459 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6460 final int userId = UserHandle.getCallingUserId(); 6461 while (i.hasNext()) { 6462 final PackageParser.Package p = i.next(); 6463 if (p.applicationInfo == null) continue; 6464 6465 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6466 && !p.applicationInfo.isDirectBootAware(); 6467 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6468 && p.applicationInfo.isDirectBootAware(); 6469 6470 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6471 && (!mSafeMode || isSystemApp(p)) 6472 && (matchesUnaware || matchesAware)) { 6473 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6474 if (ps != null) { 6475 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6476 ps.readUserState(userId), userId); 6477 if (ai != null) { 6478 finalList.add(ai); 6479 } 6480 } 6481 } 6482 } 6483 } 6484 6485 return finalList; 6486 } 6487 6488 @Override 6489 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6490 if (!sUserManager.exists(userId)) return null; 6491 flags = updateFlagsForComponent(flags, userId, name); 6492 // reader 6493 synchronized (mPackages) { 6494 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6495 PackageSetting ps = provider != null 6496 ? mSettings.mPackages.get(provider.owner.packageName) 6497 : null; 6498 return ps != null 6499 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6500 ? PackageParser.generateProviderInfo(provider, flags, 6501 ps.readUserState(userId), userId) 6502 : null; 6503 } 6504 } 6505 6506 /** 6507 * @deprecated 6508 */ 6509 @Deprecated 6510 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6511 // reader 6512 synchronized (mPackages) { 6513 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6514 .entrySet().iterator(); 6515 final int userId = UserHandle.getCallingUserId(); 6516 while (i.hasNext()) { 6517 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6518 PackageParser.Provider p = entry.getValue(); 6519 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6520 6521 if (ps != null && p.syncable 6522 && (!mSafeMode || (p.info.applicationInfo.flags 6523 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6524 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6525 ps.readUserState(userId), userId); 6526 if (info != null) { 6527 outNames.add(entry.getKey()); 6528 outInfo.add(info); 6529 } 6530 } 6531 } 6532 } 6533 } 6534 6535 @Override 6536 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6537 int uid, int flags) { 6538 final int userId = processName != null ? UserHandle.getUserId(uid) 6539 : UserHandle.getCallingUserId(); 6540 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6541 flags = updateFlagsForComponent(flags, userId, processName); 6542 6543 ArrayList<ProviderInfo> finalList = null; 6544 // reader 6545 synchronized (mPackages) { 6546 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6547 while (i.hasNext()) { 6548 final PackageParser.Provider p = i.next(); 6549 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6550 if (ps != null && p.info.authority != null 6551 && (processName == null 6552 || (p.info.processName.equals(processName) 6553 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6554 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6555 if (finalList == null) { 6556 finalList = new ArrayList<ProviderInfo>(3); 6557 } 6558 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6559 ps.readUserState(userId), userId); 6560 if (info != null) { 6561 finalList.add(info); 6562 } 6563 } 6564 } 6565 } 6566 6567 if (finalList != null) { 6568 Collections.sort(finalList, mProviderInitOrderSorter); 6569 return new ParceledListSlice<ProviderInfo>(finalList); 6570 } 6571 6572 return ParceledListSlice.emptyList(); 6573 } 6574 6575 @Override 6576 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6577 // reader 6578 synchronized (mPackages) { 6579 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6580 return PackageParser.generateInstrumentationInfo(i, flags); 6581 } 6582 } 6583 6584 @Override 6585 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6586 String targetPackage, int flags) { 6587 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6588 } 6589 6590 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6591 int flags) { 6592 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6593 6594 // reader 6595 synchronized (mPackages) { 6596 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6597 while (i.hasNext()) { 6598 final PackageParser.Instrumentation p = i.next(); 6599 if (targetPackage == null 6600 || targetPackage.equals(p.info.targetPackage)) { 6601 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6602 flags); 6603 if (ii != null) { 6604 finalList.add(ii); 6605 } 6606 } 6607 } 6608 } 6609 6610 return finalList; 6611 } 6612 6613 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6614 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6615 if (overlays == null) { 6616 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6617 return; 6618 } 6619 for (PackageParser.Package opkg : overlays.values()) { 6620 // Not much to do if idmap fails: we already logged the error 6621 // and we certainly don't want to abort installation of pkg simply 6622 // because an overlay didn't fit properly. For these reasons, 6623 // ignore the return value of createIdmapForPackagePairLI. 6624 createIdmapForPackagePairLI(pkg, opkg); 6625 } 6626 } 6627 6628 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6629 PackageParser.Package opkg) { 6630 if (!opkg.mTrustedOverlay) { 6631 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6632 opkg.baseCodePath + ": overlay not trusted"); 6633 return false; 6634 } 6635 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6636 if (overlaySet == null) { 6637 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6638 opkg.baseCodePath + " but target package has no known overlays"); 6639 return false; 6640 } 6641 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6642 // TODO: generate idmap for split APKs 6643 try { 6644 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6645 } catch (InstallerException e) { 6646 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6647 + opkg.baseCodePath); 6648 return false; 6649 } 6650 PackageParser.Package[] overlayArray = 6651 overlaySet.values().toArray(new PackageParser.Package[0]); 6652 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6653 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6654 return p1.mOverlayPriority - p2.mOverlayPriority; 6655 } 6656 }; 6657 Arrays.sort(overlayArray, cmp); 6658 6659 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6660 int i = 0; 6661 for (PackageParser.Package p : overlayArray) { 6662 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6663 } 6664 return true; 6665 } 6666 6667 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6668 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 6669 try { 6670 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6671 } finally { 6672 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6673 } 6674 } 6675 6676 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6677 final File[] files = dir.listFiles(); 6678 if (ArrayUtils.isEmpty(files)) { 6679 Log.d(TAG, "No files in app dir " + dir); 6680 return; 6681 } 6682 6683 if (DEBUG_PACKAGE_SCANNING) { 6684 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6685 + " flags=0x" + Integer.toHexString(parseFlags)); 6686 } 6687 6688 for (File file : files) { 6689 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6690 && !PackageInstallerService.isStageName(file.getName()); 6691 if (!isPackage) { 6692 // Ignore entries which are not packages 6693 continue; 6694 } 6695 try { 6696 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6697 scanFlags, currentTime, null); 6698 } catch (PackageManagerException e) { 6699 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6700 6701 // Delete invalid userdata apps 6702 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6703 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6704 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6705 removeCodePathLI(file); 6706 } 6707 } 6708 } 6709 } 6710 6711 private static File getSettingsProblemFile() { 6712 File dataDir = Environment.getDataDirectory(); 6713 File systemDir = new File(dataDir, "system"); 6714 File fname = new File(systemDir, "uiderrors.txt"); 6715 return fname; 6716 } 6717 6718 static void reportSettingsProblem(int priority, String msg) { 6719 logCriticalInfo(priority, msg); 6720 } 6721 6722 static void logCriticalInfo(int priority, String msg) { 6723 Slog.println(priority, TAG, msg); 6724 EventLogTags.writePmCriticalInfo(msg); 6725 try { 6726 File fname = getSettingsProblemFile(); 6727 FileOutputStream out = new FileOutputStream(fname, true); 6728 PrintWriter pw = new FastPrintWriter(out); 6729 SimpleDateFormat formatter = new SimpleDateFormat(); 6730 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6731 pw.println(dateString + ": " + msg); 6732 pw.close(); 6733 FileUtils.setPermissions( 6734 fname.toString(), 6735 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6736 -1, -1); 6737 } catch (java.io.IOException e) { 6738 } 6739 } 6740 6741 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6742 if (srcFile.isDirectory()) { 6743 final File baseFile = new File(pkg.baseCodePath); 6744 long maxModifiedTime = baseFile.lastModified(); 6745 if (pkg.splitCodePaths != null) { 6746 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6747 final File splitFile = new File(pkg.splitCodePaths[i]); 6748 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6749 } 6750 } 6751 return maxModifiedTime; 6752 } 6753 return srcFile.lastModified(); 6754 } 6755 6756 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6757 final int policyFlags) throws PackageManagerException { 6758 // When upgrading from pre-N MR1, verify the package time stamp using the package 6759 // directory and not the APK file. 6760 final long lastModifiedTime = mIsPreNMR1Upgrade 6761 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 6762 if (ps != null 6763 && ps.codePath.equals(srcFile) 6764 && ps.timeStamp == lastModifiedTime 6765 && !isCompatSignatureUpdateNeeded(pkg) 6766 && !isRecoverSignatureUpdateNeeded(pkg)) { 6767 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6768 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6769 ArraySet<PublicKey> signingKs; 6770 synchronized (mPackages) { 6771 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6772 } 6773 if (ps.signatures.mSignatures != null 6774 && ps.signatures.mSignatures.length != 0 6775 && signingKs != null) { 6776 // Optimization: reuse the existing cached certificates 6777 // if the package appears to be unchanged. 6778 pkg.mSignatures = ps.signatures.mSignatures; 6779 pkg.mSigningKeys = signingKs; 6780 return; 6781 } 6782 6783 Slog.w(TAG, "PackageSetting for " + ps.name 6784 + " is missing signatures. Collecting certs again to recover them."); 6785 } else { 6786 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 6787 } 6788 6789 try { 6790 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 6791 PackageParser.collectCertificates(pkg, policyFlags); 6792 } catch (PackageParserException e) { 6793 throw PackageManagerException.from(e); 6794 } finally { 6795 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6796 } 6797 } 6798 6799 /** 6800 * Traces a package scan. 6801 * @see #scanPackageLI(File, int, int, long, UserHandle) 6802 */ 6803 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6804 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6805 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 6806 try { 6807 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6808 } finally { 6809 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6810 } 6811 } 6812 6813 /** 6814 * Scans a package and returns the newly parsed package. 6815 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6816 */ 6817 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6818 long currentTime, UserHandle user) throws PackageManagerException { 6819 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6820 PackageParser pp = new PackageParser(); 6821 pp.setSeparateProcesses(mSeparateProcesses); 6822 pp.setOnlyCoreApps(mOnlyCore); 6823 pp.setDisplayMetrics(mMetrics); 6824 6825 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6826 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6827 } 6828 6829 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6830 final PackageParser.Package pkg; 6831 try { 6832 pkg = pp.parsePackage(scanFile, parseFlags); 6833 } catch (PackageParserException e) { 6834 throw PackageManagerException.from(e); 6835 } finally { 6836 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6837 } 6838 6839 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6840 } 6841 6842 /** 6843 * Scans a package and returns the newly parsed package. 6844 * @throws PackageManagerException on a parse error. 6845 */ 6846 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6847 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6848 throws PackageManagerException { 6849 // If the package has children and this is the first dive in the function 6850 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6851 // packages (parent and children) would be successfully scanned before the 6852 // actual scan since scanning mutates internal state and we want to atomically 6853 // install the package and its children. 6854 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6855 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6856 scanFlags |= SCAN_CHECK_ONLY; 6857 } 6858 } else { 6859 scanFlags &= ~SCAN_CHECK_ONLY; 6860 } 6861 6862 // Scan the parent 6863 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6864 scanFlags, currentTime, user); 6865 6866 // Scan the children 6867 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6868 for (int i = 0; i < childCount; i++) { 6869 PackageParser.Package childPackage = pkg.childPackages.get(i); 6870 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6871 currentTime, user); 6872 } 6873 6874 6875 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6876 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6877 } 6878 6879 return scannedPkg; 6880 } 6881 6882 /** 6883 * Scans a package and returns the newly parsed package. 6884 * @throws PackageManagerException on a parse error. 6885 */ 6886 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6887 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6888 throws PackageManagerException { 6889 PackageSetting ps = null; 6890 PackageSetting updatedPkg; 6891 // reader 6892 synchronized (mPackages) { 6893 // Look to see if we already know about this package. 6894 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 6895 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6896 // This package has been renamed to its original name. Let's 6897 // use that. 6898 ps = mSettings.peekPackageLPr(oldName); 6899 } 6900 // If there was no original package, see one for the real package name. 6901 if (ps == null) { 6902 ps = mSettings.peekPackageLPr(pkg.packageName); 6903 } 6904 // Check to see if this package could be hiding/updating a system 6905 // package. Must look for it either under the original or real 6906 // package name depending on our state. 6907 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6908 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6909 6910 // If this is a package we don't know about on the system partition, we 6911 // may need to remove disabled child packages on the system partition 6912 // or may need to not add child packages if the parent apk is updated 6913 // on the data partition and no longer defines this child package. 6914 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6915 // If this is a parent package for an updated system app and this system 6916 // app got an OTA update which no longer defines some of the child packages 6917 // we have to prune them from the disabled system packages. 6918 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6919 if (disabledPs != null) { 6920 final int scannedChildCount = (pkg.childPackages != null) 6921 ? pkg.childPackages.size() : 0; 6922 final int disabledChildCount = disabledPs.childPackageNames != null 6923 ? disabledPs.childPackageNames.size() : 0; 6924 for (int i = 0; i < disabledChildCount; i++) { 6925 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6926 boolean disabledPackageAvailable = false; 6927 for (int j = 0; j < scannedChildCount; j++) { 6928 PackageParser.Package childPkg = pkg.childPackages.get(j); 6929 if (childPkg.packageName.equals(disabledChildPackageName)) { 6930 disabledPackageAvailable = true; 6931 break; 6932 } 6933 } 6934 if (!disabledPackageAvailable) { 6935 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6936 } 6937 } 6938 } 6939 } 6940 } 6941 6942 boolean updatedPkgBetter = false; 6943 // First check if this is a system package that may involve an update 6944 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6945 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6946 // it needs to drop FLAG_PRIVILEGED. 6947 if (locationIsPrivileged(scanFile)) { 6948 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6949 } else { 6950 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6951 } 6952 6953 if (ps != null && !ps.codePath.equals(scanFile)) { 6954 // The path has changed from what was last scanned... check the 6955 // version of the new path against what we have stored to determine 6956 // what to do. 6957 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6958 if (pkg.mVersionCode <= ps.versionCode) { 6959 // The system package has been updated and the code path does not match 6960 // Ignore entry. Skip it. 6961 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6962 + " ignored: updated version " + ps.versionCode 6963 + " better than this " + pkg.mVersionCode); 6964 if (!updatedPkg.codePath.equals(scanFile)) { 6965 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6966 + ps.name + " changing from " + updatedPkg.codePathString 6967 + " to " + scanFile); 6968 updatedPkg.codePath = scanFile; 6969 updatedPkg.codePathString = scanFile.toString(); 6970 updatedPkg.resourcePath = scanFile; 6971 updatedPkg.resourcePathString = scanFile.toString(); 6972 } 6973 updatedPkg.pkg = pkg; 6974 updatedPkg.versionCode = pkg.mVersionCode; 6975 6976 // Update the disabled system child packages to point to the package too. 6977 final int childCount = updatedPkg.childPackageNames != null 6978 ? updatedPkg.childPackageNames.size() : 0; 6979 for (int i = 0; i < childCount; i++) { 6980 String childPackageName = updatedPkg.childPackageNames.get(i); 6981 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6982 childPackageName); 6983 if (updatedChildPkg != null) { 6984 updatedChildPkg.pkg = pkg; 6985 updatedChildPkg.versionCode = pkg.mVersionCode; 6986 } 6987 } 6988 6989 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6990 + scanFile + " ignored: updated version " + ps.versionCode 6991 + " better than this " + pkg.mVersionCode); 6992 } else { 6993 // The current app on the system partition is better than 6994 // what we have updated to on the data partition; switch 6995 // back to the system partition version. 6996 // At this point, its safely assumed that package installation for 6997 // apps in system partition will go through. If not there won't be a working 6998 // version of the app 6999 // writer 7000 synchronized (mPackages) { 7001 // Just remove the loaded entries from package lists. 7002 mPackages.remove(ps.name); 7003 } 7004 7005 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7006 + " reverting from " + ps.codePathString 7007 + ": new version " + pkg.mVersionCode 7008 + " better than installed " + ps.versionCode); 7009 7010 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7011 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7012 synchronized (mInstallLock) { 7013 args.cleanUpResourcesLI(); 7014 } 7015 synchronized (mPackages) { 7016 mSettings.enableSystemPackageLPw(ps.name); 7017 } 7018 updatedPkgBetter = true; 7019 } 7020 } 7021 } 7022 7023 if (updatedPkg != null) { 7024 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7025 // initially 7026 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7027 7028 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7029 // flag set initially 7030 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7031 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7032 } 7033 } 7034 7035 // Verify certificates against what was last scanned 7036 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7037 7038 /* 7039 * A new system app appeared, but we already had a non-system one of the 7040 * same name installed earlier. 7041 */ 7042 boolean shouldHideSystemApp = false; 7043 if (updatedPkg == null && ps != null 7044 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7045 /* 7046 * Check to make sure the signatures match first. If they don't, 7047 * wipe the installed application and its data. 7048 */ 7049 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7050 != PackageManager.SIGNATURE_MATCH) { 7051 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7052 + " signatures don't match existing userdata copy; removing"); 7053 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7054 "scanPackageInternalLI")) { 7055 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7056 } 7057 ps = null; 7058 } else { 7059 /* 7060 * If the newly-added system app is an older version than the 7061 * already installed version, hide it. It will be scanned later 7062 * and re-added like an update. 7063 */ 7064 if (pkg.mVersionCode <= ps.versionCode) { 7065 shouldHideSystemApp = true; 7066 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7067 + " but new version " + pkg.mVersionCode + " better than installed " 7068 + ps.versionCode + "; hiding system"); 7069 } else { 7070 /* 7071 * The newly found system app is a newer version that the 7072 * one previously installed. Simply remove the 7073 * already-installed application and replace it with our own 7074 * while keeping the application data. 7075 */ 7076 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7077 + " reverting from " + ps.codePathString + ": new version " 7078 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7079 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7080 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7081 synchronized (mInstallLock) { 7082 args.cleanUpResourcesLI(); 7083 } 7084 } 7085 } 7086 } 7087 7088 // The apk is forward locked (not public) if its code and resources 7089 // are kept in different files. (except for app in either system or 7090 // vendor path). 7091 // TODO grab this value from PackageSettings 7092 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7093 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7094 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7095 } 7096 } 7097 7098 // TODO: extend to support forward-locked splits 7099 String resourcePath = null; 7100 String baseResourcePath = null; 7101 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7102 if (ps != null && ps.resourcePathString != null) { 7103 resourcePath = ps.resourcePathString; 7104 baseResourcePath = ps.resourcePathString; 7105 } else { 7106 // Should not happen at all. Just log an error. 7107 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7108 } 7109 } else { 7110 resourcePath = pkg.codePath; 7111 baseResourcePath = pkg.baseCodePath; 7112 } 7113 7114 // Set application objects path explicitly. 7115 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7116 pkg.setApplicationInfoCodePath(pkg.codePath); 7117 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7118 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7119 pkg.setApplicationInfoResourcePath(resourcePath); 7120 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7121 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7122 7123 // Note that we invoke the following method only if we are about to unpack an application 7124 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7125 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7126 7127 /* 7128 * If the system app should be overridden by a previously installed 7129 * data, hide the system app now and let the /data/app scan pick it up 7130 * again. 7131 */ 7132 if (shouldHideSystemApp) { 7133 synchronized (mPackages) { 7134 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7135 } 7136 } 7137 7138 return scannedPkg; 7139 } 7140 7141 private static String fixProcessName(String defProcessName, 7142 String processName, int uid) { 7143 if (processName == null) { 7144 return defProcessName; 7145 } 7146 return processName; 7147 } 7148 7149 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7150 throws PackageManagerException { 7151 if (pkgSetting.signatures.mSignatures != null) { 7152 // Already existing package. Make sure signatures match 7153 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7154 == PackageManager.SIGNATURE_MATCH; 7155 if (!match) { 7156 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7157 == PackageManager.SIGNATURE_MATCH; 7158 } 7159 if (!match) { 7160 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7161 == PackageManager.SIGNATURE_MATCH; 7162 } 7163 if (!match) { 7164 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7165 + pkg.packageName + " signatures do not match the " 7166 + "previously installed version; ignoring!"); 7167 } 7168 } 7169 7170 // Check for shared user signatures 7171 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7172 // Already existing package. Make sure signatures match 7173 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7174 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7175 if (!match) { 7176 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7177 == PackageManager.SIGNATURE_MATCH; 7178 } 7179 if (!match) { 7180 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7181 == PackageManager.SIGNATURE_MATCH; 7182 } 7183 if (!match) { 7184 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7185 "Package " + pkg.packageName 7186 + " has no signatures that match those in shared user " 7187 + pkgSetting.sharedUser.name + "; ignoring!"); 7188 } 7189 } 7190 } 7191 7192 /** 7193 * Enforces that only the system UID or root's UID can call a method exposed 7194 * via Binder. 7195 * 7196 * @param message used as message if SecurityException is thrown 7197 * @throws SecurityException if the caller is not system or root 7198 */ 7199 private static final void enforceSystemOrRoot(String message) { 7200 final int uid = Binder.getCallingUid(); 7201 if (uid != Process.SYSTEM_UID && uid != 0) { 7202 throw new SecurityException(message); 7203 } 7204 } 7205 7206 @Override 7207 public void performFstrimIfNeeded() { 7208 enforceSystemOrRoot("Only the system can request fstrim"); 7209 7210 // Before everything else, see whether we need to fstrim. 7211 try { 7212 IMountService ms = PackageHelper.getMountService(); 7213 if (ms != null) { 7214 boolean doTrim = false; 7215 final long interval = android.provider.Settings.Global.getLong( 7216 mContext.getContentResolver(), 7217 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7218 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7219 if (interval > 0) { 7220 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7221 if (timeSinceLast > interval) { 7222 doTrim = true; 7223 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7224 + "; running immediately"); 7225 } 7226 } 7227 if (doTrim) { 7228 final boolean dexOptDialogShown; 7229 synchronized (mPackages) { 7230 dexOptDialogShown = mDexOptDialogShown; 7231 } 7232 if (!isFirstBoot() && dexOptDialogShown) { 7233 try { 7234 ActivityManagerNative.getDefault().showBootMessage( 7235 mContext.getResources().getString( 7236 R.string.android_upgrading_fstrim), true); 7237 } catch (RemoteException e) { 7238 } 7239 } 7240 ms.runMaintenance(); 7241 } 7242 } else { 7243 Slog.e(TAG, "Mount service unavailable!"); 7244 } 7245 } catch (RemoteException e) { 7246 // Can't happen; MountService is local 7247 } 7248 } 7249 7250 @Override 7251 public void updatePackagesIfNeeded() { 7252 enforceSystemOrRoot("Only the system can request package update"); 7253 7254 // We need to re-extract after an OTA. 7255 boolean causeUpgrade = isUpgrade(); 7256 7257 // First boot or factory reset. 7258 // Note: we also handle devices that are upgrading to N right now as if it is their 7259 // first boot, as they do not have profile data. 7260 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7261 7262 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7263 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7264 7265 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7266 return; 7267 } 7268 7269 List<PackageParser.Package> pkgs; 7270 synchronized (mPackages) { 7271 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7272 } 7273 7274 final long startTime = System.nanoTime(); 7275 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7276 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7277 7278 final int elapsedTimeSeconds = 7279 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7280 7281 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7282 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7283 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7284 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7285 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7286 } 7287 7288 /** 7289 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7290 * containing statistics about the invocation. The array consists of three elements, 7291 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7292 * and {@code numberOfPackagesFailed}. 7293 */ 7294 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7295 String compilerFilter) { 7296 7297 int numberOfPackagesVisited = 0; 7298 int numberOfPackagesOptimized = 0; 7299 int numberOfPackagesSkipped = 0; 7300 int numberOfPackagesFailed = 0; 7301 final int numberOfPackagesToDexopt = pkgs.size(); 7302 7303 for (PackageParser.Package pkg : pkgs) { 7304 numberOfPackagesVisited++; 7305 7306 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7307 if (DEBUG_DEXOPT) { 7308 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7309 } 7310 numberOfPackagesSkipped++; 7311 continue; 7312 } 7313 7314 if (DEBUG_DEXOPT) { 7315 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7316 numberOfPackagesToDexopt + ": " + pkg.packageName); 7317 } 7318 7319 if (showDialog) { 7320 try { 7321 ActivityManagerNative.getDefault().showBootMessage( 7322 mContext.getResources().getString(R.string.android_upgrading_apk, 7323 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7324 } catch (RemoteException e) { 7325 } 7326 synchronized (mPackages) { 7327 mDexOptDialogShown = true; 7328 } 7329 } 7330 7331 // If the OTA updates a system app which was previously preopted to a non-preopted state 7332 // the app might end up being verified at runtime. That's because by default the apps 7333 // are verify-profile but for preopted apps there's no profile. 7334 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7335 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7336 // filter (by default interpret-only). 7337 // Note that at this stage unused apps are already filtered. 7338 if (isSystemApp(pkg) && 7339 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7340 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7341 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7342 } 7343 7344 // If the OTA updates a system app which was previously preopted to a non-preopted state 7345 // the app might end up being verified at runtime. That's because by default the apps 7346 // are verify-profile but for preopted apps there's no profile. 7347 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7348 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7349 // filter (by default interpret-only). 7350 // Note that at this stage unused apps are already filtered. 7351 if (isSystemApp(pkg) && 7352 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7353 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7354 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7355 } 7356 7357 // checkProfiles is false to avoid merging profiles during boot which 7358 // might interfere with background compilation (b/28612421). 7359 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7360 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7361 // trade-off worth doing to save boot time work. 7362 int dexOptStatus = performDexOptTraced(pkg.packageName, 7363 false /* checkProfiles */, 7364 compilerFilter, 7365 false /* force */); 7366 switch (dexOptStatus) { 7367 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7368 numberOfPackagesOptimized++; 7369 break; 7370 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7371 numberOfPackagesSkipped++; 7372 break; 7373 case PackageDexOptimizer.DEX_OPT_FAILED: 7374 numberOfPackagesFailed++; 7375 break; 7376 default: 7377 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7378 break; 7379 } 7380 } 7381 7382 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7383 numberOfPackagesFailed }; 7384 } 7385 7386 @Override 7387 public void notifyPackageUse(String packageName, int reason) { 7388 synchronized (mPackages) { 7389 PackageParser.Package p = mPackages.get(packageName); 7390 if (p == null) { 7391 return; 7392 } 7393 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7394 } 7395 } 7396 7397 // TODO: this is not used nor needed. Delete it. 7398 @Override 7399 public boolean performDexOptIfNeeded(String packageName) { 7400 int dexOptStatus = performDexOptTraced(packageName, 7401 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7402 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7403 } 7404 7405 @Override 7406 public boolean performDexOpt(String packageName, 7407 boolean checkProfiles, int compileReason, boolean force) { 7408 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7409 getCompilerFilterForReason(compileReason), force); 7410 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7411 } 7412 7413 @Override 7414 public boolean performDexOptMode(String packageName, 7415 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7416 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7417 targetCompilerFilter, force); 7418 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7419 } 7420 7421 private int performDexOptTraced(String packageName, 7422 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7423 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7424 try { 7425 return performDexOptInternal(packageName, checkProfiles, 7426 targetCompilerFilter, force); 7427 } finally { 7428 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7429 } 7430 } 7431 7432 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7433 // if the package can now be considered up to date for the given filter. 7434 private int performDexOptInternal(String packageName, 7435 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7436 PackageParser.Package p; 7437 synchronized (mPackages) { 7438 p = mPackages.get(packageName); 7439 if (p == null) { 7440 // Package could not be found. Report failure. 7441 return PackageDexOptimizer.DEX_OPT_FAILED; 7442 } 7443 mPackageUsage.maybeWriteAsync(mPackages); 7444 mCompilerStats.maybeWriteAsync(); 7445 } 7446 long callingId = Binder.clearCallingIdentity(); 7447 try { 7448 synchronized (mInstallLock) { 7449 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7450 targetCompilerFilter, force); 7451 } 7452 } finally { 7453 Binder.restoreCallingIdentity(callingId); 7454 } 7455 } 7456 7457 public ArraySet<String> getOptimizablePackages() { 7458 ArraySet<String> pkgs = new ArraySet<String>(); 7459 synchronized (mPackages) { 7460 for (PackageParser.Package p : mPackages.values()) { 7461 if (PackageDexOptimizer.canOptimizePackage(p)) { 7462 pkgs.add(p.packageName); 7463 } 7464 } 7465 } 7466 return pkgs; 7467 } 7468 7469 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7470 boolean checkProfiles, String targetCompilerFilter, 7471 boolean force) { 7472 // Select the dex optimizer based on the force parameter. 7473 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7474 // allocate an object here. 7475 PackageDexOptimizer pdo = force 7476 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7477 : mPackageDexOptimizer; 7478 7479 // Optimize all dependencies first. Note: we ignore the return value and march on 7480 // on errors. 7481 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7482 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7483 if (!deps.isEmpty()) { 7484 for (PackageParser.Package depPackage : deps) { 7485 // TODO: Analyze and investigate if we (should) profile libraries. 7486 // Currently this will do a full compilation of the library by default. 7487 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7488 false /* checkProfiles */, 7489 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7490 getOrCreateCompilerPackageStats(depPackage)); 7491 } 7492 } 7493 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7494 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7495 } 7496 7497 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7498 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7499 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7500 Set<String> collectedNames = new HashSet<>(); 7501 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7502 7503 retValue.remove(p); 7504 7505 return retValue; 7506 } else { 7507 return Collections.emptyList(); 7508 } 7509 } 7510 7511 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7512 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7513 if (!collectedNames.contains(p.packageName)) { 7514 collectedNames.add(p.packageName); 7515 collected.add(p); 7516 7517 if (p.usesLibraries != null) { 7518 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7519 } 7520 if (p.usesOptionalLibraries != null) { 7521 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7522 collectedNames); 7523 } 7524 } 7525 } 7526 7527 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7528 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7529 for (String libName : libs) { 7530 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7531 if (libPkg != null) { 7532 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7533 } 7534 } 7535 } 7536 7537 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7538 synchronized (mPackages) { 7539 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7540 if (lib != null && lib.apk != null) { 7541 return mPackages.get(lib.apk); 7542 } 7543 } 7544 return null; 7545 } 7546 7547 public void shutdown() { 7548 mPackageUsage.writeNow(mPackages); 7549 mCompilerStats.writeNow(); 7550 } 7551 7552 @Override 7553 public void dumpProfiles(String packageName) { 7554 PackageParser.Package pkg; 7555 synchronized (mPackages) { 7556 pkg = mPackages.get(packageName); 7557 if (pkg == null) { 7558 throw new IllegalArgumentException("Unknown package: " + packageName); 7559 } 7560 } 7561 /* Only the shell, root, or the app user should be able to dump profiles. */ 7562 int callingUid = Binder.getCallingUid(); 7563 if (callingUid != Process.SHELL_UID && 7564 callingUid != Process.ROOT_UID && 7565 callingUid != pkg.applicationInfo.uid) { 7566 throw new SecurityException("dumpProfiles"); 7567 } 7568 7569 synchronized (mInstallLock) { 7570 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7571 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7572 try { 7573 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7574 String gid = Integer.toString(sharedGid); 7575 String codePaths = TextUtils.join(";", allCodePaths); 7576 mInstaller.dumpProfiles(gid, packageName, codePaths); 7577 } catch (InstallerException e) { 7578 Slog.w(TAG, "Failed to dump profiles", e); 7579 } 7580 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7581 } 7582 } 7583 7584 @Override 7585 public void forceDexOpt(String packageName) { 7586 enforceSystemOrRoot("forceDexOpt"); 7587 7588 PackageParser.Package pkg; 7589 synchronized (mPackages) { 7590 pkg = mPackages.get(packageName); 7591 if (pkg == null) { 7592 throw new IllegalArgumentException("Unknown package: " + packageName); 7593 } 7594 } 7595 7596 synchronized (mInstallLock) { 7597 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7598 7599 // Whoever is calling forceDexOpt wants a fully compiled package. 7600 // Don't use profiles since that may cause compilation to be skipped. 7601 final int res = performDexOptInternalWithDependenciesLI(pkg, 7602 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7603 true /* force */); 7604 7605 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7606 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7607 throw new IllegalStateException("Failed to dexopt: " + res); 7608 } 7609 } 7610 } 7611 7612 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7613 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7614 Slog.w(TAG, "Unable to update from " + oldPkg.name 7615 + " to " + newPkg.packageName 7616 + ": old package not in system partition"); 7617 return false; 7618 } else if (mPackages.get(oldPkg.name) != null) { 7619 Slog.w(TAG, "Unable to update from " + oldPkg.name 7620 + " to " + newPkg.packageName 7621 + ": old package still exists"); 7622 return false; 7623 } 7624 return true; 7625 } 7626 7627 void removeCodePathLI(File codePath) { 7628 if (codePath.isDirectory()) { 7629 try { 7630 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7631 } catch (InstallerException e) { 7632 Slog.w(TAG, "Failed to remove code path", e); 7633 } 7634 } else { 7635 codePath.delete(); 7636 } 7637 } 7638 7639 private int[] resolveUserIds(int userId) { 7640 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7641 } 7642 7643 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7644 if (pkg == null) { 7645 Slog.wtf(TAG, "Package was null!", new Throwable()); 7646 return; 7647 } 7648 clearAppDataLeafLIF(pkg, userId, flags); 7649 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7650 for (int i = 0; i < childCount; i++) { 7651 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7652 } 7653 } 7654 7655 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7656 final PackageSetting ps; 7657 synchronized (mPackages) { 7658 ps = mSettings.mPackages.get(pkg.packageName); 7659 } 7660 for (int realUserId : resolveUserIds(userId)) { 7661 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7662 try { 7663 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7664 ceDataInode); 7665 } catch (InstallerException e) { 7666 Slog.w(TAG, String.valueOf(e)); 7667 } 7668 } 7669 } 7670 7671 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7672 if (pkg == null) { 7673 Slog.wtf(TAG, "Package was null!", new Throwable()); 7674 return; 7675 } 7676 destroyAppDataLeafLIF(pkg, userId, flags); 7677 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7678 for (int i = 0; i < childCount; i++) { 7679 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7680 } 7681 } 7682 7683 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7684 final PackageSetting ps; 7685 synchronized (mPackages) { 7686 ps = mSettings.mPackages.get(pkg.packageName); 7687 } 7688 for (int realUserId : resolveUserIds(userId)) { 7689 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7690 try { 7691 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7692 ceDataInode); 7693 } catch (InstallerException e) { 7694 Slog.w(TAG, String.valueOf(e)); 7695 } 7696 } 7697 } 7698 7699 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7700 if (pkg == null) { 7701 Slog.wtf(TAG, "Package was null!", new Throwable()); 7702 return; 7703 } 7704 destroyAppProfilesLeafLIF(pkg); 7705 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7706 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7707 for (int i = 0; i < childCount; i++) { 7708 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7709 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7710 true /* removeBaseMarker */); 7711 } 7712 } 7713 7714 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7715 boolean removeBaseMarker) { 7716 if (pkg.isForwardLocked()) { 7717 return; 7718 } 7719 7720 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7721 try { 7722 path = PackageManagerServiceUtils.realpath(new File(path)); 7723 } catch (IOException e) { 7724 // TODO: Should we return early here ? 7725 Slog.w(TAG, "Failed to get canonical path", e); 7726 continue; 7727 } 7728 7729 final String useMarker = path.replace('/', '@'); 7730 for (int realUserId : resolveUserIds(userId)) { 7731 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7732 if (removeBaseMarker) { 7733 File foreignUseMark = new File(profileDir, useMarker); 7734 if (foreignUseMark.exists()) { 7735 if (!foreignUseMark.delete()) { 7736 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7737 + pkg.packageName); 7738 } 7739 } 7740 } 7741 7742 File[] markers = profileDir.listFiles(); 7743 if (markers != null) { 7744 final String searchString = "@" + pkg.packageName + "@"; 7745 // We also delete all markers that contain the package name we're 7746 // uninstalling. These are associated with secondary dex-files belonging 7747 // to the package. Reconstructing the path of these dex files is messy 7748 // in general. 7749 for (File marker : markers) { 7750 if (marker.getName().indexOf(searchString) > 0) { 7751 if (!marker.delete()) { 7752 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7753 + pkg.packageName); 7754 } 7755 } 7756 } 7757 } 7758 } 7759 } 7760 } 7761 7762 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7763 try { 7764 mInstaller.destroyAppProfiles(pkg.packageName); 7765 } catch (InstallerException e) { 7766 Slog.w(TAG, String.valueOf(e)); 7767 } 7768 } 7769 7770 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7771 if (pkg == null) { 7772 Slog.wtf(TAG, "Package was null!", new Throwable()); 7773 return; 7774 } 7775 clearAppProfilesLeafLIF(pkg); 7776 // We don't remove the base foreign use marker when clearing profiles because 7777 // we will rename it when the app is updated. Unlike the actual profile contents, 7778 // the foreign use marker is good across installs. 7779 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7780 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7781 for (int i = 0; i < childCount; i++) { 7782 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7783 } 7784 } 7785 7786 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7787 try { 7788 mInstaller.clearAppProfiles(pkg.packageName); 7789 } catch (InstallerException e) { 7790 Slog.w(TAG, String.valueOf(e)); 7791 } 7792 } 7793 7794 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7795 long lastUpdateTime) { 7796 // Set parent install/update time 7797 PackageSetting ps = (PackageSetting) pkg.mExtras; 7798 if (ps != null) { 7799 ps.firstInstallTime = firstInstallTime; 7800 ps.lastUpdateTime = lastUpdateTime; 7801 } 7802 // Set children install/update time 7803 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7804 for (int i = 0; i < childCount; i++) { 7805 PackageParser.Package childPkg = pkg.childPackages.get(i); 7806 ps = (PackageSetting) childPkg.mExtras; 7807 if (ps != null) { 7808 ps.firstInstallTime = firstInstallTime; 7809 ps.lastUpdateTime = lastUpdateTime; 7810 } 7811 } 7812 } 7813 7814 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7815 PackageParser.Package changingLib) { 7816 if (file.path != null) { 7817 usesLibraryFiles.add(file.path); 7818 return; 7819 } 7820 PackageParser.Package p = mPackages.get(file.apk); 7821 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7822 // If we are doing this while in the middle of updating a library apk, 7823 // then we need to make sure to use that new apk for determining the 7824 // dependencies here. (We haven't yet finished committing the new apk 7825 // to the package manager state.) 7826 if (p == null || p.packageName.equals(changingLib.packageName)) { 7827 p = changingLib; 7828 } 7829 } 7830 if (p != null) { 7831 usesLibraryFiles.addAll(p.getAllCodePaths()); 7832 } 7833 } 7834 7835 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7836 PackageParser.Package changingLib) throws PackageManagerException { 7837 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7838 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7839 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7840 for (int i=0; i<N; i++) { 7841 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7842 if (file == null) { 7843 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7844 "Package " + pkg.packageName + " requires unavailable shared library " 7845 + pkg.usesLibraries.get(i) + "; failing!"); 7846 } 7847 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7848 } 7849 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7850 for (int i=0; i<N; i++) { 7851 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7852 if (file == null) { 7853 Slog.w(TAG, "Package " + pkg.packageName 7854 + " desires unavailable shared library " 7855 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7856 } else { 7857 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7858 } 7859 } 7860 N = usesLibraryFiles.size(); 7861 if (N > 0) { 7862 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7863 } else { 7864 pkg.usesLibraryFiles = null; 7865 } 7866 } 7867 } 7868 7869 private static boolean hasString(List<String> list, List<String> which) { 7870 if (list == null) { 7871 return false; 7872 } 7873 for (int i=list.size()-1; i>=0; i--) { 7874 for (int j=which.size()-1; j>=0; j--) { 7875 if (which.get(j).equals(list.get(i))) { 7876 return true; 7877 } 7878 } 7879 } 7880 return false; 7881 } 7882 7883 private void updateAllSharedLibrariesLPw() { 7884 for (PackageParser.Package pkg : mPackages.values()) { 7885 try { 7886 updateSharedLibrariesLPw(pkg, null); 7887 } catch (PackageManagerException e) { 7888 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7889 } 7890 } 7891 } 7892 7893 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7894 PackageParser.Package changingPkg) { 7895 ArrayList<PackageParser.Package> res = null; 7896 for (PackageParser.Package pkg : mPackages.values()) { 7897 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7898 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7899 if (res == null) { 7900 res = new ArrayList<PackageParser.Package>(); 7901 } 7902 res.add(pkg); 7903 try { 7904 updateSharedLibrariesLPw(pkg, changingPkg); 7905 } catch (PackageManagerException e) { 7906 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7907 } 7908 } 7909 } 7910 return res; 7911 } 7912 7913 /** 7914 * Derive the value of the {@code cpuAbiOverride} based on the provided 7915 * value and an optional stored value from the package settings. 7916 */ 7917 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7918 String cpuAbiOverride = null; 7919 7920 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7921 cpuAbiOverride = null; 7922 } else if (abiOverride != null) { 7923 cpuAbiOverride = abiOverride; 7924 } else if (settings != null) { 7925 cpuAbiOverride = settings.cpuAbiOverrideString; 7926 } 7927 7928 return cpuAbiOverride; 7929 } 7930 7931 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7932 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7933 throws PackageManagerException { 7934 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7935 // If the package has children and this is the first dive in the function 7936 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7937 // whether all packages (parent and children) would be successfully scanned 7938 // before the actual scan since scanning mutates internal state and we want 7939 // to atomically install the package and its children. 7940 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7941 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7942 scanFlags |= SCAN_CHECK_ONLY; 7943 } 7944 } else { 7945 scanFlags &= ~SCAN_CHECK_ONLY; 7946 } 7947 7948 final PackageParser.Package scannedPkg; 7949 try { 7950 // Scan the parent 7951 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7952 // Scan the children 7953 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7954 for (int i = 0; i < childCount; i++) { 7955 PackageParser.Package childPkg = pkg.childPackages.get(i); 7956 scanPackageLI(childPkg, policyFlags, 7957 scanFlags, currentTime, user); 7958 } 7959 } finally { 7960 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7961 } 7962 7963 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7964 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7965 } 7966 7967 return scannedPkg; 7968 } 7969 7970 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7971 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7972 boolean success = false; 7973 try { 7974 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7975 currentTime, user); 7976 success = true; 7977 return res; 7978 } finally { 7979 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7980 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7981 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7982 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7983 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7984 } 7985 } 7986 } 7987 7988 /** 7989 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7990 */ 7991 private static boolean apkHasCode(String fileName) { 7992 StrictJarFile jarFile = null; 7993 try { 7994 jarFile = new StrictJarFile(fileName, 7995 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7996 return jarFile.findEntry("classes.dex") != null; 7997 } catch (IOException ignore) { 7998 } finally { 7999 try { 8000 if (jarFile != null) { 8001 jarFile.close(); 8002 } 8003 } catch (IOException ignore) {} 8004 } 8005 return false; 8006 } 8007 8008 /** 8009 * Enforces code policy for the package. This ensures that if an APK has 8010 * declared hasCode="true" in its manifest that the APK actually contains 8011 * code. 8012 * 8013 * @throws PackageManagerException If bytecode could not be found when it should exist 8014 */ 8015 private static void enforceCodePolicy(PackageParser.Package pkg) 8016 throws PackageManagerException { 8017 final boolean shouldHaveCode = 8018 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8019 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8020 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8021 "Package " + pkg.baseCodePath + " code is missing"); 8022 } 8023 8024 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8025 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8026 final boolean splitShouldHaveCode = 8027 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8028 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8029 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8030 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8031 } 8032 } 8033 } 8034 } 8035 8036 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8037 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8038 throws PackageManagerException { 8039 final File scanFile = new File(pkg.codePath); 8040 if (pkg.applicationInfo.getCodePath() == null || 8041 pkg.applicationInfo.getResourcePath() == null) { 8042 // Bail out. The resource and code paths haven't been set. 8043 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8044 "Code and resource paths haven't been set correctly"); 8045 } 8046 8047 // Apply policy 8048 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8049 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8050 if (pkg.applicationInfo.isDirectBootAware()) { 8051 // we're direct boot aware; set for all components 8052 for (PackageParser.Service s : pkg.services) { 8053 s.info.encryptionAware = s.info.directBootAware = true; 8054 } 8055 for (PackageParser.Provider p : pkg.providers) { 8056 p.info.encryptionAware = p.info.directBootAware = true; 8057 } 8058 for (PackageParser.Activity a : pkg.activities) { 8059 a.info.encryptionAware = a.info.directBootAware = true; 8060 } 8061 for (PackageParser.Activity r : pkg.receivers) { 8062 r.info.encryptionAware = r.info.directBootAware = true; 8063 } 8064 } 8065 } else { 8066 // Only allow system apps to be flagged as core apps. 8067 pkg.coreApp = false; 8068 // clear flags not applicable to regular apps 8069 pkg.applicationInfo.privateFlags &= 8070 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8071 pkg.applicationInfo.privateFlags &= 8072 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8073 } 8074 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8075 8076 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8077 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8078 } 8079 8080 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8081 enforceCodePolicy(pkg); 8082 } 8083 8084 if (mCustomResolverComponentName != null && 8085 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8086 setUpCustomResolverActivity(pkg); 8087 } 8088 8089 if (pkg.packageName.equals("android")) { 8090 synchronized (mPackages) { 8091 if (mAndroidApplication != null) { 8092 Slog.w(TAG, "*************************************************"); 8093 Slog.w(TAG, "Core android package being redefined. Skipping."); 8094 Slog.w(TAG, " file=" + scanFile); 8095 Slog.w(TAG, "*************************************************"); 8096 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8097 "Core android package being redefined. Skipping."); 8098 } 8099 8100 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8101 // Set up information for our fall-back user intent resolution activity. 8102 mPlatformPackage = pkg; 8103 pkg.mVersionCode = mSdkVersion; 8104 mAndroidApplication = pkg.applicationInfo; 8105 8106 if (!mResolverReplaced) { 8107 mResolveActivity.applicationInfo = mAndroidApplication; 8108 mResolveActivity.name = ResolverActivity.class.getName(); 8109 mResolveActivity.packageName = mAndroidApplication.packageName; 8110 mResolveActivity.processName = "system:ui"; 8111 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8112 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8113 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8114 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8115 mResolveActivity.exported = true; 8116 mResolveActivity.enabled = true; 8117 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8118 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8119 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8120 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8121 | ActivityInfo.CONFIG_ORIENTATION 8122 | ActivityInfo.CONFIG_KEYBOARD 8123 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8124 mResolveInfo.activityInfo = mResolveActivity; 8125 mResolveInfo.priority = 0; 8126 mResolveInfo.preferredOrder = 0; 8127 mResolveInfo.match = 0; 8128 mResolveComponentName = new ComponentName( 8129 mAndroidApplication.packageName, mResolveActivity.name); 8130 } 8131 } 8132 } 8133 } 8134 8135 if (DEBUG_PACKAGE_SCANNING) { 8136 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8137 Log.d(TAG, "Scanning package " + pkg.packageName); 8138 } 8139 8140 synchronized (mPackages) { 8141 if (mPackages.containsKey(pkg.packageName) 8142 || mSharedLibraries.containsKey(pkg.packageName)) { 8143 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8144 "Application package " + pkg.packageName 8145 + " already installed. Skipping duplicate."); 8146 } 8147 8148 // If we're only installing presumed-existing packages, require that the 8149 // scanned APK is both already known and at the path previously established 8150 // for it. Previously unknown packages we pick up normally, but if we have an 8151 // a priori expectation about this package's install presence, enforce it. 8152 // With a singular exception for new system packages. When an OTA contains 8153 // a new system package, we allow the codepath to change from a system location 8154 // to the user-installed location. If we don't allow this change, any newer, 8155 // user-installed version of the application will be ignored. 8156 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8157 if (mExpectingBetter.containsKey(pkg.packageName)) { 8158 logCriticalInfo(Log.WARN, 8159 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8160 } else { 8161 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8162 if (known != null) { 8163 if (DEBUG_PACKAGE_SCANNING) { 8164 Log.d(TAG, "Examining " + pkg.codePath 8165 + " and requiring known paths " + known.codePathString 8166 + " & " + known.resourcePathString); 8167 } 8168 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8169 || !pkg.applicationInfo.getResourcePath().equals( 8170 known.resourcePathString)) { 8171 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8172 "Application package " + pkg.packageName 8173 + " found at " + pkg.applicationInfo.getCodePath() 8174 + " but expected at " + known.codePathString 8175 + "; ignoring."); 8176 } 8177 } 8178 } 8179 } 8180 } 8181 8182 // Initialize package source and resource directories 8183 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8184 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8185 8186 SharedUserSetting suid = null; 8187 PackageSetting pkgSetting = null; 8188 8189 if (!isSystemApp(pkg)) { 8190 // Only system apps can use these features. 8191 pkg.mOriginalPackages = null; 8192 pkg.mRealPackage = null; 8193 pkg.mAdoptPermissions = null; 8194 } 8195 8196 // Getting the package setting may have a side-effect, so if we 8197 // are only checking if scan would succeed, stash a copy of the 8198 // old setting to restore at the end. 8199 PackageSetting nonMutatedPs = null; 8200 8201 // writer 8202 synchronized (mPackages) { 8203 if (pkg.mSharedUserId != null) { 8204 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8205 if (suid == null) { 8206 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8207 "Creating application package " + pkg.packageName 8208 + " for shared user failed"); 8209 } 8210 if (DEBUG_PACKAGE_SCANNING) { 8211 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8212 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8213 + "): packages=" + suid.packages); 8214 } 8215 } 8216 8217 // Check if we are renaming from an original package name. 8218 PackageSetting origPackage = null; 8219 String realName = null; 8220 if (pkg.mOriginalPackages != null) { 8221 // This package may need to be renamed to a previously 8222 // installed name. Let's check on that... 8223 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8224 if (pkg.mOriginalPackages.contains(renamed)) { 8225 // This package had originally been installed as the 8226 // original name, and we have already taken care of 8227 // transitioning to the new one. Just update the new 8228 // one to continue using the old name. 8229 realName = pkg.mRealPackage; 8230 if (!pkg.packageName.equals(renamed)) { 8231 // Callers into this function may have already taken 8232 // care of renaming the package; only do it here if 8233 // it is not already done. 8234 pkg.setPackageName(renamed); 8235 } 8236 8237 } else { 8238 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8239 if ((origPackage = mSettings.peekPackageLPr( 8240 pkg.mOriginalPackages.get(i))) != null) { 8241 // We do have the package already installed under its 8242 // original name... should we use it? 8243 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8244 // New package is not compatible with original. 8245 origPackage = null; 8246 continue; 8247 } else if (origPackage.sharedUser != null) { 8248 // Make sure uid is compatible between packages. 8249 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8250 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8251 + " to " + pkg.packageName + ": old uid " 8252 + origPackage.sharedUser.name 8253 + " differs from " + pkg.mSharedUserId); 8254 origPackage = null; 8255 continue; 8256 } 8257 // TODO: Add case when shared user id is added [b/28144775] 8258 } else { 8259 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8260 + pkg.packageName + " to old name " + origPackage.name); 8261 } 8262 break; 8263 } 8264 } 8265 } 8266 } 8267 8268 if (mTransferedPackages.contains(pkg.packageName)) { 8269 Slog.w(TAG, "Package " + pkg.packageName 8270 + " was transferred to another, but its .apk remains"); 8271 } 8272 8273 // See comments in nonMutatedPs declaration 8274 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8275 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8276 if (foundPs != null) { 8277 nonMutatedPs = new PackageSetting(foundPs); 8278 } 8279 } 8280 8281 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8282 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 8283 PackageManagerService.reportSettingsProblem(Log.WARN, 8284 "Package " + pkg.packageName + " shared user changed from " 8285 + (pkgSetting.sharedUser != null ? pkgSetting.sharedUser.name : "<nothing>") 8286 + " to " 8287 + (suid != null ? suid.name : "<nothing>") 8288 + "; replacing with new"); 8289 pkgSetting = null; 8290 } 8291 final PackageSetting oldPkgSetting = 8292 pkgSetting == null ? null : new PackageSetting(pkgSetting); 8293 final PackageSetting disabledPkgSetting = 8294 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8295 if (pkgSetting == null) { 8296 final String parentPackageName = (pkg.parentPackage != null) 8297 ? pkg.parentPackage.packageName : null; 8298 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 8299 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 8300 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 8301 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 8302 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 8303 true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(), 8304 UserManagerService.getInstance()); 8305 if (origPackage != null) { 8306 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 8307 } 8308 mSettings.addUserToSettingLPw(pkgSetting); 8309 } else { 8310 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 8311 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 8312 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 8313 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 8314 UserManagerService.getInstance()); 8315 } 8316 mSettings.writeUserRestrictions(pkgSetting, oldPkgSetting); 8317 8318 if (pkgSetting.origPackage != null) { 8319 // If we are first transitioning from an original package, 8320 // fix up the new package's name now. We need to do this after 8321 // looking up the package under its new name, so getPackageLP 8322 // can take care of fiddling things correctly. 8323 pkg.setPackageName(origPackage.name); 8324 8325 // File a report about this. 8326 String msg = "New package " + pkgSetting.realName 8327 + " renamed to replace old package " + pkgSetting.name; 8328 reportSettingsProblem(Log.WARN, msg); 8329 8330 // Make a note of it. 8331 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8332 mTransferedPackages.add(origPackage.name); 8333 } 8334 8335 // No longer need to retain this. 8336 pkgSetting.origPackage = null; 8337 } 8338 8339 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8340 // Make a note of it. 8341 mTransferedPackages.add(pkg.packageName); 8342 } 8343 8344 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8345 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8346 } 8347 8348 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8349 // Check all shared libraries and map to their actual file path. 8350 // We only do this here for apps not on a system dir, because those 8351 // are the only ones that can fail an install due to this. We 8352 // will take care of the system apps by updating all of their 8353 // library paths after the scan is done. 8354 updateSharedLibrariesLPw(pkg, null); 8355 } 8356 8357 if (mFoundPolicyFile) { 8358 SELinuxMMAC.assignSeinfoValue(pkg); 8359 } 8360 8361 pkg.applicationInfo.uid = pkgSetting.appId; 8362 pkg.mExtras = pkgSetting; 8363 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8364 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8365 // We just determined the app is signed correctly, so bring 8366 // over the latest parsed certs. 8367 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8368 } else { 8369 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8370 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8371 "Package " + pkg.packageName + " upgrade keys do not match the " 8372 + "previously installed version"); 8373 } else { 8374 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8375 String msg = "System package " + pkg.packageName 8376 + " signature changed; retaining data."; 8377 reportSettingsProblem(Log.WARN, msg); 8378 } 8379 } 8380 } else { 8381 try { 8382 verifySignaturesLP(pkgSetting, pkg); 8383 // We just determined the app is signed correctly, so bring 8384 // over the latest parsed certs. 8385 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8386 } catch (PackageManagerException e) { 8387 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8388 throw e; 8389 } 8390 // The signature has changed, but this package is in the system 8391 // image... let's recover! 8392 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8393 // However... if this package is part of a shared user, but it 8394 // doesn't match the signature of the shared user, let's fail. 8395 // What this means is that you can't change the signatures 8396 // associated with an overall shared user, which doesn't seem all 8397 // that unreasonable. 8398 if (pkgSetting.sharedUser != null) { 8399 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8400 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8401 throw new PackageManagerException( 8402 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8403 "Signature mismatch for shared user: " 8404 + pkgSetting.sharedUser); 8405 } 8406 } 8407 // File a report about this. 8408 String msg = "System package " + pkg.packageName 8409 + " signature changed; retaining data."; 8410 reportSettingsProblem(Log.WARN, msg); 8411 } 8412 } 8413 // Verify that this new package doesn't have any content providers 8414 // that conflict with existing packages. Only do this if the 8415 // package isn't already installed, since we don't want to break 8416 // things that are installed. 8417 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8418 final int N = pkg.providers.size(); 8419 int i; 8420 for (i=0; i<N; i++) { 8421 PackageParser.Provider p = pkg.providers.get(i); 8422 if (p.info.authority != null) { 8423 String names[] = p.info.authority.split(";"); 8424 for (int j = 0; j < names.length; j++) { 8425 if (mProvidersByAuthority.containsKey(names[j])) { 8426 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8427 final String otherPackageName = 8428 ((other != null && other.getComponentName() != null) ? 8429 other.getComponentName().getPackageName() : "?"); 8430 throw new PackageManagerException( 8431 INSTALL_FAILED_CONFLICTING_PROVIDER, 8432 "Can't install because provider name " + names[j] 8433 + " (in package " + pkg.applicationInfo.packageName 8434 + ") is already used by " + otherPackageName); 8435 } 8436 } 8437 } 8438 } 8439 } 8440 8441 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8442 // This package wants to adopt ownership of permissions from 8443 // another package. 8444 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8445 final String origName = pkg.mAdoptPermissions.get(i); 8446 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8447 if (orig != null) { 8448 if (verifyPackageUpdateLPr(orig, pkg)) { 8449 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8450 + pkg.packageName); 8451 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8452 } 8453 } 8454 } 8455 } 8456 } 8457 8458 final String pkgName = pkg.packageName; 8459 8460 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8461 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8462 pkg.applicationInfo.processName = fixProcessName( 8463 pkg.applicationInfo.packageName, 8464 pkg.applicationInfo.processName, 8465 pkg.applicationInfo.uid); 8466 8467 if (pkg != mPlatformPackage) { 8468 // Get all of our default paths setup 8469 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8470 } 8471 8472 final String path = scanFile.getPath(); 8473 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8474 8475 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8476 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 8477 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /*extractLibs*/); 8478 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8479 8480 // Some system apps still use directory structure for native libraries 8481 // in which case we might end up not detecting abi solely based on apk 8482 // structure. Try to detect abi based on directory structure. 8483 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8484 pkg.applicationInfo.primaryCpuAbi == null) { 8485 setBundledAppAbisAndRoots(pkg, pkgSetting); 8486 setNativeLibraryPaths(pkg); 8487 } 8488 8489 } else { 8490 if ((scanFlags & SCAN_MOVE) != 0) { 8491 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8492 // but we already have this packages package info in the PackageSetting. We just 8493 // use that and derive the native library path based on the new codepath. 8494 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8495 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8496 } 8497 8498 // Set native library paths again. For moves, the path will be updated based on the 8499 // ABIs we've determined above. For non-moves, the path will be updated based on the 8500 // ABIs we determined during compilation, but the path will depend on the final 8501 // package path (after the rename away from the stage path). 8502 setNativeLibraryPaths(pkg); 8503 } 8504 8505 // This is a special case for the "system" package, where the ABI is 8506 // dictated by the zygote configuration (and init.rc). We should keep track 8507 // of this ABI so that we can deal with "normal" applications that run under 8508 // the same UID correctly. 8509 if (mPlatformPackage == pkg) { 8510 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8511 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8512 } 8513 8514 // If there's a mismatch between the abi-override in the package setting 8515 // and the abiOverride specified for the install. Warn about this because we 8516 // would've already compiled the app without taking the package setting into 8517 // account. 8518 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8519 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8520 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8521 " for package " + pkg.packageName); 8522 } 8523 } 8524 8525 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8526 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8527 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8528 8529 // Copy the derived override back to the parsed package, so that we can 8530 // update the package settings accordingly. 8531 pkg.cpuAbiOverride = cpuAbiOverride; 8532 8533 if (DEBUG_ABI_SELECTION) { 8534 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8535 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8536 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8537 } 8538 8539 // Push the derived path down into PackageSettings so we know what to 8540 // clean up at uninstall time. 8541 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8542 8543 if (DEBUG_ABI_SELECTION) { 8544 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8545 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8546 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8547 } 8548 8549 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8550 // We don't do this here during boot because we can do it all 8551 // at once after scanning all existing packages. 8552 // 8553 // We also do this *before* we perform dexopt on this package, so that 8554 // we can avoid redundant dexopts, and also to make sure we've got the 8555 // code and package path correct. 8556 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8557 pkg, true /* boot complete */); 8558 } 8559 8560 if (mFactoryTest && pkg.requestedPermissions.contains( 8561 android.Manifest.permission.FACTORY_TEST)) { 8562 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8563 } 8564 8565 if (isSystemApp(pkg)) { 8566 pkgSetting.isOrphaned = true; 8567 } 8568 8569 ArrayList<PackageParser.Package> clientLibPkgs = null; 8570 8571 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8572 if (nonMutatedPs != null) { 8573 synchronized (mPackages) { 8574 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8575 } 8576 } 8577 return pkg; 8578 } 8579 8580 // Only privileged apps and updated privileged apps can add child packages. 8581 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8582 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8583 throw new PackageManagerException("Only privileged apps and updated " 8584 + "privileged apps can add child packages. Ignoring package " 8585 + pkg.packageName); 8586 } 8587 final int childCount = pkg.childPackages.size(); 8588 for (int i = 0; i < childCount; i++) { 8589 PackageParser.Package childPkg = pkg.childPackages.get(i); 8590 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8591 childPkg.packageName)) { 8592 throw new PackageManagerException("Cannot override a child package of " 8593 + "another disabled system app. Ignoring package " + pkg.packageName); 8594 } 8595 } 8596 } 8597 8598 // writer 8599 synchronized (mPackages) { 8600 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8601 // Only system apps can add new shared libraries. 8602 if (pkg.libraryNames != null) { 8603 for (int i=0; i<pkg.libraryNames.size(); i++) { 8604 String name = pkg.libraryNames.get(i); 8605 boolean allowed = false; 8606 if (pkg.isUpdatedSystemApp()) { 8607 // New library entries can only be added through the 8608 // system image. This is important to get rid of a lot 8609 // of nasty edge cases: for example if we allowed a non- 8610 // system update of the app to add a library, then uninstalling 8611 // the update would make the library go away, and assumptions 8612 // we made such as through app install filtering would now 8613 // have allowed apps on the device which aren't compatible 8614 // with it. Better to just have the restriction here, be 8615 // conservative, and create many fewer cases that can negatively 8616 // impact the user experience. 8617 final PackageSetting sysPs = mSettings 8618 .getDisabledSystemPkgLPr(pkg.packageName); 8619 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8620 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8621 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8622 allowed = true; 8623 break; 8624 } 8625 } 8626 } 8627 } else { 8628 allowed = true; 8629 } 8630 if (allowed) { 8631 if (!mSharedLibraries.containsKey(name)) { 8632 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8633 } else if (!name.equals(pkg.packageName)) { 8634 Slog.w(TAG, "Package " + pkg.packageName + " library " 8635 + name + " already exists; skipping"); 8636 } 8637 } else { 8638 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8639 + name + " that is not declared on system image; skipping"); 8640 } 8641 } 8642 if ((scanFlags & SCAN_BOOTING) == 0) { 8643 // If we are not booting, we need to update any applications 8644 // that are clients of our shared library. If we are booting, 8645 // this will all be done once the scan is complete. 8646 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8647 } 8648 } 8649 } 8650 } 8651 8652 if ((scanFlags & SCAN_BOOTING) != 0) { 8653 // No apps can run during boot scan, so they don't need to be frozen 8654 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8655 // Caller asked to not kill app, so it's probably not frozen 8656 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8657 // Caller asked us to ignore frozen check for some reason; they 8658 // probably didn't know the package name 8659 } else { 8660 // We're doing major surgery on this package, so it better be frozen 8661 // right now to keep it from launching 8662 checkPackageFrozen(pkgName); 8663 } 8664 8665 // Also need to kill any apps that are dependent on the library. 8666 if (clientLibPkgs != null) { 8667 for (int i=0; i<clientLibPkgs.size(); i++) { 8668 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8669 killApplication(clientPkg.applicationInfo.packageName, 8670 clientPkg.applicationInfo.uid, "update lib"); 8671 } 8672 } 8673 8674 // Make sure we're not adding any bogus keyset info 8675 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8676 ksms.assertScannedPackageValid(pkg); 8677 8678 // writer 8679 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8680 8681 boolean createIdmapFailed = false; 8682 synchronized (mPackages) { 8683 // We don't expect installation to fail beyond this point 8684 8685 if (pkgSetting.pkg != null) { 8686 // Note that |user| might be null during the initial boot scan. If a codePath 8687 // for an app has changed during a boot scan, it's due to an app update that's 8688 // part of the system partition and marker changes must be applied to all users. 8689 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8690 (user != null) ? user : UserHandle.ALL); 8691 } 8692 8693 // Add the new setting to mSettings 8694 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8695 // Add the new setting to mPackages 8696 mPackages.put(pkg.applicationInfo.packageName, pkg); 8697 // Make sure we don't accidentally delete its data. 8698 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8699 while (iter.hasNext()) { 8700 PackageCleanItem item = iter.next(); 8701 if (pkgName.equals(item.packageName)) { 8702 iter.remove(); 8703 } 8704 } 8705 8706 // Take care of first install / last update times. 8707 if (currentTime != 0) { 8708 if (pkgSetting.firstInstallTime == 0) { 8709 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8710 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8711 pkgSetting.lastUpdateTime = currentTime; 8712 } 8713 } else if (pkgSetting.firstInstallTime == 0) { 8714 // We need *something*. Take time time stamp of the file. 8715 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8716 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8717 if (scanFileTime != pkgSetting.timeStamp) { 8718 // A package on the system image has changed; consider this 8719 // to be an update. 8720 pkgSetting.lastUpdateTime = scanFileTime; 8721 } 8722 } 8723 8724 // Add the package's KeySets to the global KeySetManagerService 8725 ksms.addScannedPackageLPw(pkg); 8726 8727 int N = pkg.providers.size(); 8728 StringBuilder r = null; 8729 int i; 8730 for (i=0; i<N; i++) { 8731 PackageParser.Provider p = pkg.providers.get(i); 8732 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8733 p.info.processName, pkg.applicationInfo.uid); 8734 mProviders.addProvider(p); 8735 p.syncable = p.info.isSyncable; 8736 if (p.info.authority != null) { 8737 String names[] = p.info.authority.split(";"); 8738 p.info.authority = null; 8739 for (int j = 0; j < names.length; j++) { 8740 if (j == 1 && p.syncable) { 8741 // We only want the first authority for a provider to possibly be 8742 // syncable, so if we already added this provider using a different 8743 // authority clear the syncable flag. We copy the provider before 8744 // changing it because the mProviders object contains a reference 8745 // to a provider that we don't want to change. 8746 // Only do this for the second authority since the resulting provider 8747 // object can be the same for all future authorities for this provider. 8748 p = new PackageParser.Provider(p); 8749 p.syncable = false; 8750 } 8751 if (!mProvidersByAuthority.containsKey(names[j])) { 8752 mProvidersByAuthority.put(names[j], p); 8753 if (p.info.authority == null) { 8754 p.info.authority = names[j]; 8755 } else { 8756 p.info.authority = p.info.authority + ";" + names[j]; 8757 } 8758 if (DEBUG_PACKAGE_SCANNING) { 8759 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8760 Log.d(TAG, "Registered content provider: " + names[j] 8761 + ", className = " + p.info.name + ", isSyncable = " 8762 + p.info.isSyncable); 8763 } 8764 } else { 8765 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8766 Slog.w(TAG, "Skipping provider name " + names[j] + 8767 " (in package " + pkg.applicationInfo.packageName + 8768 "): name already used by " 8769 + ((other != null && other.getComponentName() != null) 8770 ? other.getComponentName().getPackageName() : "?")); 8771 } 8772 } 8773 } 8774 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8775 if (r == null) { 8776 r = new StringBuilder(256); 8777 } else { 8778 r.append(' '); 8779 } 8780 r.append(p.info.name); 8781 } 8782 } 8783 if (r != null) { 8784 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8785 } 8786 8787 N = pkg.services.size(); 8788 r = null; 8789 for (i=0; i<N; i++) { 8790 PackageParser.Service s = pkg.services.get(i); 8791 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8792 s.info.processName, pkg.applicationInfo.uid); 8793 mServices.addService(s); 8794 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8795 if (r == null) { 8796 r = new StringBuilder(256); 8797 } else { 8798 r.append(' '); 8799 } 8800 r.append(s.info.name); 8801 } 8802 } 8803 if (r != null) { 8804 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8805 } 8806 8807 N = pkg.receivers.size(); 8808 r = null; 8809 for (i=0; i<N; i++) { 8810 PackageParser.Activity a = pkg.receivers.get(i); 8811 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8812 a.info.processName, pkg.applicationInfo.uid); 8813 mReceivers.addActivity(a, "receiver"); 8814 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8815 if (r == null) { 8816 r = new StringBuilder(256); 8817 } else { 8818 r.append(' '); 8819 } 8820 r.append(a.info.name); 8821 } 8822 } 8823 if (r != null) { 8824 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8825 } 8826 8827 N = pkg.activities.size(); 8828 r = null; 8829 for (i=0; i<N; i++) { 8830 PackageParser.Activity a = pkg.activities.get(i); 8831 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8832 a.info.processName, pkg.applicationInfo.uid); 8833 mActivities.addActivity(a, "activity"); 8834 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8835 if (r == null) { 8836 r = new StringBuilder(256); 8837 } else { 8838 r.append(' '); 8839 } 8840 r.append(a.info.name); 8841 } 8842 } 8843 if (r != null) { 8844 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8845 } 8846 8847 N = pkg.permissionGroups.size(); 8848 r = null; 8849 for (i=0; i<N; i++) { 8850 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8851 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8852 final String curPackageName = cur == null ? null : cur.info.packageName; 8853 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 8854 if (cur == null || isPackageUpdate) { 8855 mPermissionGroups.put(pg.info.name, pg); 8856 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8857 if (r == null) { 8858 r = new StringBuilder(256); 8859 } else { 8860 r.append(' '); 8861 } 8862 if (isPackageUpdate) { 8863 r.append("UPD:"); 8864 } 8865 r.append(pg.info.name); 8866 } 8867 } else { 8868 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8869 + pg.info.packageName + " ignored: original from " 8870 + cur.info.packageName); 8871 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8872 if (r == null) { 8873 r = new StringBuilder(256); 8874 } else { 8875 r.append(' '); 8876 } 8877 r.append("DUP:"); 8878 r.append(pg.info.name); 8879 } 8880 } 8881 } 8882 if (r != null) { 8883 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8884 } 8885 8886 N = pkg.permissions.size(); 8887 r = null; 8888 for (i=0; i<N; i++) { 8889 PackageParser.Permission p = pkg.permissions.get(i); 8890 8891 // Assume by default that we did not install this permission into the system. 8892 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8893 8894 // Now that permission groups have a special meaning, we ignore permission 8895 // groups for legacy apps to prevent unexpected behavior. In particular, 8896 // permissions for one app being granted to someone just becase they happen 8897 // to be in a group defined by another app (before this had no implications). 8898 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8899 p.group = mPermissionGroups.get(p.info.group); 8900 // Warn for a permission in an unknown group. 8901 if (p.info.group != null && p.group == null) { 8902 Slog.w(TAG, "Permission " + p.info.name + " from package " 8903 + p.info.packageName + " in an unknown group " + p.info.group); 8904 } 8905 } 8906 8907 ArrayMap<String, BasePermission> permissionMap = 8908 p.tree ? mSettings.mPermissionTrees 8909 : mSettings.mPermissions; 8910 BasePermission bp = permissionMap.get(p.info.name); 8911 8912 // Allow system apps to redefine non-system permissions 8913 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8914 final boolean currentOwnerIsSystem = (bp.perm != null 8915 && isSystemApp(bp.perm.owner)); 8916 if (isSystemApp(p.owner)) { 8917 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8918 // It's a built-in permission and no owner, take ownership now 8919 bp.packageSetting = pkgSetting; 8920 bp.perm = p; 8921 bp.uid = pkg.applicationInfo.uid; 8922 bp.sourcePackage = p.info.packageName; 8923 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8924 } else if (!currentOwnerIsSystem) { 8925 String msg = "New decl " + p.owner + " of permission " 8926 + p.info.name + " is system; overriding " + bp.sourcePackage; 8927 reportSettingsProblem(Log.WARN, msg); 8928 bp = null; 8929 } 8930 } 8931 } 8932 8933 if (bp == null) { 8934 bp = new BasePermission(p.info.name, p.info.packageName, 8935 BasePermission.TYPE_NORMAL); 8936 permissionMap.put(p.info.name, bp); 8937 } 8938 8939 if (bp.perm == null) { 8940 if (bp.sourcePackage == null 8941 || bp.sourcePackage.equals(p.info.packageName)) { 8942 BasePermission tree = findPermissionTreeLP(p.info.name); 8943 if (tree == null 8944 || tree.sourcePackage.equals(p.info.packageName)) { 8945 bp.packageSetting = pkgSetting; 8946 bp.perm = p; 8947 bp.uid = pkg.applicationInfo.uid; 8948 bp.sourcePackage = p.info.packageName; 8949 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8950 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8951 if (r == null) { 8952 r = new StringBuilder(256); 8953 } else { 8954 r.append(' '); 8955 } 8956 r.append(p.info.name); 8957 } 8958 } else { 8959 Slog.w(TAG, "Permission " + p.info.name + " from package " 8960 + p.info.packageName + " ignored: base tree " 8961 + tree.name + " is from package " 8962 + tree.sourcePackage); 8963 } 8964 } else { 8965 Slog.w(TAG, "Permission " + p.info.name + " from package " 8966 + p.info.packageName + " ignored: original from " 8967 + bp.sourcePackage); 8968 } 8969 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8970 if (r == null) { 8971 r = new StringBuilder(256); 8972 } else { 8973 r.append(' '); 8974 } 8975 r.append("DUP:"); 8976 r.append(p.info.name); 8977 } 8978 if (bp.perm == p) { 8979 bp.protectionLevel = p.info.protectionLevel; 8980 } 8981 } 8982 8983 if (r != null) { 8984 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8985 } 8986 8987 N = pkg.instrumentation.size(); 8988 r = null; 8989 for (i=0; i<N; i++) { 8990 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8991 a.info.packageName = pkg.applicationInfo.packageName; 8992 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8993 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8994 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8995 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8996 a.info.dataDir = pkg.applicationInfo.dataDir; 8997 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8998 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8999 9000 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 9001 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 9002 mInstrumentation.put(a.getComponentName(), a); 9003 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 9004 if (r == null) { 9005 r = new StringBuilder(256); 9006 } else { 9007 r.append(' '); 9008 } 9009 r.append(a.info.name); 9010 } 9011 } 9012 if (r != null) { 9013 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9014 } 9015 9016 if (pkg.protectedBroadcasts != null) { 9017 N = pkg.protectedBroadcasts.size(); 9018 for (i=0; i<N; i++) { 9019 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9020 } 9021 } 9022 9023 pkgSetting.setTimeStamp(scanFileTime); 9024 9025 // Create idmap files for pairs of (packages, overlay packages). 9026 // Note: "android", ie framework-res.apk, is handled by native layers. 9027 if (pkg.mOverlayTarget != null) { 9028 // This is an overlay package. 9029 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9030 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9031 mOverlays.put(pkg.mOverlayTarget, 9032 new ArrayMap<String, PackageParser.Package>()); 9033 } 9034 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9035 map.put(pkg.packageName, pkg); 9036 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9037 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9038 createIdmapFailed = true; 9039 } 9040 } 9041 } else if (mOverlays.containsKey(pkg.packageName) && 9042 !pkg.packageName.equals("android")) { 9043 // This is a regular package, with one or more known overlay packages. 9044 createIdmapsForPackageLI(pkg); 9045 } 9046 } 9047 9048 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9049 9050 if (createIdmapFailed) { 9051 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9052 "scanPackageLI failed to createIdmap"); 9053 } 9054 return pkg; 9055 } 9056 9057 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9058 PackageParser.Package update, UserHandle user) { 9059 if (existing.applicationInfo == null || update.applicationInfo == null) { 9060 // This isn't due to an app installation. 9061 return; 9062 } 9063 9064 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9065 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9066 9067 // The codePath hasn't changed, so there's nothing for us to do. 9068 if (Objects.equals(oldCodePath, newCodePath)) { 9069 return; 9070 } 9071 9072 File canonicalNewCodePath; 9073 try { 9074 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9075 } catch (IOException e) { 9076 Slog.w(TAG, "Failed to get canonical path.", e); 9077 return; 9078 } 9079 9080 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9081 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9082 // that the last component of the path (i.e, the name) doesn't need canonicalization 9083 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9084 // but may change in the future. Hopefully this function won't exist at that point. 9085 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9086 oldCodePath.getName()); 9087 9088 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9089 // with "@". 9090 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9091 if (!oldMarkerPrefix.endsWith("@")) { 9092 oldMarkerPrefix += "@"; 9093 } 9094 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9095 if (!newMarkerPrefix.endsWith("@")) { 9096 newMarkerPrefix += "@"; 9097 } 9098 9099 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9100 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9101 for (String updatedPath : updatedPaths) { 9102 String updatedPathName = new File(updatedPath).getName(); 9103 markerSuffixes.add(updatedPathName.replace('/', '@')); 9104 } 9105 9106 for (int userId : resolveUserIds(user.getIdentifier())) { 9107 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9108 9109 for (String markerSuffix : markerSuffixes) { 9110 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9111 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9112 if (oldForeignUseMark.exists()) { 9113 try { 9114 Os.rename(oldForeignUseMark.getAbsolutePath(), 9115 newForeignUseMark.getAbsolutePath()); 9116 } catch (ErrnoException e) { 9117 Slog.w(TAG, "Failed to rename foreign use marker", e); 9118 oldForeignUseMark.delete(); 9119 } 9120 } 9121 } 9122 } 9123 } 9124 9125 /** 9126 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9127 * is derived purely on the basis of the contents of {@code scanFile} and 9128 * {@code cpuAbiOverride}. 9129 * 9130 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9131 */ 9132 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9133 String cpuAbiOverride, boolean extractLibs) 9134 throws PackageManagerException { 9135 // TODO: We can probably be smarter about this stuff. For installed apps, 9136 // we can calculate this information at install time once and for all. For 9137 // system apps, we can probably assume that this information doesn't change 9138 // after the first boot scan. As things stand, we do lots of unnecessary work. 9139 9140 // Give ourselves some initial paths; we'll come back for another 9141 // pass once we've determined ABI below. 9142 setNativeLibraryPaths(pkg); 9143 9144 // We would never need to extract libs for forward-locked and external packages, 9145 // since the container service will do it for us. We shouldn't attempt to 9146 // extract libs from system app when it was not updated. 9147 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9148 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9149 extractLibs = false; 9150 } 9151 9152 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9153 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9154 9155 NativeLibraryHelper.Handle handle = null; 9156 try { 9157 handle = NativeLibraryHelper.Handle.create(pkg); 9158 // TODO(multiArch): This can be null for apps that didn't go through the 9159 // usual installation process. We can calculate it again, like we 9160 // do during install time. 9161 // 9162 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9163 // unnecessary. 9164 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9165 9166 // Null out the abis so that they can be recalculated. 9167 pkg.applicationInfo.primaryCpuAbi = null; 9168 pkg.applicationInfo.secondaryCpuAbi = null; 9169 if (isMultiArch(pkg.applicationInfo)) { 9170 // Warn if we've set an abiOverride for multi-lib packages.. 9171 // By definition, we need to copy both 32 and 64 bit libraries for 9172 // such packages. 9173 if (pkg.cpuAbiOverride != null 9174 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9175 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9176 } 9177 9178 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9179 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9180 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9181 if (extractLibs) { 9182 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9183 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9184 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9185 useIsaSpecificSubdirs); 9186 } else { 9187 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9188 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9189 } 9190 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9191 } 9192 9193 maybeThrowExceptionForMultiArchCopy( 9194 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9195 9196 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9197 if (extractLibs) { 9198 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9199 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9200 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9201 useIsaSpecificSubdirs); 9202 } else { 9203 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9204 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9205 } 9206 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9207 } 9208 9209 maybeThrowExceptionForMultiArchCopy( 9210 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9211 9212 if (abi64 >= 0) { 9213 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9214 } 9215 9216 if (abi32 >= 0) { 9217 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9218 if (abi64 >= 0) { 9219 if (pkg.use32bitAbi) { 9220 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9221 pkg.applicationInfo.primaryCpuAbi = abi; 9222 } else { 9223 pkg.applicationInfo.secondaryCpuAbi = abi; 9224 } 9225 } else { 9226 pkg.applicationInfo.primaryCpuAbi = abi; 9227 } 9228 } 9229 9230 } else { 9231 String[] abiList = (cpuAbiOverride != null) ? 9232 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9233 9234 // Enable gross and lame hacks for apps that are built with old 9235 // SDK tools. We must scan their APKs for renderscript bitcode and 9236 // not launch them if it's present. Don't bother checking on devices 9237 // that don't have 64 bit support. 9238 boolean needsRenderScriptOverride = false; 9239 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9240 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9241 abiList = Build.SUPPORTED_32_BIT_ABIS; 9242 needsRenderScriptOverride = true; 9243 } 9244 9245 final int copyRet; 9246 if (extractLibs) { 9247 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9248 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9249 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9250 } else { 9251 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9252 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9253 } 9254 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9255 9256 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9257 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9258 "Error unpackaging native libs for app, errorCode=" + copyRet); 9259 } 9260 9261 if (copyRet >= 0) { 9262 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9263 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9264 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9265 } else if (needsRenderScriptOverride) { 9266 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9267 } 9268 } 9269 } catch (IOException ioe) { 9270 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9271 } finally { 9272 IoUtils.closeQuietly(handle); 9273 } 9274 9275 // Now that we've calculated the ABIs and determined if it's an internal app, 9276 // we will go ahead and populate the nativeLibraryPath. 9277 setNativeLibraryPaths(pkg); 9278 } 9279 9280 /** 9281 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9282 * i.e, so that all packages can be run inside a single process if required. 9283 * 9284 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9285 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9286 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9287 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9288 * updating a package that belongs to a shared user. 9289 * 9290 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9291 * adds unnecessary complexity. 9292 */ 9293 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9294 PackageParser.Package scannedPackage, boolean bootComplete) { 9295 String requiredInstructionSet = null; 9296 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9297 requiredInstructionSet = VMRuntime.getInstructionSet( 9298 scannedPackage.applicationInfo.primaryCpuAbi); 9299 } 9300 9301 PackageSetting requirer = null; 9302 for (PackageSetting ps : packagesForUser) { 9303 // If packagesForUser contains scannedPackage, we skip it. This will happen 9304 // when scannedPackage is an update of an existing package. Without this check, 9305 // we will never be able to change the ABI of any package belonging to a shared 9306 // user, even if it's compatible with other packages. 9307 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9308 if (ps.primaryCpuAbiString == null) { 9309 continue; 9310 } 9311 9312 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9313 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9314 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9315 // this but there's not much we can do. 9316 String errorMessage = "Instruction set mismatch, " 9317 + ((requirer == null) ? "[caller]" : requirer) 9318 + " requires " + requiredInstructionSet + " whereas " + ps 9319 + " requires " + instructionSet; 9320 Slog.w(TAG, errorMessage); 9321 } 9322 9323 if (requiredInstructionSet == null) { 9324 requiredInstructionSet = instructionSet; 9325 requirer = ps; 9326 } 9327 } 9328 } 9329 9330 if (requiredInstructionSet != null) { 9331 String adjustedAbi; 9332 if (requirer != null) { 9333 // requirer != null implies that either scannedPackage was null or that scannedPackage 9334 // did not require an ABI, in which case we have to adjust scannedPackage to match 9335 // the ABI of the set (which is the same as requirer's ABI) 9336 adjustedAbi = requirer.primaryCpuAbiString; 9337 if (scannedPackage != null) { 9338 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9339 } 9340 } else { 9341 // requirer == null implies that we're updating all ABIs in the set to 9342 // match scannedPackage. 9343 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9344 } 9345 9346 for (PackageSetting ps : packagesForUser) { 9347 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9348 if (ps.primaryCpuAbiString != null) { 9349 continue; 9350 } 9351 9352 ps.primaryCpuAbiString = adjustedAbi; 9353 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9354 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9355 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9356 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9357 + " (requirer=" 9358 + (requirer == null ? "null" : requirer.pkg.packageName) 9359 + ", scannedPackage=" 9360 + (scannedPackage != null ? scannedPackage.packageName : "null") 9361 + ")"); 9362 try { 9363 mInstaller.rmdex(ps.codePathString, 9364 getDexCodeInstructionSet(getPreferredInstructionSet())); 9365 } catch (InstallerException ignored) { 9366 } 9367 } 9368 } 9369 } 9370 } 9371 } 9372 9373 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9374 synchronized (mPackages) { 9375 mResolverReplaced = true; 9376 // Set up information for custom user intent resolution activity. 9377 mResolveActivity.applicationInfo = pkg.applicationInfo; 9378 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9379 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9380 mResolveActivity.processName = pkg.applicationInfo.packageName; 9381 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9382 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9383 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9384 mResolveActivity.theme = 0; 9385 mResolveActivity.exported = true; 9386 mResolveActivity.enabled = true; 9387 mResolveInfo.activityInfo = mResolveActivity; 9388 mResolveInfo.priority = 0; 9389 mResolveInfo.preferredOrder = 0; 9390 mResolveInfo.match = 0; 9391 mResolveComponentName = mCustomResolverComponentName; 9392 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9393 mResolveComponentName); 9394 } 9395 } 9396 9397 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9398 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9399 9400 // Set up information for ephemeral installer activity 9401 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9402 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9403 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9404 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9405 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9406 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9407 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9408 mEphemeralInstallerActivity.theme = 0; 9409 mEphemeralInstallerActivity.exported = true; 9410 mEphemeralInstallerActivity.enabled = true; 9411 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9412 mEphemeralInstallerInfo.priority = 0; 9413 mEphemeralInstallerInfo.preferredOrder = 1; 9414 mEphemeralInstallerInfo.isDefault = true; 9415 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9416 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9417 9418 if (DEBUG_EPHEMERAL) { 9419 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9420 } 9421 } 9422 9423 private static String calculateBundledApkRoot(final String codePathString) { 9424 final File codePath = new File(codePathString); 9425 final File codeRoot; 9426 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9427 codeRoot = Environment.getRootDirectory(); 9428 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9429 codeRoot = Environment.getOemDirectory(); 9430 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9431 codeRoot = Environment.getVendorDirectory(); 9432 } else { 9433 // Unrecognized code path; take its top real segment as the apk root: 9434 // e.g. /something/app/blah.apk => /something 9435 try { 9436 File f = codePath.getCanonicalFile(); 9437 File parent = f.getParentFile(); // non-null because codePath is a file 9438 File tmp; 9439 while ((tmp = parent.getParentFile()) != null) { 9440 f = parent; 9441 parent = tmp; 9442 } 9443 codeRoot = f; 9444 Slog.w(TAG, "Unrecognized code path " 9445 + codePath + " - using " + codeRoot); 9446 } catch (IOException e) { 9447 // Can't canonicalize the code path -- shenanigans? 9448 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9449 return Environment.getRootDirectory().getPath(); 9450 } 9451 } 9452 return codeRoot.getPath(); 9453 } 9454 9455 /** 9456 * Derive and set the location of native libraries for the given package, 9457 * which varies depending on where and how the package was installed. 9458 */ 9459 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9460 final ApplicationInfo info = pkg.applicationInfo; 9461 final String codePath = pkg.codePath; 9462 final File codeFile = new File(codePath); 9463 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9464 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9465 9466 info.nativeLibraryRootDir = null; 9467 info.nativeLibraryRootRequiresIsa = false; 9468 info.nativeLibraryDir = null; 9469 info.secondaryNativeLibraryDir = null; 9470 9471 if (isApkFile(codeFile)) { 9472 // Monolithic install 9473 if (bundledApp) { 9474 // If "/system/lib64/apkname" exists, assume that is the per-package 9475 // native library directory to use; otherwise use "/system/lib/apkname". 9476 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9477 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9478 getPrimaryInstructionSet(info)); 9479 9480 // This is a bundled system app so choose the path based on the ABI. 9481 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9482 // is just the default path. 9483 final String apkName = deriveCodePathName(codePath); 9484 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9485 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9486 apkName).getAbsolutePath(); 9487 9488 if (info.secondaryCpuAbi != null) { 9489 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9490 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9491 secondaryLibDir, apkName).getAbsolutePath(); 9492 } 9493 } else if (asecApp) { 9494 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9495 .getAbsolutePath(); 9496 } else { 9497 final String apkName = deriveCodePathName(codePath); 9498 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9499 .getAbsolutePath(); 9500 } 9501 9502 info.nativeLibraryRootRequiresIsa = false; 9503 info.nativeLibraryDir = info.nativeLibraryRootDir; 9504 } else { 9505 // Cluster install 9506 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9507 info.nativeLibraryRootRequiresIsa = true; 9508 9509 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9510 getPrimaryInstructionSet(info)).getAbsolutePath(); 9511 9512 if (info.secondaryCpuAbi != null) { 9513 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9514 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9515 } 9516 } 9517 } 9518 9519 /** 9520 * Calculate the abis and roots for a bundled app. These can uniquely 9521 * be determined from the contents of the system partition, i.e whether 9522 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9523 * of this information, and instead assume that the system was built 9524 * sensibly. 9525 */ 9526 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9527 PackageSetting pkgSetting) { 9528 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9529 9530 // If "/system/lib64/apkname" exists, assume that is the per-package 9531 // native library directory to use; otherwise use "/system/lib/apkname". 9532 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9533 setBundledAppAbi(pkg, apkRoot, apkName); 9534 // pkgSetting might be null during rescan following uninstall of updates 9535 // to a bundled app, so accommodate that possibility. The settings in 9536 // that case will be established later from the parsed package. 9537 // 9538 // If the settings aren't null, sync them up with what we've just derived. 9539 // note that apkRoot isn't stored in the package settings. 9540 if (pkgSetting != null) { 9541 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9542 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9543 } 9544 } 9545 9546 /** 9547 * Deduces the ABI of a bundled app and sets the relevant fields on the 9548 * parsed pkg object. 9549 * 9550 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9551 * under which system libraries are installed. 9552 * @param apkName the name of the installed package. 9553 */ 9554 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9555 final File codeFile = new File(pkg.codePath); 9556 9557 final boolean has64BitLibs; 9558 final boolean has32BitLibs; 9559 if (isApkFile(codeFile)) { 9560 // Monolithic install 9561 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9562 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9563 } else { 9564 // Cluster install 9565 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9566 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9567 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9568 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9569 has64BitLibs = (new File(rootDir, isa)).exists(); 9570 } else { 9571 has64BitLibs = false; 9572 } 9573 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9574 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9575 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9576 has32BitLibs = (new File(rootDir, isa)).exists(); 9577 } else { 9578 has32BitLibs = false; 9579 } 9580 } 9581 9582 if (has64BitLibs && !has32BitLibs) { 9583 // The package has 64 bit libs, but not 32 bit libs. Its primary 9584 // ABI should be 64 bit. We can safely assume here that the bundled 9585 // native libraries correspond to the most preferred ABI in the list. 9586 9587 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9588 pkg.applicationInfo.secondaryCpuAbi = null; 9589 } else if (has32BitLibs && !has64BitLibs) { 9590 // The package has 32 bit libs but not 64 bit libs. Its primary 9591 // ABI should be 32 bit. 9592 9593 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9594 pkg.applicationInfo.secondaryCpuAbi = null; 9595 } else if (has32BitLibs && has64BitLibs) { 9596 // The application has both 64 and 32 bit bundled libraries. We check 9597 // here that the app declares multiArch support, and warn if it doesn't. 9598 // 9599 // We will be lenient here and record both ABIs. The primary will be the 9600 // ABI that's higher on the list, i.e, a device that's configured to prefer 9601 // 64 bit apps will see a 64 bit primary ABI, 9602 9603 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9604 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9605 } 9606 9607 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9608 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9609 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9610 } else { 9611 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9612 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9613 } 9614 } else { 9615 pkg.applicationInfo.primaryCpuAbi = null; 9616 pkg.applicationInfo.secondaryCpuAbi = null; 9617 } 9618 } 9619 9620 private void killApplication(String pkgName, int appId, String reason) { 9621 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9622 } 9623 9624 private void killApplication(String pkgName, int appId, int userId, String reason) { 9625 // Request the ActivityManager to kill the process(only for existing packages) 9626 // so that we do not end up in a confused state while the user is still using the older 9627 // version of the application while the new one gets installed. 9628 final long token = Binder.clearCallingIdentity(); 9629 try { 9630 IActivityManager am = ActivityManagerNative.getDefault(); 9631 if (am != null) { 9632 try { 9633 am.killApplication(pkgName, appId, userId, reason); 9634 } catch (RemoteException e) { 9635 } 9636 } 9637 } finally { 9638 Binder.restoreCallingIdentity(token); 9639 } 9640 } 9641 9642 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9643 // Remove the parent package setting 9644 PackageSetting ps = (PackageSetting) pkg.mExtras; 9645 if (ps != null) { 9646 removePackageLI(ps, chatty); 9647 } 9648 // Remove the child package setting 9649 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9650 for (int i = 0; i < childCount; i++) { 9651 PackageParser.Package childPkg = pkg.childPackages.get(i); 9652 ps = (PackageSetting) childPkg.mExtras; 9653 if (ps != null) { 9654 removePackageLI(ps, chatty); 9655 } 9656 } 9657 } 9658 9659 void removePackageLI(PackageSetting ps, boolean chatty) { 9660 if (DEBUG_INSTALL) { 9661 if (chatty) 9662 Log.d(TAG, "Removing package " + ps.name); 9663 } 9664 9665 // writer 9666 synchronized (mPackages) { 9667 mPackages.remove(ps.name); 9668 final PackageParser.Package pkg = ps.pkg; 9669 if (pkg != null) { 9670 cleanPackageDataStructuresLILPw(pkg, chatty); 9671 } 9672 } 9673 } 9674 9675 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9676 if (DEBUG_INSTALL) { 9677 if (chatty) 9678 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9679 } 9680 9681 // writer 9682 synchronized (mPackages) { 9683 // Remove the parent package 9684 mPackages.remove(pkg.applicationInfo.packageName); 9685 cleanPackageDataStructuresLILPw(pkg, chatty); 9686 9687 // Remove the child packages 9688 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9689 for (int i = 0; i < childCount; i++) { 9690 PackageParser.Package childPkg = pkg.childPackages.get(i); 9691 mPackages.remove(childPkg.applicationInfo.packageName); 9692 cleanPackageDataStructuresLILPw(childPkg, chatty); 9693 } 9694 } 9695 } 9696 9697 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9698 int N = pkg.providers.size(); 9699 StringBuilder r = null; 9700 int i; 9701 for (i=0; i<N; i++) { 9702 PackageParser.Provider p = pkg.providers.get(i); 9703 mProviders.removeProvider(p); 9704 if (p.info.authority == null) { 9705 9706 /* There was another ContentProvider with this authority when 9707 * this app was installed so this authority is null, 9708 * Ignore it as we don't have to unregister the provider. 9709 */ 9710 continue; 9711 } 9712 String names[] = p.info.authority.split(";"); 9713 for (int j = 0; j < names.length; j++) { 9714 if (mProvidersByAuthority.get(names[j]) == p) { 9715 mProvidersByAuthority.remove(names[j]); 9716 if (DEBUG_REMOVE) { 9717 if (chatty) 9718 Log.d(TAG, "Unregistered content provider: " + names[j] 9719 + ", className = " + p.info.name + ", isSyncable = " 9720 + p.info.isSyncable); 9721 } 9722 } 9723 } 9724 if (DEBUG_REMOVE && chatty) { 9725 if (r == null) { 9726 r = new StringBuilder(256); 9727 } else { 9728 r.append(' '); 9729 } 9730 r.append(p.info.name); 9731 } 9732 } 9733 if (r != null) { 9734 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9735 } 9736 9737 N = pkg.services.size(); 9738 r = null; 9739 for (i=0; i<N; i++) { 9740 PackageParser.Service s = pkg.services.get(i); 9741 mServices.removeService(s); 9742 if (chatty) { 9743 if (r == null) { 9744 r = new StringBuilder(256); 9745 } else { 9746 r.append(' '); 9747 } 9748 r.append(s.info.name); 9749 } 9750 } 9751 if (r != null) { 9752 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9753 } 9754 9755 N = pkg.receivers.size(); 9756 r = null; 9757 for (i=0; i<N; i++) { 9758 PackageParser.Activity a = pkg.receivers.get(i); 9759 mReceivers.removeActivity(a, "receiver"); 9760 if (DEBUG_REMOVE && chatty) { 9761 if (r == null) { 9762 r = new StringBuilder(256); 9763 } else { 9764 r.append(' '); 9765 } 9766 r.append(a.info.name); 9767 } 9768 } 9769 if (r != null) { 9770 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9771 } 9772 9773 N = pkg.activities.size(); 9774 r = null; 9775 for (i=0; i<N; i++) { 9776 PackageParser.Activity a = pkg.activities.get(i); 9777 mActivities.removeActivity(a, "activity"); 9778 if (DEBUG_REMOVE && chatty) { 9779 if (r == null) { 9780 r = new StringBuilder(256); 9781 } else { 9782 r.append(' '); 9783 } 9784 r.append(a.info.name); 9785 } 9786 } 9787 if (r != null) { 9788 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9789 } 9790 9791 N = pkg.permissions.size(); 9792 r = null; 9793 for (i=0; i<N; i++) { 9794 PackageParser.Permission p = pkg.permissions.get(i); 9795 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9796 if (bp == null) { 9797 bp = mSettings.mPermissionTrees.get(p.info.name); 9798 } 9799 if (bp != null && bp.perm == p) { 9800 bp.perm = null; 9801 if (DEBUG_REMOVE && chatty) { 9802 if (r == null) { 9803 r = new StringBuilder(256); 9804 } else { 9805 r.append(' '); 9806 } 9807 r.append(p.info.name); 9808 } 9809 } 9810 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9811 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9812 if (appOpPkgs != null) { 9813 appOpPkgs.remove(pkg.packageName); 9814 } 9815 } 9816 } 9817 if (r != null) { 9818 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9819 } 9820 9821 N = pkg.requestedPermissions.size(); 9822 r = null; 9823 for (i=0; i<N; i++) { 9824 String perm = pkg.requestedPermissions.get(i); 9825 BasePermission bp = mSettings.mPermissions.get(perm); 9826 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9827 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9828 if (appOpPkgs != null) { 9829 appOpPkgs.remove(pkg.packageName); 9830 if (appOpPkgs.isEmpty()) { 9831 mAppOpPermissionPackages.remove(perm); 9832 } 9833 } 9834 } 9835 } 9836 if (r != null) { 9837 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9838 } 9839 9840 N = pkg.instrumentation.size(); 9841 r = null; 9842 for (i=0; i<N; i++) { 9843 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9844 mInstrumentation.remove(a.getComponentName()); 9845 if (DEBUG_REMOVE && chatty) { 9846 if (r == null) { 9847 r = new StringBuilder(256); 9848 } else { 9849 r.append(' '); 9850 } 9851 r.append(a.info.name); 9852 } 9853 } 9854 if (r != null) { 9855 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9856 } 9857 9858 r = null; 9859 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9860 // Only system apps can hold shared libraries. 9861 if (pkg.libraryNames != null) { 9862 for (i=0; i<pkg.libraryNames.size(); i++) { 9863 String name = pkg.libraryNames.get(i); 9864 SharedLibraryEntry cur = mSharedLibraries.get(name); 9865 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9866 mSharedLibraries.remove(name); 9867 if (DEBUG_REMOVE && chatty) { 9868 if (r == null) { 9869 r = new StringBuilder(256); 9870 } else { 9871 r.append(' '); 9872 } 9873 r.append(name); 9874 } 9875 } 9876 } 9877 } 9878 } 9879 if (r != null) { 9880 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9881 } 9882 } 9883 9884 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9885 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9886 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9887 return true; 9888 } 9889 } 9890 return false; 9891 } 9892 9893 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9894 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9895 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9896 9897 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9898 // Update the parent permissions 9899 updatePermissionsLPw(pkg.packageName, pkg, flags); 9900 // Update the child permissions 9901 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9902 for (int i = 0; i < childCount; i++) { 9903 PackageParser.Package childPkg = pkg.childPackages.get(i); 9904 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9905 } 9906 } 9907 9908 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9909 int flags) { 9910 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9911 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9912 } 9913 9914 private void updatePermissionsLPw(String changingPkg, 9915 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9916 // Make sure there are no dangling permission trees. 9917 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9918 while (it.hasNext()) { 9919 final BasePermission bp = it.next(); 9920 if (bp.packageSetting == null) { 9921 // We may not yet have parsed the package, so just see if 9922 // we still know about its settings. 9923 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9924 } 9925 if (bp.packageSetting == null) { 9926 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9927 + " from package " + bp.sourcePackage); 9928 it.remove(); 9929 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9930 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9931 Slog.i(TAG, "Removing old permission tree: " + bp.name 9932 + " from package " + bp.sourcePackage); 9933 flags |= UPDATE_PERMISSIONS_ALL; 9934 it.remove(); 9935 } 9936 } 9937 } 9938 9939 // Make sure all dynamic permissions have been assigned to a package, 9940 // and make sure there are no dangling permissions. 9941 it = mSettings.mPermissions.values().iterator(); 9942 while (it.hasNext()) { 9943 final BasePermission bp = it.next(); 9944 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9945 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9946 + bp.name + " pkg=" + bp.sourcePackage 9947 + " info=" + bp.pendingInfo); 9948 if (bp.packageSetting == null && bp.pendingInfo != null) { 9949 final BasePermission tree = findPermissionTreeLP(bp.name); 9950 if (tree != null && tree.perm != null) { 9951 bp.packageSetting = tree.packageSetting; 9952 bp.perm = new PackageParser.Permission(tree.perm.owner, 9953 new PermissionInfo(bp.pendingInfo)); 9954 bp.perm.info.packageName = tree.perm.info.packageName; 9955 bp.perm.info.name = bp.name; 9956 bp.uid = tree.uid; 9957 } 9958 } 9959 } 9960 if (bp.packageSetting == null) { 9961 // We may not yet have parsed the package, so just see if 9962 // we still know about its settings. 9963 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9964 } 9965 if (bp.packageSetting == null) { 9966 Slog.w(TAG, "Removing dangling permission: " + bp.name 9967 + " from package " + bp.sourcePackage); 9968 it.remove(); 9969 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9970 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9971 Slog.i(TAG, "Removing old permission: " + bp.name 9972 + " from package " + bp.sourcePackage); 9973 flags |= UPDATE_PERMISSIONS_ALL; 9974 it.remove(); 9975 } 9976 } 9977 } 9978 9979 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9980 // Now update the permissions for all packages, in particular 9981 // replace the granted permissions of the system packages. 9982 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9983 for (PackageParser.Package pkg : mPackages.values()) { 9984 if (pkg != pkgInfo) { 9985 // Only replace for packages on requested volume 9986 final String volumeUuid = getVolumeUuidForPackage(pkg); 9987 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9988 && Objects.equals(replaceVolumeUuid, volumeUuid); 9989 grantPermissionsLPw(pkg, replace, changingPkg); 9990 } 9991 } 9992 } 9993 9994 if (pkgInfo != null) { 9995 // Only replace for packages on requested volume 9996 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9997 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9998 && Objects.equals(replaceVolumeUuid, volumeUuid); 9999 grantPermissionsLPw(pkgInfo, replace, changingPkg); 10000 } 10001 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10002 } 10003 10004 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 10005 String packageOfInterest) { 10006 // IMPORTANT: There are two types of permissions: install and runtime. 10007 // Install time permissions are granted when the app is installed to 10008 // all device users and users added in the future. Runtime permissions 10009 // are granted at runtime explicitly to specific users. Normal and signature 10010 // protected permissions are install time permissions. Dangerous permissions 10011 // are install permissions if the app's target SDK is Lollipop MR1 or older, 10012 // otherwise they are runtime permissions. This function does not manage 10013 // runtime permissions except for the case an app targeting Lollipop MR1 10014 // being upgraded to target a newer SDK, in which case dangerous permissions 10015 // are transformed from install time to runtime ones. 10016 10017 final PackageSetting ps = (PackageSetting) pkg.mExtras; 10018 if (ps == null) { 10019 return; 10020 } 10021 10022 PermissionsState permissionsState = ps.getPermissionsState(); 10023 PermissionsState origPermissions = permissionsState; 10024 10025 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10026 10027 boolean runtimePermissionsRevoked = false; 10028 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10029 10030 boolean changedInstallPermission = false; 10031 10032 if (replace) { 10033 ps.installPermissionsFixed = false; 10034 if (!ps.isSharedUser()) { 10035 origPermissions = new PermissionsState(permissionsState); 10036 permissionsState.reset(); 10037 } else { 10038 // We need to know only about runtime permission changes since the 10039 // calling code always writes the install permissions state but 10040 // the runtime ones are written only if changed. The only cases of 10041 // changed runtime permissions here are promotion of an install to 10042 // runtime and revocation of a runtime from a shared user. 10043 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10044 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10045 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10046 runtimePermissionsRevoked = true; 10047 } 10048 } 10049 } 10050 10051 permissionsState.setGlobalGids(mGlobalGids); 10052 10053 final int N = pkg.requestedPermissions.size(); 10054 for (int i=0; i<N; i++) { 10055 final String name = pkg.requestedPermissions.get(i); 10056 final BasePermission bp = mSettings.mPermissions.get(name); 10057 10058 if (DEBUG_INSTALL) { 10059 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10060 } 10061 10062 if (bp == null || bp.packageSetting == null) { 10063 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10064 Slog.w(TAG, "Unknown permission " + name 10065 + " in package " + pkg.packageName); 10066 } 10067 continue; 10068 } 10069 10070 final String perm = bp.name; 10071 boolean allowedSig = false; 10072 int grant = GRANT_DENIED; 10073 10074 // Keep track of app op permissions. 10075 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10076 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10077 if (pkgs == null) { 10078 pkgs = new ArraySet<>(); 10079 mAppOpPermissionPackages.put(bp.name, pkgs); 10080 } 10081 pkgs.add(pkg.packageName); 10082 } 10083 10084 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10085 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10086 >= Build.VERSION_CODES.M; 10087 switch (level) { 10088 case PermissionInfo.PROTECTION_NORMAL: { 10089 // For all apps normal permissions are install time ones. 10090 grant = GRANT_INSTALL; 10091 } break; 10092 10093 case PermissionInfo.PROTECTION_DANGEROUS: { 10094 // If a permission review is required for legacy apps we represent 10095 // their permissions as always granted runtime ones since we need 10096 // to keep the review required permission flag per user while an 10097 // install permission's state is shared across all users. 10098 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 10099 // For legacy apps dangerous permissions are install time ones. 10100 grant = GRANT_INSTALL; 10101 } else if (origPermissions.hasInstallPermission(bp.name)) { 10102 // For legacy apps that became modern, install becomes runtime. 10103 grant = GRANT_UPGRADE; 10104 } else if (mPromoteSystemApps 10105 && isSystemApp(ps) 10106 && mExistingSystemPackages.contains(ps.name)) { 10107 // For legacy system apps, install becomes runtime. 10108 // We cannot check hasInstallPermission() for system apps since those 10109 // permissions were granted implicitly and not persisted pre-M. 10110 grant = GRANT_UPGRADE; 10111 } else { 10112 // For modern apps keep runtime permissions unchanged. 10113 grant = GRANT_RUNTIME; 10114 } 10115 } break; 10116 10117 case PermissionInfo.PROTECTION_SIGNATURE: { 10118 // For all apps signature permissions are install time ones. 10119 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10120 if (allowedSig) { 10121 grant = GRANT_INSTALL; 10122 } 10123 } break; 10124 } 10125 10126 if (DEBUG_INSTALL) { 10127 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10128 } 10129 10130 if (grant != GRANT_DENIED) { 10131 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10132 // If this is an existing, non-system package, then 10133 // we can't add any new permissions to it. 10134 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10135 // Except... if this is a permission that was added 10136 // to the platform (note: need to only do this when 10137 // updating the platform). 10138 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10139 grant = GRANT_DENIED; 10140 } 10141 } 10142 } 10143 10144 switch (grant) { 10145 case GRANT_INSTALL: { 10146 // Revoke this as runtime permission to handle the case of 10147 // a runtime permission being downgraded to an install one. 10148 // Also in permission review mode we keep dangerous permissions 10149 // for legacy apps 10150 for (int userId : UserManagerService.getInstance().getUserIds()) { 10151 if (origPermissions.getRuntimePermissionState( 10152 bp.name, userId) != null) { 10153 // Revoke the runtime permission and clear the flags. 10154 origPermissions.revokeRuntimePermission(bp, userId); 10155 origPermissions.updatePermissionFlags(bp, userId, 10156 PackageManager.MASK_PERMISSION_FLAGS, 0); 10157 // If we revoked a permission permission, we have to write. 10158 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10159 changedRuntimePermissionUserIds, userId); 10160 } 10161 } 10162 // Grant an install permission. 10163 if (permissionsState.grantInstallPermission(bp) != 10164 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10165 changedInstallPermission = true; 10166 } 10167 } break; 10168 10169 case GRANT_RUNTIME: { 10170 // Grant previously granted runtime permissions. 10171 for (int userId : UserManagerService.getInstance().getUserIds()) { 10172 PermissionState permissionState = origPermissions 10173 .getRuntimePermissionState(bp.name, userId); 10174 int flags = permissionState != null 10175 ? permissionState.getFlags() : 0; 10176 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10177 if (permissionsState.grantRuntimePermission(bp, userId) == 10178 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10179 // If we cannot put the permission as it was, we have to write. 10180 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10181 changedRuntimePermissionUserIds, userId); 10182 } 10183 // If the app supports runtime permissions no need for a review. 10184 if (mPermissionReviewRequired 10185 && appSupportsRuntimePermissions 10186 && (flags & PackageManager 10187 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10188 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10189 // Since we changed the flags, we have to write. 10190 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10191 changedRuntimePermissionUserIds, userId); 10192 } 10193 } else if (mPermissionReviewRequired 10194 && !appSupportsRuntimePermissions) { 10195 // For legacy apps that need a permission review, every new 10196 // runtime permission is granted but it is pending a review. 10197 // We also need to review only platform defined runtime 10198 // permissions as these are the only ones the platform knows 10199 // how to disable the API to simulate revocation as legacy 10200 // apps don't expect to run with revoked permissions. 10201 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10202 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10203 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10204 // We changed the flags, hence have to write. 10205 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10206 changedRuntimePermissionUserIds, userId); 10207 } 10208 } 10209 if (permissionsState.grantRuntimePermission(bp, userId) 10210 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10211 // We changed the permission, hence have to write. 10212 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10213 changedRuntimePermissionUserIds, userId); 10214 } 10215 } 10216 // Propagate the permission flags. 10217 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10218 } 10219 } break; 10220 10221 case GRANT_UPGRADE: { 10222 // Grant runtime permissions for a previously held install permission. 10223 PermissionState permissionState = origPermissions 10224 .getInstallPermissionState(bp.name); 10225 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10226 10227 if (origPermissions.revokeInstallPermission(bp) 10228 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10229 // We will be transferring the permission flags, so clear them. 10230 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10231 PackageManager.MASK_PERMISSION_FLAGS, 0); 10232 changedInstallPermission = true; 10233 } 10234 10235 // If the permission is not to be promoted to runtime we ignore it and 10236 // also its other flags as they are not applicable to install permissions. 10237 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10238 for (int userId : currentUserIds) { 10239 if (permissionsState.grantRuntimePermission(bp, userId) != 10240 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10241 // Transfer the permission flags. 10242 permissionsState.updatePermissionFlags(bp, userId, 10243 flags, flags); 10244 // If we granted the permission, we have to write. 10245 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10246 changedRuntimePermissionUserIds, userId); 10247 } 10248 } 10249 } 10250 } break; 10251 10252 default: { 10253 if (packageOfInterest == null 10254 || packageOfInterest.equals(pkg.packageName)) { 10255 Slog.w(TAG, "Not granting permission " + perm 10256 + " to package " + pkg.packageName 10257 + " because it was previously installed without"); 10258 } 10259 } break; 10260 } 10261 } else { 10262 if (permissionsState.revokeInstallPermission(bp) != 10263 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10264 // Also drop the permission flags. 10265 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10266 PackageManager.MASK_PERMISSION_FLAGS, 0); 10267 changedInstallPermission = true; 10268 Slog.i(TAG, "Un-granting permission " + perm 10269 + " from package " + pkg.packageName 10270 + " (protectionLevel=" + bp.protectionLevel 10271 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10272 + ")"); 10273 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10274 // Don't print warning for app op permissions, since it is fine for them 10275 // not to be granted, there is a UI for the user to decide. 10276 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10277 Slog.w(TAG, "Not granting permission " + perm 10278 + " to package " + pkg.packageName 10279 + " (protectionLevel=" + bp.protectionLevel 10280 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10281 + ")"); 10282 } 10283 } 10284 } 10285 } 10286 10287 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10288 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10289 // This is the first that we have heard about this package, so the 10290 // permissions we have now selected are fixed until explicitly 10291 // changed. 10292 ps.installPermissionsFixed = true; 10293 } 10294 10295 // Persist the runtime permissions state for users with changes. If permissions 10296 // were revoked because no app in the shared user declares them we have to 10297 // write synchronously to avoid losing runtime permissions state. 10298 for (int userId : changedRuntimePermissionUserIds) { 10299 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10300 } 10301 } 10302 10303 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10304 boolean allowed = false; 10305 final int NP = PackageParser.NEW_PERMISSIONS.length; 10306 for (int ip=0; ip<NP; ip++) { 10307 final PackageParser.NewPermissionInfo npi 10308 = PackageParser.NEW_PERMISSIONS[ip]; 10309 if (npi.name.equals(perm) 10310 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10311 allowed = true; 10312 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10313 + pkg.packageName); 10314 break; 10315 } 10316 } 10317 return allowed; 10318 } 10319 10320 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10321 BasePermission bp, PermissionsState origPermissions) { 10322 boolean allowed; 10323 allowed = (compareSignatures( 10324 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10325 == PackageManager.SIGNATURE_MATCH) 10326 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10327 == PackageManager.SIGNATURE_MATCH); 10328 if (!allowed && (bp.protectionLevel 10329 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10330 if (isSystemApp(pkg)) { 10331 // For updated system applications, a system permission 10332 // is granted only if it had been defined by the original application. 10333 if (pkg.isUpdatedSystemApp()) { 10334 final PackageSetting sysPs = mSettings 10335 .getDisabledSystemPkgLPr(pkg.packageName); 10336 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10337 // If the original was granted this permission, we take 10338 // that grant decision as read and propagate it to the 10339 // update. 10340 if (sysPs.isPrivileged()) { 10341 allowed = true; 10342 } 10343 } else { 10344 // The system apk may have been updated with an older 10345 // version of the one on the data partition, but which 10346 // granted a new system permission that it didn't have 10347 // before. In this case we do want to allow the app to 10348 // now get the new permission if the ancestral apk is 10349 // privileged to get it. 10350 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10351 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10352 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10353 allowed = true; 10354 break; 10355 } 10356 } 10357 } 10358 // Also if a privileged parent package on the system image or any of 10359 // its children requested a privileged permission, the updated child 10360 // packages can also get the permission. 10361 if (pkg.parentPackage != null) { 10362 final PackageSetting disabledSysParentPs = mSettings 10363 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10364 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10365 && disabledSysParentPs.isPrivileged()) { 10366 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10367 allowed = true; 10368 } else if (disabledSysParentPs.pkg.childPackages != null) { 10369 final int count = disabledSysParentPs.pkg.childPackages.size(); 10370 for (int i = 0; i < count; i++) { 10371 PackageParser.Package disabledSysChildPkg = 10372 disabledSysParentPs.pkg.childPackages.get(i); 10373 if (isPackageRequestingPermission(disabledSysChildPkg, 10374 perm)) { 10375 allowed = true; 10376 break; 10377 } 10378 } 10379 } 10380 } 10381 } 10382 } 10383 } else { 10384 allowed = isPrivilegedApp(pkg); 10385 } 10386 } 10387 } 10388 if (!allowed) { 10389 if (!allowed && (bp.protectionLevel 10390 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10391 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10392 // If this was a previously normal/dangerous permission that got moved 10393 // to a system permission as part of the runtime permission redesign, then 10394 // we still want to blindly grant it to old apps. 10395 allowed = true; 10396 } 10397 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10398 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10399 // If this permission is to be granted to the system installer and 10400 // this app is an installer, then it gets the permission. 10401 allowed = true; 10402 } 10403 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10404 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10405 // If this permission is to be granted to the system verifier and 10406 // this app is a verifier, then it gets the permission. 10407 allowed = true; 10408 } 10409 if (!allowed && (bp.protectionLevel 10410 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10411 && isSystemApp(pkg)) { 10412 // Any pre-installed system app is allowed to get this permission. 10413 allowed = true; 10414 } 10415 if (!allowed && (bp.protectionLevel 10416 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10417 // For development permissions, a development permission 10418 // is granted only if it was already granted. 10419 allowed = origPermissions.hasInstallPermission(perm); 10420 } 10421 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10422 && pkg.packageName.equals(mSetupWizardPackage)) { 10423 // If this permission is to be granted to the system setup wizard and 10424 // this app is a setup wizard, then it gets the permission. 10425 allowed = true; 10426 } 10427 } 10428 return allowed; 10429 } 10430 10431 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10432 final int permCount = pkg.requestedPermissions.size(); 10433 for (int j = 0; j < permCount; j++) { 10434 String requestedPermission = pkg.requestedPermissions.get(j); 10435 if (permission.equals(requestedPermission)) { 10436 return true; 10437 } 10438 } 10439 return false; 10440 } 10441 10442 final class ActivityIntentResolver 10443 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10444 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10445 boolean defaultOnly, int userId) { 10446 if (!sUserManager.exists(userId)) return null; 10447 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10448 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10449 } 10450 10451 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10452 int userId) { 10453 if (!sUserManager.exists(userId)) return null; 10454 mFlags = flags; 10455 return super.queryIntent(intent, resolvedType, 10456 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10457 } 10458 10459 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10460 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10461 if (!sUserManager.exists(userId)) return null; 10462 if (packageActivities == null) { 10463 return null; 10464 } 10465 mFlags = flags; 10466 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10467 final int N = packageActivities.size(); 10468 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10469 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10470 10471 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10472 for (int i = 0; i < N; ++i) { 10473 intentFilters = packageActivities.get(i).intents; 10474 if (intentFilters != null && intentFilters.size() > 0) { 10475 PackageParser.ActivityIntentInfo[] array = 10476 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10477 intentFilters.toArray(array); 10478 listCut.add(array); 10479 } 10480 } 10481 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10482 } 10483 10484 /** 10485 * Finds a privileged activity that matches the specified activity names. 10486 */ 10487 private PackageParser.Activity findMatchingActivity( 10488 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10489 for (PackageParser.Activity sysActivity : activityList) { 10490 if (sysActivity.info.name.equals(activityInfo.name)) { 10491 return sysActivity; 10492 } 10493 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10494 return sysActivity; 10495 } 10496 if (sysActivity.info.targetActivity != null) { 10497 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10498 return sysActivity; 10499 } 10500 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10501 return sysActivity; 10502 } 10503 } 10504 } 10505 return null; 10506 } 10507 10508 public class IterGenerator<E> { 10509 public Iterator<E> generate(ActivityIntentInfo info) { 10510 return null; 10511 } 10512 } 10513 10514 public class ActionIterGenerator extends IterGenerator<String> { 10515 @Override 10516 public Iterator<String> generate(ActivityIntentInfo info) { 10517 return info.actionsIterator(); 10518 } 10519 } 10520 10521 public class CategoriesIterGenerator extends IterGenerator<String> { 10522 @Override 10523 public Iterator<String> generate(ActivityIntentInfo info) { 10524 return info.categoriesIterator(); 10525 } 10526 } 10527 10528 public class SchemesIterGenerator extends IterGenerator<String> { 10529 @Override 10530 public Iterator<String> generate(ActivityIntentInfo info) { 10531 return info.schemesIterator(); 10532 } 10533 } 10534 10535 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10536 @Override 10537 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10538 return info.authoritiesIterator(); 10539 } 10540 } 10541 10542 /** 10543 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10544 * MODIFIED. Do not pass in a list that should not be changed. 10545 */ 10546 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10547 IterGenerator<T> generator, Iterator<T> searchIterator) { 10548 // loop through the set of actions; every one must be found in the intent filter 10549 while (searchIterator.hasNext()) { 10550 // we must have at least one filter in the list to consider a match 10551 if (intentList.size() == 0) { 10552 break; 10553 } 10554 10555 final T searchAction = searchIterator.next(); 10556 10557 // loop through the set of intent filters 10558 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10559 while (intentIter.hasNext()) { 10560 final ActivityIntentInfo intentInfo = intentIter.next(); 10561 boolean selectionFound = false; 10562 10563 // loop through the intent filter's selection criteria; at least one 10564 // of them must match the searched criteria 10565 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10566 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10567 final T intentSelection = intentSelectionIter.next(); 10568 if (intentSelection != null && intentSelection.equals(searchAction)) { 10569 selectionFound = true; 10570 break; 10571 } 10572 } 10573 10574 // the selection criteria wasn't found in this filter's set; this filter 10575 // is not a potential match 10576 if (!selectionFound) { 10577 intentIter.remove(); 10578 } 10579 } 10580 } 10581 } 10582 10583 private boolean isProtectedAction(ActivityIntentInfo filter) { 10584 final Iterator<String> actionsIter = filter.actionsIterator(); 10585 while (actionsIter != null && actionsIter.hasNext()) { 10586 final String filterAction = actionsIter.next(); 10587 if (PROTECTED_ACTIONS.contains(filterAction)) { 10588 return true; 10589 } 10590 } 10591 return false; 10592 } 10593 10594 /** 10595 * Adjusts the priority of the given intent filter according to policy. 10596 * <p> 10597 * <ul> 10598 * <li>The priority for non privileged applications is capped to '0'</li> 10599 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10600 * <li>The priority for unbundled updates to privileged applications is capped to the 10601 * priority defined on the system partition</li> 10602 * </ul> 10603 * <p> 10604 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10605 * allowed to obtain any priority on any action. 10606 */ 10607 private void adjustPriority( 10608 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10609 // nothing to do; priority is fine as-is 10610 if (intent.getPriority() <= 0) { 10611 return; 10612 } 10613 10614 final ActivityInfo activityInfo = intent.activity.info; 10615 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10616 10617 final boolean privilegedApp = 10618 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10619 if (!privilegedApp) { 10620 // non-privileged applications can never define a priority >0 10621 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10622 + " package: " + applicationInfo.packageName 10623 + " activity: " + intent.activity.className 10624 + " origPrio: " + intent.getPriority()); 10625 intent.setPriority(0); 10626 return; 10627 } 10628 10629 if (systemActivities == null) { 10630 // the system package is not disabled; we're parsing the system partition 10631 if (isProtectedAction(intent)) { 10632 if (mDeferProtectedFilters) { 10633 // We can't deal with these just yet. No component should ever obtain a 10634 // >0 priority for a protected actions, with ONE exception -- the setup 10635 // wizard. The setup wizard, however, cannot be known until we're able to 10636 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10637 // until all intent filters have been processed. Chicken, meet egg. 10638 // Let the filter temporarily have a high priority and rectify the 10639 // priorities after all system packages have been scanned. 10640 mProtectedFilters.add(intent); 10641 if (DEBUG_FILTERS) { 10642 Slog.i(TAG, "Protected action; save for later;" 10643 + " package: " + applicationInfo.packageName 10644 + " activity: " + intent.activity.className 10645 + " origPrio: " + intent.getPriority()); 10646 } 10647 return; 10648 } else { 10649 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10650 Slog.i(TAG, "No setup wizard;" 10651 + " All protected intents capped to priority 0"); 10652 } 10653 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10654 if (DEBUG_FILTERS) { 10655 Slog.i(TAG, "Found setup wizard;" 10656 + " allow priority " + intent.getPriority() + ";" 10657 + " package: " + intent.activity.info.packageName 10658 + " activity: " + intent.activity.className 10659 + " priority: " + intent.getPriority()); 10660 } 10661 // setup wizard gets whatever it wants 10662 return; 10663 } 10664 Slog.w(TAG, "Protected action; cap priority to 0;" 10665 + " package: " + intent.activity.info.packageName 10666 + " activity: " + intent.activity.className 10667 + " origPrio: " + intent.getPriority()); 10668 intent.setPriority(0); 10669 return; 10670 } 10671 } 10672 // privileged apps on the system image get whatever priority they request 10673 return; 10674 } 10675 10676 // privileged app unbundled update ... try to find the same activity 10677 final PackageParser.Activity foundActivity = 10678 findMatchingActivity(systemActivities, activityInfo); 10679 if (foundActivity == null) { 10680 // this is a new activity; it cannot obtain >0 priority 10681 if (DEBUG_FILTERS) { 10682 Slog.i(TAG, "New activity; cap priority to 0;" 10683 + " package: " + applicationInfo.packageName 10684 + " activity: " + intent.activity.className 10685 + " origPrio: " + intent.getPriority()); 10686 } 10687 intent.setPriority(0); 10688 return; 10689 } 10690 10691 // found activity, now check for filter equivalence 10692 10693 // a shallow copy is enough; we modify the list, not its contents 10694 final List<ActivityIntentInfo> intentListCopy = 10695 new ArrayList<>(foundActivity.intents); 10696 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10697 10698 // find matching action subsets 10699 final Iterator<String> actionsIterator = intent.actionsIterator(); 10700 if (actionsIterator != null) { 10701 getIntentListSubset( 10702 intentListCopy, new ActionIterGenerator(), actionsIterator); 10703 if (intentListCopy.size() == 0) { 10704 // no more intents to match; we're not equivalent 10705 if (DEBUG_FILTERS) { 10706 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10707 + " package: " + applicationInfo.packageName 10708 + " activity: " + intent.activity.className 10709 + " origPrio: " + intent.getPriority()); 10710 } 10711 intent.setPriority(0); 10712 return; 10713 } 10714 } 10715 10716 // find matching category subsets 10717 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10718 if (categoriesIterator != null) { 10719 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10720 categoriesIterator); 10721 if (intentListCopy.size() == 0) { 10722 // no more intents to match; we're not equivalent 10723 if (DEBUG_FILTERS) { 10724 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10725 + " package: " + applicationInfo.packageName 10726 + " activity: " + intent.activity.className 10727 + " origPrio: " + intent.getPriority()); 10728 } 10729 intent.setPriority(0); 10730 return; 10731 } 10732 } 10733 10734 // find matching schemes subsets 10735 final Iterator<String> schemesIterator = intent.schemesIterator(); 10736 if (schemesIterator != null) { 10737 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10738 schemesIterator); 10739 if (intentListCopy.size() == 0) { 10740 // no more intents to match; we're not equivalent 10741 if (DEBUG_FILTERS) { 10742 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10743 + " package: " + applicationInfo.packageName 10744 + " activity: " + intent.activity.className 10745 + " origPrio: " + intent.getPriority()); 10746 } 10747 intent.setPriority(0); 10748 return; 10749 } 10750 } 10751 10752 // find matching authorities subsets 10753 final Iterator<IntentFilter.AuthorityEntry> 10754 authoritiesIterator = intent.authoritiesIterator(); 10755 if (authoritiesIterator != null) { 10756 getIntentListSubset(intentListCopy, 10757 new AuthoritiesIterGenerator(), 10758 authoritiesIterator); 10759 if (intentListCopy.size() == 0) { 10760 // no more intents to match; we're not equivalent 10761 if (DEBUG_FILTERS) { 10762 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10763 + " package: " + applicationInfo.packageName 10764 + " activity: " + intent.activity.className 10765 + " origPrio: " + intent.getPriority()); 10766 } 10767 intent.setPriority(0); 10768 return; 10769 } 10770 } 10771 10772 // we found matching filter(s); app gets the max priority of all intents 10773 int cappedPriority = 0; 10774 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10775 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10776 } 10777 if (intent.getPriority() > cappedPriority) { 10778 if (DEBUG_FILTERS) { 10779 Slog.i(TAG, "Found matching filter(s);" 10780 + " cap priority to " + cappedPriority + ";" 10781 + " package: " + applicationInfo.packageName 10782 + " activity: " + intent.activity.className 10783 + " origPrio: " + intent.getPriority()); 10784 } 10785 intent.setPriority(cappedPriority); 10786 return; 10787 } 10788 // all this for nothing; the requested priority was <= what was on the system 10789 } 10790 10791 public final void addActivity(PackageParser.Activity a, String type) { 10792 mActivities.put(a.getComponentName(), a); 10793 if (DEBUG_SHOW_INFO) 10794 Log.v( 10795 TAG, " " + type + " " + 10796 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10797 if (DEBUG_SHOW_INFO) 10798 Log.v(TAG, " Class=" + a.info.name); 10799 final int NI = a.intents.size(); 10800 for (int j=0; j<NI; j++) { 10801 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10802 if ("activity".equals(type)) { 10803 final PackageSetting ps = 10804 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10805 final List<PackageParser.Activity> systemActivities = 10806 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10807 adjustPriority(systemActivities, intent); 10808 } 10809 if (DEBUG_SHOW_INFO) { 10810 Log.v(TAG, " IntentFilter:"); 10811 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10812 } 10813 if (!intent.debugCheck()) { 10814 Log.w(TAG, "==> For Activity " + a.info.name); 10815 } 10816 addFilter(intent); 10817 } 10818 } 10819 10820 public final void removeActivity(PackageParser.Activity a, String type) { 10821 mActivities.remove(a.getComponentName()); 10822 if (DEBUG_SHOW_INFO) { 10823 Log.v(TAG, " " + type + " " 10824 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10825 : a.info.name) + ":"); 10826 Log.v(TAG, " Class=" + a.info.name); 10827 } 10828 final int NI = a.intents.size(); 10829 for (int j=0; j<NI; j++) { 10830 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10831 if (DEBUG_SHOW_INFO) { 10832 Log.v(TAG, " IntentFilter:"); 10833 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10834 } 10835 removeFilter(intent); 10836 } 10837 } 10838 10839 @Override 10840 protected boolean allowFilterResult( 10841 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10842 ActivityInfo filterAi = filter.activity.info; 10843 for (int i=dest.size()-1; i>=0; i--) { 10844 ActivityInfo destAi = dest.get(i).activityInfo; 10845 if (destAi.name == filterAi.name 10846 && destAi.packageName == filterAi.packageName) { 10847 return false; 10848 } 10849 } 10850 return true; 10851 } 10852 10853 @Override 10854 protected ActivityIntentInfo[] newArray(int size) { 10855 return new ActivityIntentInfo[size]; 10856 } 10857 10858 @Override 10859 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10860 if (!sUserManager.exists(userId)) return true; 10861 PackageParser.Package p = filter.activity.owner; 10862 if (p != null) { 10863 PackageSetting ps = (PackageSetting)p.mExtras; 10864 if (ps != null) { 10865 // System apps are never considered stopped for purposes of 10866 // filtering, because there may be no way for the user to 10867 // actually re-launch them. 10868 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10869 && ps.getStopped(userId); 10870 } 10871 } 10872 return false; 10873 } 10874 10875 @Override 10876 protected boolean isPackageForFilter(String packageName, 10877 PackageParser.ActivityIntentInfo info) { 10878 return packageName.equals(info.activity.owner.packageName); 10879 } 10880 10881 @Override 10882 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10883 int match, int userId) { 10884 if (!sUserManager.exists(userId)) return null; 10885 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10886 return null; 10887 } 10888 final PackageParser.Activity activity = info.activity; 10889 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10890 if (ps == null) { 10891 return null; 10892 } 10893 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10894 ps.readUserState(userId), userId); 10895 if (ai == null) { 10896 return null; 10897 } 10898 final ResolveInfo res = new ResolveInfo(); 10899 res.activityInfo = ai; 10900 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10901 res.filter = info; 10902 } 10903 if (info != null) { 10904 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10905 } 10906 res.priority = info.getPriority(); 10907 res.preferredOrder = activity.owner.mPreferredOrder; 10908 //System.out.println("Result: " + res.activityInfo.className + 10909 // " = " + res.priority); 10910 res.match = match; 10911 res.isDefault = info.hasDefault; 10912 res.labelRes = info.labelRes; 10913 res.nonLocalizedLabel = info.nonLocalizedLabel; 10914 if (userNeedsBadging(userId)) { 10915 res.noResourceId = true; 10916 } else { 10917 res.icon = info.icon; 10918 } 10919 res.iconResourceId = info.icon; 10920 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10921 return res; 10922 } 10923 10924 @Override 10925 protected void sortResults(List<ResolveInfo> results) { 10926 Collections.sort(results, mResolvePrioritySorter); 10927 } 10928 10929 @Override 10930 protected void dumpFilter(PrintWriter out, String prefix, 10931 PackageParser.ActivityIntentInfo filter) { 10932 out.print(prefix); out.print( 10933 Integer.toHexString(System.identityHashCode(filter.activity))); 10934 out.print(' '); 10935 filter.activity.printComponentShortName(out); 10936 out.print(" filter "); 10937 out.println(Integer.toHexString(System.identityHashCode(filter))); 10938 } 10939 10940 @Override 10941 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10942 return filter.activity; 10943 } 10944 10945 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10946 PackageParser.Activity activity = (PackageParser.Activity)label; 10947 out.print(prefix); out.print( 10948 Integer.toHexString(System.identityHashCode(activity))); 10949 out.print(' '); 10950 activity.printComponentShortName(out); 10951 if (count > 1) { 10952 out.print(" ("); out.print(count); out.print(" filters)"); 10953 } 10954 out.println(); 10955 } 10956 10957 // Keys are String (activity class name), values are Activity. 10958 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10959 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10960 private int mFlags; 10961 } 10962 10963 private final class ServiceIntentResolver 10964 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10965 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10966 boolean defaultOnly, int userId) { 10967 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10968 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10969 } 10970 10971 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10972 int userId) { 10973 if (!sUserManager.exists(userId)) return null; 10974 mFlags = flags; 10975 return super.queryIntent(intent, resolvedType, 10976 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10977 } 10978 10979 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10980 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10981 if (!sUserManager.exists(userId)) return null; 10982 if (packageServices == null) { 10983 return null; 10984 } 10985 mFlags = flags; 10986 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10987 final int N = packageServices.size(); 10988 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10989 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10990 10991 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10992 for (int i = 0; i < N; ++i) { 10993 intentFilters = packageServices.get(i).intents; 10994 if (intentFilters != null && intentFilters.size() > 0) { 10995 PackageParser.ServiceIntentInfo[] array = 10996 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10997 intentFilters.toArray(array); 10998 listCut.add(array); 10999 } 11000 } 11001 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11002 } 11003 11004 public final void addService(PackageParser.Service s) { 11005 mServices.put(s.getComponentName(), s); 11006 if (DEBUG_SHOW_INFO) { 11007 Log.v(TAG, " " 11008 + (s.info.nonLocalizedLabel != null 11009 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11010 Log.v(TAG, " Class=" + s.info.name); 11011 } 11012 final int NI = s.intents.size(); 11013 int j; 11014 for (j=0; j<NI; j++) { 11015 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11016 if (DEBUG_SHOW_INFO) { 11017 Log.v(TAG, " IntentFilter:"); 11018 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11019 } 11020 if (!intent.debugCheck()) { 11021 Log.w(TAG, "==> For Service " + s.info.name); 11022 } 11023 addFilter(intent); 11024 } 11025 } 11026 11027 public final void removeService(PackageParser.Service s) { 11028 mServices.remove(s.getComponentName()); 11029 if (DEBUG_SHOW_INFO) { 11030 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11031 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11032 Log.v(TAG, " Class=" + s.info.name); 11033 } 11034 final int NI = s.intents.size(); 11035 int j; 11036 for (j=0; j<NI; j++) { 11037 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11038 if (DEBUG_SHOW_INFO) { 11039 Log.v(TAG, " IntentFilter:"); 11040 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11041 } 11042 removeFilter(intent); 11043 } 11044 } 11045 11046 @Override 11047 protected boolean allowFilterResult( 11048 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11049 ServiceInfo filterSi = filter.service.info; 11050 for (int i=dest.size()-1; i>=0; i--) { 11051 ServiceInfo destAi = dest.get(i).serviceInfo; 11052 if (destAi.name == filterSi.name 11053 && destAi.packageName == filterSi.packageName) { 11054 return false; 11055 } 11056 } 11057 return true; 11058 } 11059 11060 @Override 11061 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11062 return new PackageParser.ServiceIntentInfo[size]; 11063 } 11064 11065 @Override 11066 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11067 if (!sUserManager.exists(userId)) return true; 11068 PackageParser.Package p = filter.service.owner; 11069 if (p != null) { 11070 PackageSetting ps = (PackageSetting)p.mExtras; 11071 if (ps != null) { 11072 // System apps are never considered stopped for purposes of 11073 // filtering, because there may be no way for the user to 11074 // actually re-launch them. 11075 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11076 && ps.getStopped(userId); 11077 } 11078 } 11079 return false; 11080 } 11081 11082 @Override 11083 protected boolean isPackageForFilter(String packageName, 11084 PackageParser.ServiceIntentInfo info) { 11085 return packageName.equals(info.service.owner.packageName); 11086 } 11087 11088 @Override 11089 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11090 int match, int userId) { 11091 if (!sUserManager.exists(userId)) return null; 11092 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11093 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11094 return null; 11095 } 11096 final PackageParser.Service service = info.service; 11097 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11098 if (ps == null) { 11099 return null; 11100 } 11101 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11102 ps.readUserState(userId), userId); 11103 if (si == null) { 11104 return null; 11105 } 11106 final ResolveInfo res = new ResolveInfo(); 11107 res.serviceInfo = si; 11108 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11109 res.filter = filter; 11110 } 11111 res.priority = info.getPriority(); 11112 res.preferredOrder = service.owner.mPreferredOrder; 11113 res.match = match; 11114 res.isDefault = info.hasDefault; 11115 res.labelRes = info.labelRes; 11116 res.nonLocalizedLabel = info.nonLocalizedLabel; 11117 res.icon = info.icon; 11118 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11119 return res; 11120 } 11121 11122 @Override 11123 protected void sortResults(List<ResolveInfo> results) { 11124 Collections.sort(results, mResolvePrioritySorter); 11125 } 11126 11127 @Override 11128 protected void dumpFilter(PrintWriter out, String prefix, 11129 PackageParser.ServiceIntentInfo filter) { 11130 out.print(prefix); out.print( 11131 Integer.toHexString(System.identityHashCode(filter.service))); 11132 out.print(' '); 11133 filter.service.printComponentShortName(out); 11134 out.print(" filter "); 11135 out.println(Integer.toHexString(System.identityHashCode(filter))); 11136 } 11137 11138 @Override 11139 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11140 return filter.service; 11141 } 11142 11143 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11144 PackageParser.Service service = (PackageParser.Service)label; 11145 out.print(prefix); out.print( 11146 Integer.toHexString(System.identityHashCode(service))); 11147 out.print(' '); 11148 service.printComponentShortName(out); 11149 if (count > 1) { 11150 out.print(" ("); out.print(count); out.print(" filters)"); 11151 } 11152 out.println(); 11153 } 11154 11155// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11156// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11157// final List<ResolveInfo> retList = Lists.newArrayList(); 11158// while (i.hasNext()) { 11159// final ResolveInfo resolveInfo = (ResolveInfo) i; 11160// if (isEnabledLP(resolveInfo.serviceInfo)) { 11161// retList.add(resolveInfo); 11162// } 11163// } 11164// return retList; 11165// } 11166 11167 // Keys are String (activity class name), values are Activity. 11168 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11169 = new ArrayMap<ComponentName, PackageParser.Service>(); 11170 private int mFlags; 11171 }; 11172 11173 private final class ProviderIntentResolver 11174 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11175 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11176 boolean defaultOnly, int userId) { 11177 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11178 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11179 } 11180 11181 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11182 int userId) { 11183 if (!sUserManager.exists(userId)) 11184 return null; 11185 mFlags = flags; 11186 return super.queryIntent(intent, resolvedType, 11187 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11188 } 11189 11190 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11191 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11192 if (!sUserManager.exists(userId)) 11193 return null; 11194 if (packageProviders == null) { 11195 return null; 11196 } 11197 mFlags = flags; 11198 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11199 final int N = packageProviders.size(); 11200 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11201 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11202 11203 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11204 for (int i = 0; i < N; ++i) { 11205 intentFilters = packageProviders.get(i).intents; 11206 if (intentFilters != null && intentFilters.size() > 0) { 11207 PackageParser.ProviderIntentInfo[] array = 11208 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11209 intentFilters.toArray(array); 11210 listCut.add(array); 11211 } 11212 } 11213 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11214 } 11215 11216 public final void addProvider(PackageParser.Provider p) { 11217 if (mProviders.containsKey(p.getComponentName())) { 11218 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11219 return; 11220 } 11221 11222 mProviders.put(p.getComponentName(), p); 11223 if (DEBUG_SHOW_INFO) { 11224 Log.v(TAG, " " 11225 + (p.info.nonLocalizedLabel != null 11226 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11227 Log.v(TAG, " Class=" + p.info.name); 11228 } 11229 final int NI = p.intents.size(); 11230 int j; 11231 for (j = 0; j < NI; j++) { 11232 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11233 if (DEBUG_SHOW_INFO) { 11234 Log.v(TAG, " IntentFilter:"); 11235 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11236 } 11237 if (!intent.debugCheck()) { 11238 Log.w(TAG, "==> For Provider " + p.info.name); 11239 } 11240 addFilter(intent); 11241 } 11242 } 11243 11244 public final void removeProvider(PackageParser.Provider p) { 11245 mProviders.remove(p.getComponentName()); 11246 if (DEBUG_SHOW_INFO) { 11247 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11248 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11249 Log.v(TAG, " Class=" + p.info.name); 11250 } 11251 final int NI = p.intents.size(); 11252 int j; 11253 for (j = 0; j < NI; j++) { 11254 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11255 if (DEBUG_SHOW_INFO) { 11256 Log.v(TAG, " IntentFilter:"); 11257 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11258 } 11259 removeFilter(intent); 11260 } 11261 } 11262 11263 @Override 11264 protected boolean allowFilterResult( 11265 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11266 ProviderInfo filterPi = filter.provider.info; 11267 for (int i = dest.size() - 1; i >= 0; i--) { 11268 ProviderInfo destPi = dest.get(i).providerInfo; 11269 if (destPi.name == filterPi.name 11270 && destPi.packageName == filterPi.packageName) { 11271 return false; 11272 } 11273 } 11274 return true; 11275 } 11276 11277 @Override 11278 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11279 return new PackageParser.ProviderIntentInfo[size]; 11280 } 11281 11282 @Override 11283 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11284 if (!sUserManager.exists(userId)) 11285 return true; 11286 PackageParser.Package p = filter.provider.owner; 11287 if (p != null) { 11288 PackageSetting ps = (PackageSetting) p.mExtras; 11289 if (ps != null) { 11290 // System apps are never considered stopped for purposes of 11291 // filtering, because there may be no way for the user to 11292 // actually re-launch them. 11293 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11294 && ps.getStopped(userId); 11295 } 11296 } 11297 return false; 11298 } 11299 11300 @Override 11301 protected boolean isPackageForFilter(String packageName, 11302 PackageParser.ProviderIntentInfo info) { 11303 return packageName.equals(info.provider.owner.packageName); 11304 } 11305 11306 @Override 11307 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11308 int match, int userId) { 11309 if (!sUserManager.exists(userId)) 11310 return null; 11311 final PackageParser.ProviderIntentInfo info = filter; 11312 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11313 return null; 11314 } 11315 final PackageParser.Provider provider = info.provider; 11316 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11317 if (ps == null) { 11318 return null; 11319 } 11320 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11321 ps.readUserState(userId), userId); 11322 if (pi == null) { 11323 return null; 11324 } 11325 final ResolveInfo res = new ResolveInfo(); 11326 res.providerInfo = pi; 11327 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11328 res.filter = filter; 11329 } 11330 res.priority = info.getPriority(); 11331 res.preferredOrder = provider.owner.mPreferredOrder; 11332 res.match = match; 11333 res.isDefault = info.hasDefault; 11334 res.labelRes = info.labelRes; 11335 res.nonLocalizedLabel = info.nonLocalizedLabel; 11336 res.icon = info.icon; 11337 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11338 return res; 11339 } 11340 11341 @Override 11342 protected void sortResults(List<ResolveInfo> results) { 11343 Collections.sort(results, mResolvePrioritySorter); 11344 } 11345 11346 @Override 11347 protected void dumpFilter(PrintWriter out, String prefix, 11348 PackageParser.ProviderIntentInfo filter) { 11349 out.print(prefix); 11350 out.print( 11351 Integer.toHexString(System.identityHashCode(filter.provider))); 11352 out.print(' '); 11353 filter.provider.printComponentShortName(out); 11354 out.print(" filter "); 11355 out.println(Integer.toHexString(System.identityHashCode(filter))); 11356 } 11357 11358 @Override 11359 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11360 return filter.provider; 11361 } 11362 11363 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11364 PackageParser.Provider provider = (PackageParser.Provider)label; 11365 out.print(prefix); out.print( 11366 Integer.toHexString(System.identityHashCode(provider))); 11367 out.print(' '); 11368 provider.printComponentShortName(out); 11369 if (count > 1) { 11370 out.print(" ("); out.print(count); out.print(" filters)"); 11371 } 11372 out.println(); 11373 } 11374 11375 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11376 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11377 private int mFlags; 11378 } 11379 11380 private static final class EphemeralIntentResolver 11381 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11382 /** 11383 * The result that has the highest defined order. Ordering applies on a 11384 * per-package basis. Mapping is from package name to Pair of order and 11385 * EphemeralResolveInfo. 11386 * <p> 11387 * NOTE: This is implemented as a field variable for convenience and efficiency. 11388 * By having a field variable, we're able to track filter ordering as soon as 11389 * a non-zero order is defined. Otherwise, multiple loops across the result set 11390 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11391 * this needs to be contained entirely within {@link #filterResults()}. 11392 */ 11393 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11394 11395 @Override 11396 protected EphemeralResolveIntentInfo[] newArray(int size) { 11397 return new EphemeralResolveIntentInfo[size]; 11398 } 11399 11400 @Override 11401 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11402 return true; 11403 } 11404 11405 @Override 11406 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11407 int userId) { 11408 if (!sUserManager.exists(userId)) { 11409 return null; 11410 } 11411 final String packageName = info.getEphemeralResolveInfo().getPackageName(); 11412 final Integer order = info.getOrder(); 11413 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11414 mOrderResult.get(packageName); 11415 // ordering is enabled and this item's order isn't high enough 11416 if (lastOrderResult != null && lastOrderResult.first >= order) { 11417 return null; 11418 } 11419 final EphemeralResolveInfo res = info.getEphemeralResolveInfo(); 11420 if (order > 0) { 11421 // non-zero order, enable ordering 11422 mOrderResult.put(packageName, new Pair<>(order, res)); 11423 } 11424 return res; 11425 } 11426 11427 @Override 11428 protected void filterResults(List<EphemeralResolveInfo> results) { 11429 // only do work if ordering is enabled [most of the time it won't be] 11430 if (mOrderResult.size() == 0) { 11431 return; 11432 } 11433 int resultSize = results.size(); 11434 for (int i = 0; i < resultSize; i++) { 11435 final EphemeralResolveInfo info = results.get(i); 11436 final String packageName = info.getPackageName(); 11437 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11438 if (savedInfo == null) { 11439 // package doesn't having ordering 11440 continue; 11441 } 11442 if (savedInfo.second == info) { 11443 // circled back to the highest ordered item; remove from order list 11444 mOrderResult.remove(savedInfo); 11445 if (mOrderResult.size() == 0) { 11446 // no more ordered items 11447 break; 11448 } 11449 continue; 11450 } 11451 // item has a worse order, remove it from the result list 11452 results.remove(i); 11453 resultSize--; 11454 i--; 11455 } 11456 } 11457 } 11458 11459 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11460 new Comparator<ResolveInfo>() { 11461 public int compare(ResolveInfo r1, ResolveInfo r2) { 11462 int v1 = r1.priority; 11463 int v2 = r2.priority; 11464 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11465 if (v1 != v2) { 11466 return (v1 > v2) ? -1 : 1; 11467 } 11468 v1 = r1.preferredOrder; 11469 v2 = r2.preferredOrder; 11470 if (v1 != v2) { 11471 return (v1 > v2) ? -1 : 1; 11472 } 11473 if (r1.isDefault != r2.isDefault) { 11474 return r1.isDefault ? -1 : 1; 11475 } 11476 v1 = r1.match; 11477 v2 = r2.match; 11478 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11479 if (v1 != v2) { 11480 return (v1 > v2) ? -1 : 1; 11481 } 11482 if (r1.system != r2.system) { 11483 return r1.system ? -1 : 1; 11484 } 11485 if (r1.activityInfo != null) { 11486 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11487 } 11488 if (r1.serviceInfo != null) { 11489 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11490 } 11491 if (r1.providerInfo != null) { 11492 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11493 } 11494 return 0; 11495 } 11496 }; 11497 11498 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11499 new Comparator<ProviderInfo>() { 11500 public int compare(ProviderInfo p1, ProviderInfo p2) { 11501 final int v1 = p1.initOrder; 11502 final int v2 = p2.initOrder; 11503 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11504 } 11505 }; 11506 11507 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11508 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11509 final int[] userIds) { 11510 mHandler.post(new Runnable() { 11511 @Override 11512 public void run() { 11513 try { 11514 final IActivityManager am = ActivityManagerNative.getDefault(); 11515 if (am == null) return; 11516 final int[] resolvedUserIds; 11517 if (userIds == null) { 11518 resolvedUserIds = am.getRunningUserIds(); 11519 } else { 11520 resolvedUserIds = userIds; 11521 } 11522 for (int id : resolvedUserIds) { 11523 final Intent intent = new Intent(action, 11524 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11525 if (extras != null) { 11526 intent.putExtras(extras); 11527 } 11528 if (targetPkg != null) { 11529 intent.setPackage(targetPkg); 11530 } 11531 // Modify the UID when posting to other users 11532 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11533 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11534 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11535 intent.putExtra(Intent.EXTRA_UID, uid); 11536 } 11537 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11538 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11539 if (DEBUG_BROADCASTS) { 11540 RuntimeException here = new RuntimeException("here"); 11541 here.fillInStackTrace(); 11542 Slog.d(TAG, "Sending to user " + id + ": " 11543 + intent.toShortString(false, true, false, false) 11544 + " " + intent.getExtras(), here); 11545 } 11546 am.broadcastIntent(null, intent, null, finishedReceiver, 11547 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11548 null, finishedReceiver != null, false, id); 11549 } 11550 } catch (RemoteException ex) { 11551 } 11552 } 11553 }); 11554 } 11555 11556 /** 11557 * Check if the external storage media is available. This is true if there 11558 * is a mounted external storage medium or if the external storage is 11559 * emulated. 11560 */ 11561 private boolean isExternalMediaAvailable() { 11562 return mMediaMounted || Environment.isExternalStorageEmulated(); 11563 } 11564 11565 @Override 11566 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11567 // writer 11568 synchronized (mPackages) { 11569 if (!isExternalMediaAvailable()) { 11570 // If the external storage is no longer mounted at this point, 11571 // the caller may not have been able to delete all of this 11572 // packages files and can not delete any more. Bail. 11573 return null; 11574 } 11575 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11576 if (lastPackage != null) { 11577 pkgs.remove(lastPackage); 11578 } 11579 if (pkgs.size() > 0) { 11580 return pkgs.get(0); 11581 } 11582 } 11583 return null; 11584 } 11585 11586 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11587 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11588 userId, andCode ? 1 : 0, packageName); 11589 if (mSystemReady) { 11590 msg.sendToTarget(); 11591 } else { 11592 if (mPostSystemReadyMessages == null) { 11593 mPostSystemReadyMessages = new ArrayList<>(); 11594 } 11595 mPostSystemReadyMessages.add(msg); 11596 } 11597 } 11598 11599 void startCleaningPackages() { 11600 // reader 11601 if (!isExternalMediaAvailable()) { 11602 return; 11603 } 11604 synchronized (mPackages) { 11605 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11606 return; 11607 } 11608 } 11609 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11610 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11611 IActivityManager am = ActivityManagerNative.getDefault(); 11612 if (am != null) { 11613 try { 11614 am.startService(null, intent, null, mContext.getOpPackageName(), 11615 UserHandle.USER_SYSTEM); 11616 } catch (RemoteException e) { 11617 } 11618 } 11619 } 11620 11621 @Override 11622 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11623 int installFlags, String installerPackageName, int userId) { 11624 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11625 11626 final int callingUid = Binder.getCallingUid(); 11627 enforceCrossUserPermission(callingUid, userId, 11628 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11629 11630 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11631 try { 11632 if (observer != null) { 11633 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11634 } 11635 } catch (RemoteException re) { 11636 } 11637 return; 11638 } 11639 11640 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11641 installFlags |= PackageManager.INSTALL_FROM_ADB; 11642 11643 } else { 11644 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11645 // about installerPackageName. 11646 11647 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11648 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11649 } 11650 11651 UserHandle user; 11652 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11653 user = UserHandle.ALL; 11654 } else { 11655 user = new UserHandle(userId); 11656 } 11657 11658 // Only system components can circumvent runtime permissions when installing. 11659 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11660 && mContext.checkCallingOrSelfPermission(Manifest.permission 11661 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11662 throw new SecurityException("You need the " 11663 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11664 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11665 } 11666 11667 final File originFile = new File(originPath); 11668 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11669 11670 final Message msg = mHandler.obtainMessage(INIT_COPY); 11671 final VerificationInfo verificationInfo = new VerificationInfo( 11672 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11673 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11674 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11675 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11676 null /*certificates*/); 11677 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11678 msg.obj = params; 11679 11680 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11681 System.identityHashCode(msg.obj)); 11682 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11683 System.identityHashCode(msg.obj)); 11684 11685 mHandler.sendMessage(msg); 11686 } 11687 11688 void installStage(String packageName, File stagedDir, String stagedCid, 11689 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11690 String installerPackageName, int installerUid, UserHandle user, 11691 Certificate[][] certificates) { 11692 if (DEBUG_EPHEMERAL) { 11693 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11694 Slog.d(TAG, "Ephemeral install of " + packageName); 11695 } 11696 } 11697 final VerificationInfo verificationInfo = new VerificationInfo( 11698 sessionParams.originatingUri, sessionParams.referrerUri, 11699 sessionParams.originatingUid, installerUid); 11700 11701 final OriginInfo origin; 11702 if (stagedDir != null) { 11703 origin = OriginInfo.fromStagedFile(stagedDir); 11704 } else { 11705 origin = OriginInfo.fromStagedContainer(stagedCid); 11706 } 11707 11708 final Message msg = mHandler.obtainMessage(INIT_COPY); 11709 final InstallParams params = new InstallParams(origin, null, observer, 11710 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11711 verificationInfo, user, sessionParams.abiOverride, 11712 sessionParams.grantedRuntimePermissions, certificates); 11713 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11714 msg.obj = params; 11715 11716 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11717 System.identityHashCode(msg.obj)); 11718 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11719 System.identityHashCode(msg.obj)); 11720 11721 mHandler.sendMessage(msg); 11722 } 11723 11724 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11725 int userId) { 11726 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11727 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11728 } 11729 11730 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11731 int appId, int userId) { 11732 Bundle extras = new Bundle(1); 11733 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11734 11735 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11736 packageName, extras, 0, null, null, new int[] {userId}); 11737 try { 11738 IActivityManager am = ActivityManagerNative.getDefault(); 11739 if (isSystem && am.isUserRunning(userId, 0)) { 11740 // The just-installed/enabled app is bundled on the system, so presumed 11741 // to be able to run automatically without needing an explicit launch. 11742 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11743 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11744 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11745 .setPackage(packageName); 11746 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11747 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11748 } 11749 } catch (RemoteException e) { 11750 // shouldn't happen 11751 Slog.w(TAG, "Unable to bootstrap installed package", e); 11752 } 11753 } 11754 11755 @Override 11756 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11757 int userId) { 11758 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11759 PackageSetting pkgSetting; 11760 final int uid = Binder.getCallingUid(); 11761 enforceCrossUserPermission(uid, userId, 11762 true /* requireFullPermission */, true /* checkShell */, 11763 "setApplicationHiddenSetting for user " + userId); 11764 11765 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11766 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11767 return false; 11768 } 11769 11770 long callingId = Binder.clearCallingIdentity(); 11771 try { 11772 boolean sendAdded = false; 11773 boolean sendRemoved = false; 11774 // writer 11775 synchronized (mPackages) { 11776 pkgSetting = mSettings.mPackages.get(packageName); 11777 if (pkgSetting == null) { 11778 return false; 11779 } 11780 // Do not allow "android" is being disabled 11781 if ("android".equals(packageName)) { 11782 Slog.w(TAG, "Cannot hide package: android"); 11783 return false; 11784 } 11785 // Only allow protected packages to hide themselves. 11786 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11787 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11788 Slog.w(TAG, "Not hiding protected package: " + packageName); 11789 return false; 11790 } 11791 11792 if (pkgSetting.getHidden(userId) != hidden) { 11793 pkgSetting.setHidden(hidden, userId); 11794 mSettings.writePackageRestrictionsLPr(userId); 11795 if (hidden) { 11796 sendRemoved = true; 11797 } else { 11798 sendAdded = true; 11799 } 11800 } 11801 } 11802 if (sendAdded) { 11803 sendPackageAddedForUser(packageName, pkgSetting, userId); 11804 return true; 11805 } 11806 if (sendRemoved) { 11807 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11808 "hiding pkg"); 11809 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11810 return true; 11811 } 11812 } finally { 11813 Binder.restoreCallingIdentity(callingId); 11814 } 11815 return false; 11816 } 11817 11818 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11819 int userId) { 11820 final PackageRemovedInfo info = new PackageRemovedInfo(); 11821 info.removedPackage = packageName; 11822 info.removedUsers = new int[] {userId}; 11823 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11824 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11825 } 11826 11827 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11828 if (pkgList.length > 0) { 11829 Bundle extras = new Bundle(1); 11830 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11831 11832 sendPackageBroadcast( 11833 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11834 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11835 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11836 new int[] {userId}); 11837 } 11838 } 11839 11840 /** 11841 * Returns true if application is not found or there was an error. Otherwise it returns 11842 * the hidden state of the package for the given user. 11843 */ 11844 @Override 11845 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11846 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11847 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11848 true /* requireFullPermission */, false /* checkShell */, 11849 "getApplicationHidden for user " + userId); 11850 PackageSetting pkgSetting; 11851 long callingId = Binder.clearCallingIdentity(); 11852 try { 11853 // writer 11854 synchronized (mPackages) { 11855 pkgSetting = mSettings.mPackages.get(packageName); 11856 if (pkgSetting == null) { 11857 return true; 11858 } 11859 return pkgSetting.getHidden(userId); 11860 } 11861 } finally { 11862 Binder.restoreCallingIdentity(callingId); 11863 } 11864 } 11865 11866 /** 11867 * @hide 11868 */ 11869 @Override 11870 public int installExistingPackageAsUser(String packageName, int userId) { 11871 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11872 null); 11873 PackageSetting pkgSetting; 11874 final int uid = Binder.getCallingUid(); 11875 enforceCrossUserPermission(uid, userId, 11876 true /* requireFullPermission */, true /* checkShell */, 11877 "installExistingPackage for user " + userId); 11878 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11879 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11880 } 11881 11882 long callingId = Binder.clearCallingIdentity(); 11883 try { 11884 boolean installed = false; 11885 11886 // writer 11887 synchronized (mPackages) { 11888 pkgSetting = mSettings.mPackages.get(packageName); 11889 if (pkgSetting == null) { 11890 return PackageManager.INSTALL_FAILED_INVALID_URI; 11891 } 11892 if (!pkgSetting.getInstalled(userId)) { 11893 pkgSetting.setInstalled(true, userId); 11894 pkgSetting.setHidden(false, userId); 11895 mSettings.writePackageRestrictionsLPr(userId); 11896 installed = true; 11897 } 11898 } 11899 11900 if (installed) { 11901 if (pkgSetting.pkg != null) { 11902 synchronized (mInstallLock) { 11903 // We don't need to freeze for a brand new install 11904 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11905 } 11906 } 11907 sendPackageAddedForUser(packageName, pkgSetting, userId); 11908 } 11909 } finally { 11910 Binder.restoreCallingIdentity(callingId); 11911 } 11912 11913 return PackageManager.INSTALL_SUCCEEDED; 11914 } 11915 11916 boolean isUserRestricted(int userId, String restrictionKey) { 11917 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11918 if (restrictions.getBoolean(restrictionKey, false)) { 11919 Log.w(TAG, "User is restricted: " + restrictionKey); 11920 return true; 11921 } 11922 return false; 11923 } 11924 11925 @Override 11926 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11927 int userId) { 11928 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11929 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11930 true /* requireFullPermission */, true /* checkShell */, 11931 "setPackagesSuspended for user " + userId); 11932 11933 if (ArrayUtils.isEmpty(packageNames)) { 11934 return packageNames; 11935 } 11936 11937 // List of package names for whom the suspended state has changed. 11938 List<String> changedPackages = new ArrayList<>(packageNames.length); 11939 // List of package names for whom the suspended state is not set as requested in this 11940 // method. 11941 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11942 long callingId = Binder.clearCallingIdentity(); 11943 try { 11944 for (int i = 0; i < packageNames.length; i++) { 11945 String packageName = packageNames[i]; 11946 boolean changed = false; 11947 final int appId; 11948 synchronized (mPackages) { 11949 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11950 if (pkgSetting == null) { 11951 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11952 + "\". Skipping suspending/un-suspending."); 11953 unactionedPackages.add(packageName); 11954 continue; 11955 } 11956 appId = pkgSetting.appId; 11957 if (pkgSetting.getSuspended(userId) != suspended) { 11958 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11959 unactionedPackages.add(packageName); 11960 continue; 11961 } 11962 pkgSetting.setSuspended(suspended, userId); 11963 mSettings.writePackageRestrictionsLPr(userId); 11964 changed = true; 11965 changedPackages.add(packageName); 11966 } 11967 } 11968 11969 if (changed && suspended) { 11970 killApplication(packageName, UserHandle.getUid(userId, appId), 11971 "suspending package"); 11972 } 11973 } 11974 } finally { 11975 Binder.restoreCallingIdentity(callingId); 11976 } 11977 11978 if (!changedPackages.isEmpty()) { 11979 sendPackagesSuspendedForUser(changedPackages.toArray( 11980 new String[changedPackages.size()]), userId, suspended); 11981 } 11982 11983 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11984 } 11985 11986 @Override 11987 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11988 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11989 true /* requireFullPermission */, false /* checkShell */, 11990 "isPackageSuspendedForUser for user " + userId); 11991 synchronized (mPackages) { 11992 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11993 if (pkgSetting == null) { 11994 throw new IllegalArgumentException("Unknown target package: " + packageName); 11995 } 11996 return pkgSetting.getSuspended(userId); 11997 } 11998 } 11999 12000 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 12001 if (isPackageDeviceAdmin(packageName, userId)) { 12002 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12003 + "\": has an active device admin"); 12004 return false; 12005 } 12006 12007 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 12008 if (packageName.equals(activeLauncherPackageName)) { 12009 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12010 + "\": contains the active launcher"); 12011 return false; 12012 } 12013 12014 if (packageName.equals(mRequiredInstallerPackage)) { 12015 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12016 + "\": required for package installation"); 12017 return false; 12018 } 12019 12020 if (packageName.equals(mRequiredUninstallerPackage)) { 12021 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12022 + "\": required for package uninstallation"); 12023 return false; 12024 } 12025 12026 if (packageName.equals(mRequiredVerifierPackage)) { 12027 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12028 + "\": required for package verification"); 12029 return false; 12030 } 12031 12032 if (packageName.equals(getDefaultDialerPackageName(userId))) { 12033 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12034 + "\": is the default dialer"); 12035 return false; 12036 } 12037 12038 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12039 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12040 + "\": protected package"); 12041 return false; 12042 } 12043 12044 return true; 12045 } 12046 12047 private String getActiveLauncherPackageName(int userId) { 12048 Intent intent = new Intent(Intent.ACTION_MAIN); 12049 intent.addCategory(Intent.CATEGORY_HOME); 12050 ResolveInfo resolveInfo = resolveIntent( 12051 intent, 12052 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 12053 PackageManager.MATCH_DEFAULT_ONLY, 12054 userId); 12055 12056 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 12057 } 12058 12059 private String getDefaultDialerPackageName(int userId) { 12060 synchronized (mPackages) { 12061 return mSettings.getDefaultDialerPackageNameLPw(userId); 12062 } 12063 } 12064 12065 @Override 12066 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 12067 mContext.enforceCallingOrSelfPermission( 12068 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12069 "Only package verification agents can verify applications"); 12070 12071 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12072 final PackageVerificationResponse response = new PackageVerificationResponse( 12073 verificationCode, Binder.getCallingUid()); 12074 msg.arg1 = id; 12075 msg.obj = response; 12076 mHandler.sendMessage(msg); 12077 } 12078 12079 @Override 12080 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12081 long millisecondsToDelay) { 12082 mContext.enforceCallingOrSelfPermission( 12083 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12084 "Only package verification agents can extend verification timeouts"); 12085 12086 final PackageVerificationState state = mPendingVerification.get(id); 12087 final PackageVerificationResponse response = new PackageVerificationResponse( 12088 verificationCodeAtTimeout, Binder.getCallingUid()); 12089 12090 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12091 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12092 } 12093 if (millisecondsToDelay < 0) { 12094 millisecondsToDelay = 0; 12095 } 12096 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12097 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12098 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12099 } 12100 12101 if ((state != null) && !state.timeoutExtended()) { 12102 state.extendTimeout(); 12103 12104 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12105 msg.arg1 = id; 12106 msg.obj = response; 12107 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12108 } 12109 } 12110 12111 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12112 int verificationCode, UserHandle user) { 12113 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12114 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12115 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12116 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12117 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12118 12119 mContext.sendBroadcastAsUser(intent, user, 12120 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12121 } 12122 12123 private ComponentName matchComponentForVerifier(String packageName, 12124 List<ResolveInfo> receivers) { 12125 ActivityInfo targetReceiver = null; 12126 12127 final int NR = receivers.size(); 12128 for (int i = 0; i < NR; i++) { 12129 final ResolveInfo info = receivers.get(i); 12130 if (info.activityInfo == null) { 12131 continue; 12132 } 12133 12134 if (packageName.equals(info.activityInfo.packageName)) { 12135 targetReceiver = info.activityInfo; 12136 break; 12137 } 12138 } 12139 12140 if (targetReceiver == null) { 12141 return null; 12142 } 12143 12144 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12145 } 12146 12147 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12148 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12149 if (pkgInfo.verifiers.length == 0) { 12150 return null; 12151 } 12152 12153 final int N = pkgInfo.verifiers.length; 12154 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12155 for (int i = 0; i < N; i++) { 12156 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12157 12158 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12159 receivers); 12160 if (comp == null) { 12161 continue; 12162 } 12163 12164 final int verifierUid = getUidForVerifier(verifierInfo); 12165 if (verifierUid == -1) { 12166 continue; 12167 } 12168 12169 if (DEBUG_VERIFY) { 12170 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12171 + " with the correct signature"); 12172 } 12173 sufficientVerifiers.add(comp); 12174 verificationState.addSufficientVerifier(verifierUid); 12175 } 12176 12177 return sufficientVerifiers; 12178 } 12179 12180 private int getUidForVerifier(VerifierInfo verifierInfo) { 12181 synchronized (mPackages) { 12182 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12183 if (pkg == null) { 12184 return -1; 12185 } else if (pkg.mSignatures.length != 1) { 12186 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12187 + " has more than one signature; ignoring"); 12188 return -1; 12189 } 12190 12191 /* 12192 * If the public key of the package's signature does not match 12193 * our expected public key, then this is a different package and 12194 * we should skip. 12195 */ 12196 12197 final byte[] expectedPublicKey; 12198 try { 12199 final Signature verifierSig = pkg.mSignatures[0]; 12200 final PublicKey publicKey = verifierSig.getPublicKey(); 12201 expectedPublicKey = publicKey.getEncoded(); 12202 } catch (CertificateException e) { 12203 return -1; 12204 } 12205 12206 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12207 12208 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12209 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12210 + " does not have the expected public key; ignoring"); 12211 return -1; 12212 } 12213 12214 return pkg.applicationInfo.uid; 12215 } 12216 } 12217 12218 @Override 12219 public void finishPackageInstall(int token, boolean didLaunch) { 12220 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12221 12222 if (DEBUG_INSTALL) { 12223 Slog.v(TAG, "BM finishing package install for " + token); 12224 } 12225 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12226 12227 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12228 mHandler.sendMessage(msg); 12229 } 12230 12231 /** 12232 * Get the verification agent timeout. 12233 * 12234 * @return verification timeout in milliseconds 12235 */ 12236 private long getVerificationTimeout() { 12237 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12238 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12239 DEFAULT_VERIFICATION_TIMEOUT); 12240 } 12241 12242 /** 12243 * Get the default verification agent response code. 12244 * 12245 * @return default verification response code 12246 */ 12247 private int getDefaultVerificationResponse() { 12248 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12249 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12250 DEFAULT_VERIFICATION_RESPONSE); 12251 } 12252 12253 /** 12254 * Check whether or not package verification has been enabled. 12255 * 12256 * @return true if verification should be performed 12257 */ 12258 private boolean isVerificationEnabled(int userId, int installFlags) { 12259 if (!DEFAULT_VERIFY_ENABLE) { 12260 return false; 12261 } 12262 // Ephemeral apps don't get the full verification treatment 12263 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12264 if (DEBUG_EPHEMERAL) { 12265 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12266 } 12267 return false; 12268 } 12269 12270 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12271 12272 // Check if installing from ADB 12273 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12274 // Do not run verification in a test harness environment 12275 if (ActivityManager.isRunningInTestHarness()) { 12276 return false; 12277 } 12278 if (ensureVerifyAppsEnabled) { 12279 return true; 12280 } 12281 // Check if the developer does not want package verification for ADB installs 12282 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12283 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12284 return false; 12285 } 12286 } 12287 12288 if (ensureVerifyAppsEnabled) { 12289 return true; 12290 } 12291 12292 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12293 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12294 } 12295 12296 @Override 12297 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12298 throws RemoteException { 12299 mContext.enforceCallingOrSelfPermission( 12300 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12301 "Only intentfilter verification agents can verify applications"); 12302 12303 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12304 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12305 Binder.getCallingUid(), verificationCode, failedDomains); 12306 msg.arg1 = id; 12307 msg.obj = response; 12308 mHandler.sendMessage(msg); 12309 } 12310 12311 @Override 12312 public int getIntentVerificationStatus(String packageName, int userId) { 12313 synchronized (mPackages) { 12314 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12315 } 12316 } 12317 12318 @Override 12319 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12320 mContext.enforceCallingOrSelfPermission( 12321 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12322 12323 boolean result = false; 12324 synchronized (mPackages) { 12325 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12326 } 12327 if (result) { 12328 scheduleWritePackageRestrictionsLocked(userId); 12329 } 12330 return result; 12331 } 12332 12333 @Override 12334 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12335 String packageName) { 12336 synchronized (mPackages) { 12337 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12338 } 12339 } 12340 12341 @Override 12342 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12343 if (TextUtils.isEmpty(packageName)) { 12344 return ParceledListSlice.emptyList(); 12345 } 12346 synchronized (mPackages) { 12347 PackageParser.Package pkg = mPackages.get(packageName); 12348 if (pkg == null || pkg.activities == null) { 12349 return ParceledListSlice.emptyList(); 12350 } 12351 final int count = pkg.activities.size(); 12352 ArrayList<IntentFilter> result = new ArrayList<>(); 12353 for (int n=0; n<count; n++) { 12354 PackageParser.Activity activity = pkg.activities.get(n); 12355 if (activity.intents != null && activity.intents.size() > 0) { 12356 result.addAll(activity.intents); 12357 } 12358 } 12359 return new ParceledListSlice<>(result); 12360 } 12361 } 12362 12363 @Override 12364 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12365 mContext.enforceCallingOrSelfPermission( 12366 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12367 12368 synchronized (mPackages) { 12369 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12370 if (packageName != null) { 12371 result |= updateIntentVerificationStatus(packageName, 12372 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12373 userId); 12374 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12375 packageName, userId); 12376 } 12377 return result; 12378 } 12379 } 12380 12381 @Override 12382 public String getDefaultBrowserPackageName(int userId) { 12383 synchronized (mPackages) { 12384 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12385 } 12386 } 12387 12388 /** 12389 * Get the "allow unknown sources" setting. 12390 * 12391 * @return the current "allow unknown sources" setting 12392 */ 12393 private int getUnknownSourcesSettings() { 12394 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12395 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12396 -1); 12397 } 12398 12399 @Override 12400 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12401 final int uid = Binder.getCallingUid(); 12402 // writer 12403 synchronized (mPackages) { 12404 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12405 if (targetPackageSetting == null) { 12406 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12407 } 12408 12409 PackageSetting installerPackageSetting; 12410 if (installerPackageName != null) { 12411 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12412 if (installerPackageSetting == null) { 12413 throw new IllegalArgumentException("Unknown installer package: " 12414 + installerPackageName); 12415 } 12416 } else { 12417 installerPackageSetting = null; 12418 } 12419 12420 Signature[] callerSignature; 12421 Object obj = mSettings.getUserIdLPr(uid); 12422 if (obj != null) { 12423 if (obj instanceof SharedUserSetting) { 12424 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12425 } else if (obj instanceof PackageSetting) { 12426 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12427 } else { 12428 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12429 } 12430 } else { 12431 throw new SecurityException("Unknown calling UID: " + uid); 12432 } 12433 12434 // Verify: can't set installerPackageName to a package that is 12435 // not signed with the same cert as the caller. 12436 if (installerPackageSetting != null) { 12437 if (compareSignatures(callerSignature, 12438 installerPackageSetting.signatures.mSignatures) 12439 != PackageManager.SIGNATURE_MATCH) { 12440 throw new SecurityException( 12441 "Caller does not have same cert as new installer package " 12442 + installerPackageName); 12443 } 12444 } 12445 12446 // Verify: if target already has an installer package, it must 12447 // be signed with the same cert as the caller. 12448 if (targetPackageSetting.installerPackageName != null) { 12449 PackageSetting setting = mSettings.mPackages.get( 12450 targetPackageSetting.installerPackageName); 12451 // If the currently set package isn't valid, then it's always 12452 // okay to change it. 12453 if (setting != null) { 12454 if (compareSignatures(callerSignature, 12455 setting.signatures.mSignatures) 12456 != PackageManager.SIGNATURE_MATCH) { 12457 throw new SecurityException( 12458 "Caller does not have same cert as old installer package " 12459 + targetPackageSetting.installerPackageName); 12460 } 12461 } 12462 } 12463 12464 // Okay! 12465 targetPackageSetting.installerPackageName = installerPackageName; 12466 if (installerPackageName != null) { 12467 mSettings.mInstallerPackages.add(installerPackageName); 12468 } 12469 scheduleWriteSettingsLocked(); 12470 } 12471 } 12472 12473 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12474 // Queue up an async operation since the package installation may take a little while. 12475 mHandler.post(new Runnable() { 12476 public void run() { 12477 mHandler.removeCallbacks(this); 12478 // Result object to be returned 12479 PackageInstalledInfo res = new PackageInstalledInfo(); 12480 res.setReturnCode(currentStatus); 12481 res.uid = -1; 12482 res.pkg = null; 12483 res.removedInfo = null; 12484 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12485 args.doPreInstall(res.returnCode); 12486 synchronized (mInstallLock) { 12487 installPackageTracedLI(args, res); 12488 } 12489 args.doPostInstall(res.returnCode, res.uid); 12490 } 12491 12492 // A restore should be performed at this point if (a) the install 12493 // succeeded, (b) the operation is not an update, and (c) the new 12494 // package has not opted out of backup participation. 12495 final boolean update = res.removedInfo != null 12496 && res.removedInfo.removedPackage != null; 12497 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12498 boolean doRestore = !update 12499 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12500 12501 // Set up the post-install work request bookkeeping. This will be used 12502 // and cleaned up by the post-install event handling regardless of whether 12503 // there's a restore pass performed. Token values are >= 1. 12504 int token; 12505 if (mNextInstallToken < 0) mNextInstallToken = 1; 12506 token = mNextInstallToken++; 12507 12508 PostInstallData data = new PostInstallData(args, res); 12509 mRunningInstalls.put(token, data); 12510 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12511 12512 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12513 // Pass responsibility to the Backup Manager. It will perform a 12514 // restore if appropriate, then pass responsibility back to the 12515 // Package Manager to run the post-install observer callbacks 12516 // and broadcasts. 12517 IBackupManager bm = IBackupManager.Stub.asInterface( 12518 ServiceManager.getService(Context.BACKUP_SERVICE)); 12519 if (bm != null) { 12520 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12521 + " to BM for possible restore"); 12522 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12523 try { 12524 // TODO: http://b/22388012 12525 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12526 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12527 } else { 12528 doRestore = false; 12529 } 12530 } catch (RemoteException e) { 12531 // can't happen; the backup manager is local 12532 } catch (Exception e) { 12533 Slog.e(TAG, "Exception trying to enqueue restore", e); 12534 doRestore = false; 12535 } 12536 } else { 12537 Slog.e(TAG, "Backup Manager not found!"); 12538 doRestore = false; 12539 } 12540 } 12541 12542 if (!doRestore) { 12543 // No restore possible, or the Backup Manager was mysteriously not 12544 // available -- just fire the post-install work request directly. 12545 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12546 12547 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12548 12549 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12550 mHandler.sendMessage(msg); 12551 } 12552 } 12553 }); 12554 } 12555 12556 /** 12557 * Callback from PackageSettings whenever an app is first transitioned out of the 12558 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12559 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12560 * here whether the app is the target of an ongoing install, and only send the 12561 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12562 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12563 * handling. 12564 */ 12565 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12566 // Serialize this with the rest of the install-process message chain. In the 12567 // restore-at-install case, this Runnable will necessarily run before the 12568 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12569 // are coherent. In the non-restore case, the app has already completed install 12570 // and been launched through some other means, so it is not in a problematic 12571 // state for observers to see the FIRST_LAUNCH signal. 12572 mHandler.post(new Runnable() { 12573 @Override 12574 public void run() { 12575 for (int i = 0; i < mRunningInstalls.size(); i++) { 12576 final PostInstallData data = mRunningInstalls.valueAt(i); 12577 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12578 continue; 12579 } 12580 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12581 // right package; but is it for the right user? 12582 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12583 if (userId == data.res.newUsers[uIndex]) { 12584 if (DEBUG_BACKUP) { 12585 Slog.i(TAG, "Package " + pkgName 12586 + " being restored so deferring FIRST_LAUNCH"); 12587 } 12588 return; 12589 } 12590 } 12591 } 12592 } 12593 // didn't find it, so not being restored 12594 if (DEBUG_BACKUP) { 12595 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12596 } 12597 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12598 } 12599 }); 12600 } 12601 12602 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12603 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12604 installerPkg, null, userIds); 12605 } 12606 12607 private abstract class HandlerParams { 12608 private static final int MAX_RETRIES = 4; 12609 12610 /** 12611 * Number of times startCopy() has been attempted and had a non-fatal 12612 * error. 12613 */ 12614 private int mRetries = 0; 12615 12616 /** User handle for the user requesting the information or installation. */ 12617 private final UserHandle mUser; 12618 String traceMethod; 12619 int traceCookie; 12620 12621 HandlerParams(UserHandle user) { 12622 mUser = user; 12623 } 12624 12625 UserHandle getUser() { 12626 return mUser; 12627 } 12628 12629 HandlerParams setTraceMethod(String traceMethod) { 12630 this.traceMethod = traceMethod; 12631 return this; 12632 } 12633 12634 HandlerParams setTraceCookie(int traceCookie) { 12635 this.traceCookie = traceCookie; 12636 return this; 12637 } 12638 12639 final boolean startCopy() { 12640 boolean res; 12641 try { 12642 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12643 12644 if (++mRetries > MAX_RETRIES) { 12645 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12646 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12647 handleServiceError(); 12648 return false; 12649 } else { 12650 handleStartCopy(); 12651 res = true; 12652 } 12653 } catch (RemoteException e) { 12654 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12655 mHandler.sendEmptyMessage(MCS_RECONNECT); 12656 res = false; 12657 } 12658 handleReturnCode(); 12659 return res; 12660 } 12661 12662 final void serviceError() { 12663 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12664 handleServiceError(); 12665 handleReturnCode(); 12666 } 12667 12668 abstract void handleStartCopy() throws RemoteException; 12669 abstract void handleServiceError(); 12670 abstract void handleReturnCode(); 12671 } 12672 12673 class MeasureParams extends HandlerParams { 12674 private final PackageStats mStats; 12675 private boolean mSuccess; 12676 12677 private final IPackageStatsObserver mObserver; 12678 12679 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12680 super(new UserHandle(stats.userHandle)); 12681 mObserver = observer; 12682 mStats = stats; 12683 } 12684 12685 @Override 12686 public String toString() { 12687 return "MeasureParams{" 12688 + Integer.toHexString(System.identityHashCode(this)) 12689 + " " + mStats.packageName + "}"; 12690 } 12691 12692 @Override 12693 void handleStartCopy() throws RemoteException { 12694 synchronized (mInstallLock) { 12695 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12696 } 12697 12698 if (mSuccess) { 12699 boolean mounted = false; 12700 try { 12701 final String status = Environment.getExternalStorageState(); 12702 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12703 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12704 } catch (Exception e) { 12705 } 12706 12707 if (mounted) { 12708 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12709 12710 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12711 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12712 12713 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12714 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12715 12716 // Always subtract cache size, since it's a subdirectory 12717 mStats.externalDataSize -= mStats.externalCacheSize; 12718 12719 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12720 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12721 12722 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12723 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12724 } 12725 } 12726 } 12727 12728 @Override 12729 void handleReturnCode() { 12730 if (mObserver != null) { 12731 try { 12732 mObserver.onGetStatsCompleted(mStats, mSuccess); 12733 } catch (RemoteException e) { 12734 Slog.i(TAG, "Observer no longer exists."); 12735 } 12736 } 12737 } 12738 12739 @Override 12740 void handleServiceError() { 12741 Slog.e(TAG, "Could not measure application " + mStats.packageName 12742 + " external storage"); 12743 } 12744 } 12745 12746 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12747 throws RemoteException { 12748 long result = 0; 12749 for (File path : paths) { 12750 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12751 } 12752 return result; 12753 } 12754 12755 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12756 for (File path : paths) { 12757 try { 12758 mcs.clearDirectory(path.getAbsolutePath()); 12759 } catch (RemoteException e) { 12760 } 12761 } 12762 } 12763 12764 static class OriginInfo { 12765 /** 12766 * Location where install is coming from, before it has been 12767 * copied/renamed into place. This could be a single monolithic APK 12768 * file, or a cluster directory. This location may be untrusted. 12769 */ 12770 final File file; 12771 final String cid; 12772 12773 /** 12774 * Flag indicating that {@link #file} or {@link #cid} has already been 12775 * staged, meaning downstream users don't need to defensively copy the 12776 * contents. 12777 */ 12778 final boolean staged; 12779 12780 /** 12781 * Flag indicating that {@link #file} or {@link #cid} is an already 12782 * installed app that is being moved. 12783 */ 12784 final boolean existing; 12785 12786 final String resolvedPath; 12787 final File resolvedFile; 12788 12789 static OriginInfo fromNothing() { 12790 return new OriginInfo(null, null, false, false); 12791 } 12792 12793 static OriginInfo fromUntrustedFile(File file) { 12794 return new OriginInfo(file, null, false, false); 12795 } 12796 12797 static OriginInfo fromExistingFile(File file) { 12798 return new OriginInfo(file, null, false, true); 12799 } 12800 12801 static OriginInfo fromStagedFile(File file) { 12802 return new OriginInfo(file, null, true, false); 12803 } 12804 12805 static OriginInfo fromStagedContainer(String cid) { 12806 return new OriginInfo(null, cid, true, false); 12807 } 12808 12809 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12810 this.file = file; 12811 this.cid = cid; 12812 this.staged = staged; 12813 this.existing = existing; 12814 12815 if (cid != null) { 12816 resolvedPath = PackageHelper.getSdDir(cid); 12817 resolvedFile = new File(resolvedPath); 12818 } else if (file != null) { 12819 resolvedPath = file.getAbsolutePath(); 12820 resolvedFile = file; 12821 } else { 12822 resolvedPath = null; 12823 resolvedFile = null; 12824 } 12825 } 12826 } 12827 12828 static class MoveInfo { 12829 final int moveId; 12830 final String fromUuid; 12831 final String toUuid; 12832 final String packageName; 12833 final String dataAppName; 12834 final int appId; 12835 final String seinfo; 12836 final int targetSdkVersion; 12837 12838 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12839 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12840 this.moveId = moveId; 12841 this.fromUuid = fromUuid; 12842 this.toUuid = toUuid; 12843 this.packageName = packageName; 12844 this.dataAppName = dataAppName; 12845 this.appId = appId; 12846 this.seinfo = seinfo; 12847 this.targetSdkVersion = targetSdkVersion; 12848 } 12849 } 12850 12851 static class VerificationInfo { 12852 /** A constant used to indicate that a uid value is not present. */ 12853 public static final int NO_UID = -1; 12854 12855 /** URI referencing where the package was downloaded from. */ 12856 final Uri originatingUri; 12857 12858 /** HTTP referrer URI associated with the originatingURI. */ 12859 final Uri referrer; 12860 12861 /** UID of the application that the install request originated from. */ 12862 final int originatingUid; 12863 12864 /** UID of application requesting the install */ 12865 final int installerUid; 12866 12867 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12868 this.originatingUri = originatingUri; 12869 this.referrer = referrer; 12870 this.originatingUid = originatingUid; 12871 this.installerUid = installerUid; 12872 } 12873 } 12874 12875 class InstallParams extends HandlerParams { 12876 final OriginInfo origin; 12877 final MoveInfo move; 12878 final IPackageInstallObserver2 observer; 12879 int installFlags; 12880 final String installerPackageName; 12881 final String volumeUuid; 12882 private InstallArgs mArgs; 12883 private int mRet; 12884 final String packageAbiOverride; 12885 final String[] grantedRuntimePermissions; 12886 final VerificationInfo verificationInfo; 12887 final Certificate[][] certificates; 12888 12889 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12890 int installFlags, String installerPackageName, String volumeUuid, 12891 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12892 String[] grantedPermissions, Certificate[][] certificates) { 12893 super(user); 12894 this.origin = origin; 12895 this.move = move; 12896 this.observer = observer; 12897 this.installFlags = installFlags; 12898 this.installerPackageName = installerPackageName; 12899 this.volumeUuid = volumeUuid; 12900 this.verificationInfo = verificationInfo; 12901 this.packageAbiOverride = packageAbiOverride; 12902 this.grantedRuntimePermissions = grantedPermissions; 12903 this.certificates = certificates; 12904 } 12905 12906 @Override 12907 public String toString() { 12908 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12909 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12910 } 12911 12912 private int installLocationPolicy(PackageInfoLite pkgLite) { 12913 String packageName = pkgLite.packageName; 12914 int installLocation = pkgLite.installLocation; 12915 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12916 // reader 12917 synchronized (mPackages) { 12918 // Currently installed package which the new package is attempting to replace or 12919 // null if no such package is installed. 12920 PackageParser.Package installedPkg = mPackages.get(packageName); 12921 // Package which currently owns the data which the new package will own if installed. 12922 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12923 // will be null whereas dataOwnerPkg will contain information about the package 12924 // which was uninstalled while keeping its data. 12925 PackageParser.Package dataOwnerPkg = installedPkg; 12926 if (dataOwnerPkg == null) { 12927 PackageSetting ps = mSettings.mPackages.get(packageName); 12928 if (ps != null) { 12929 dataOwnerPkg = ps.pkg; 12930 } 12931 } 12932 12933 if (dataOwnerPkg != null) { 12934 // If installed, the package will get access to data left on the device by its 12935 // predecessor. As a security measure, this is permited only if this is not a 12936 // version downgrade or if the predecessor package is marked as debuggable and 12937 // a downgrade is explicitly requested. 12938 // 12939 // On debuggable platform builds, downgrades are permitted even for 12940 // non-debuggable packages to make testing easier. Debuggable platform builds do 12941 // not offer security guarantees and thus it's OK to disable some security 12942 // mechanisms to make debugging/testing easier on those builds. However, even on 12943 // debuggable builds downgrades of packages are permitted only if requested via 12944 // installFlags. This is because we aim to keep the behavior of debuggable 12945 // platform builds as close as possible to the behavior of non-debuggable 12946 // platform builds. 12947 final boolean downgradeRequested = 12948 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12949 final boolean packageDebuggable = 12950 (dataOwnerPkg.applicationInfo.flags 12951 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12952 final boolean downgradePermitted = 12953 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12954 if (!downgradePermitted) { 12955 try { 12956 checkDowngrade(dataOwnerPkg, pkgLite); 12957 } catch (PackageManagerException e) { 12958 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12959 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12960 } 12961 } 12962 } 12963 12964 if (installedPkg != null) { 12965 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12966 // Check for updated system application. 12967 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12968 if (onSd) { 12969 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12970 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12971 } 12972 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12973 } else { 12974 if (onSd) { 12975 // Install flag overrides everything. 12976 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12977 } 12978 // If current upgrade specifies particular preference 12979 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12980 // Application explicitly specified internal. 12981 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12982 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12983 // App explictly prefers external. Let policy decide 12984 } else { 12985 // Prefer previous location 12986 if (isExternal(installedPkg)) { 12987 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12988 } 12989 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12990 } 12991 } 12992 } else { 12993 // Invalid install. Return error code 12994 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12995 } 12996 } 12997 } 12998 // All the special cases have been taken care of. 12999 // Return result based on recommended install location. 13000 if (onSd) { 13001 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13002 } 13003 return pkgLite.recommendedInstallLocation; 13004 } 13005 13006 /* 13007 * Invoke remote method to get package information and install 13008 * location values. Override install location based on default 13009 * policy if needed and then create install arguments based 13010 * on the install location. 13011 */ 13012 public void handleStartCopy() throws RemoteException { 13013 int ret = PackageManager.INSTALL_SUCCEEDED; 13014 13015 // If we're already staged, we've firmly committed to an install location 13016 if (origin.staged) { 13017 if (origin.file != null) { 13018 installFlags |= PackageManager.INSTALL_INTERNAL; 13019 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13020 } else if (origin.cid != null) { 13021 installFlags |= PackageManager.INSTALL_EXTERNAL; 13022 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13023 } else { 13024 throw new IllegalStateException("Invalid stage location"); 13025 } 13026 } 13027 13028 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13029 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 13030 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13031 PackageInfoLite pkgLite = null; 13032 13033 if (onInt && onSd) { 13034 // Check if both bits are set. 13035 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 13036 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13037 } else if (onSd && ephemeral) { 13038 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 13039 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13040 } else { 13041 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 13042 packageAbiOverride); 13043 13044 if (DEBUG_EPHEMERAL && ephemeral) { 13045 Slog.v(TAG, "pkgLite for install: " + pkgLite); 13046 } 13047 13048 /* 13049 * If we have too little free space, try to free cache 13050 * before giving up. 13051 */ 13052 if (!origin.staged && pkgLite.recommendedInstallLocation 13053 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13054 // TODO: focus freeing disk space on the target device 13055 final StorageManager storage = StorageManager.from(mContext); 13056 final long lowThreshold = storage.getStorageLowBytes( 13057 Environment.getDataDirectory()); 13058 13059 final long sizeBytes = mContainerService.calculateInstalledSize( 13060 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 13061 13062 try { 13063 mInstaller.freeCache(null, sizeBytes + lowThreshold); 13064 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 13065 installFlags, packageAbiOverride); 13066 } catch (InstallerException e) { 13067 Slog.w(TAG, "Failed to free cache", e); 13068 } 13069 13070 /* 13071 * The cache free must have deleted the file we 13072 * downloaded to install. 13073 * 13074 * TODO: fix the "freeCache" call to not delete 13075 * the file we care about. 13076 */ 13077 if (pkgLite.recommendedInstallLocation 13078 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13079 pkgLite.recommendedInstallLocation 13080 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 13081 } 13082 } 13083 } 13084 13085 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13086 int loc = pkgLite.recommendedInstallLocation; 13087 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13088 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13089 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13090 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13091 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13092 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13093 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13094 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13095 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13096 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13097 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13098 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13099 } else { 13100 // Override with defaults if needed. 13101 loc = installLocationPolicy(pkgLite); 13102 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13103 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13104 } else if (!onSd && !onInt) { 13105 // Override install location with flags 13106 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13107 // Set the flag to install on external media. 13108 installFlags |= PackageManager.INSTALL_EXTERNAL; 13109 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13110 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13111 if (DEBUG_EPHEMERAL) { 13112 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13113 } 13114 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13115 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13116 |PackageManager.INSTALL_INTERNAL); 13117 } else { 13118 // Make sure the flag for installing on external 13119 // media is unset 13120 installFlags |= PackageManager.INSTALL_INTERNAL; 13121 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13122 } 13123 } 13124 } 13125 } 13126 13127 final InstallArgs args = createInstallArgs(this); 13128 mArgs = args; 13129 13130 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13131 // TODO: http://b/22976637 13132 // Apps installed for "all" users use the device owner to verify the app 13133 UserHandle verifierUser = getUser(); 13134 if (verifierUser == UserHandle.ALL) { 13135 verifierUser = UserHandle.SYSTEM; 13136 } 13137 13138 /* 13139 * Determine if we have any installed package verifiers. If we 13140 * do, then we'll defer to them to verify the packages. 13141 */ 13142 final int requiredUid = mRequiredVerifierPackage == null ? -1 13143 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13144 verifierUser.getIdentifier()); 13145 if (!origin.existing && requiredUid != -1 13146 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13147 final Intent verification = new Intent( 13148 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13149 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13150 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13151 PACKAGE_MIME_TYPE); 13152 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13153 13154 // Query all live verifiers based on current user state 13155 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13156 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13157 13158 if (DEBUG_VERIFY) { 13159 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13160 + verification.toString() + " with " + pkgLite.verifiers.length 13161 + " optional verifiers"); 13162 } 13163 13164 final int verificationId = mPendingVerificationToken++; 13165 13166 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13167 13168 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13169 installerPackageName); 13170 13171 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13172 installFlags); 13173 13174 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13175 pkgLite.packageName); 13176 13177 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13178 pkgLite.versionCode); 13179 13180 if (verificationInfo != null) { 13181 if (verificationInfo.originatingUri != null) { 13182 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13183 verificationInfo.originatingUri); 13184 } 13185 if (verificationInfo.referrer != null) { 13186 verification.putExtra(Intent.EXTRA_REFERRER, 13187 verificationInfo.referrer); 13188 } 13189 if (verificationInfo.originatingUid >= 0) { 13190 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13191 verificationInfo.originatingUid); 13192 } 13193 if (verificationInfo.installerUid >= 0) { 13194 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13195 verificationInfo.installerUid); 13196 } 13197 } 13198 13199 final PackageVerificationState verificationState = new PackageVerificationState( 13200 requiredUid, args); 13201 13202 mPendingVerification.append(verificationId, verificationState); 13203 13204 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13205 receivers, verificationState); 13206 13207 /* 13208 * If any sufficient verifiers were listed in the package 13209 * manifest, attempt to ask them. 13210 */ 13211 if (sufficientVerifiers != null) { 13212 final int N = sufficientVerifiers.size(); 13213 if (N == 0) { 13214 Slog.i(TAG, "Additional verifiers required, but none installed."); 13215 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13216 } else { 13217 for (int i = 0; i < N; i++) { 13218 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13219 13220 final Intent sufficientIntent = new Intent(verification); 13221 sufficientIntent.setComponent(verifierComponent); 13222 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13223 } 13224 } 13225 } 13226 13227 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13228 mRequiredVerifierPackage, receivers); 13229 if (ret == PackageManager.INSTALL_SUCCEEDED 13230 && mRequiredVerifierPackage != null) { 13231 Trace.asyncTraceBegin( 13232 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13233 /* 13234 * Send the intent to the required verification agent, 13235 * but only start the verification timeout after the 13236 * target BroadcastReceivers have run. 13237 */ 13238 verification.setComponent(requiredVerifierComponent); 13239 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13240 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13241 new BroadcastReceiver() { 13242 @Override 13243 public void onReceive(Context context, Intent intent) { 13244 final Message msg = mHandler 13245 .obtainMessage(CHECK_PENDING_VERIFICATION); 13246 msg.arg1 = verificationId; 13247 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13248 } 13249 }, null, 0, null, null); 13250 13251 /* 13252 * We don't want the copy to proceed until verification 13253 * succeeds, so null out this field. 13254 */ 13255 mArgs = null; 13256 } 13257 } else { 13258 /* 13259 * No package verification is enabled, so immediately start 13260 * the remote call to initiate copy using temporary file. 13261 */ 13262 ret = args.copyApk(mContainerService, true); 13263 } 13264 } 13265 13266 mRet = ret; 13267 } 13268 13269 @Override 13270 void handleReturnCode() { 13271 // If mArgs is null, then MCS couldn't be reached. When it 13272 // reconnects, it will try again to install. At that point, this 13273 // will succeed. 13274 if (mArgs != null) { 13275 processPendingInstall(mArgs, mRet); 13276 } 13277 } 13278 13279 @Override 13280 void handleServiceError() { 13281 mArgs = createInstallArgs(this); 13282 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13283 } 13284 13285 public boolean isForwardLocked() { 13286 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13287 } 13288 } 13289 13290 /** 13291 * Used during creation of InstallArgs 13292 * 13293 * @param installFlags package installation flags 13294 * @return true if should be installed on external storage 13295 */ 13296 private static boolean installOnExternalAsec(int installFlags) { 13297 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13298 return false; 13299 } 13300 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13301 return true; 13302 } 13303 return false; 13304 } 13305 13306 /** 13307 * Used during creation of InstallArgs 13308 * 13309 * @param installFlags package installation flags 13310 * @return true if should be installed as forward locked 13311 */ 13312 private static boolean installForwardLocked(int installFlags) { 13313 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13314 } 13315 13316 private InstallArgs createInstallArgs(InstallParams params) { 13317 if (params.move != null) { 13318 return new MoveInstallArgs(params); 13319 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13320 return new AsecInstallArgs(params); 13321 } else { 13322 return new FileInstallArgs(params); 13323 } 13324 } 13325 13326 /** 13327 * Create args that describe an existing installed package. Typically used 13328 * when cleaning up old installs, or used as a move source. 13329 */ 13330 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13331 String resourcePath, String[] instructionSets) { 13332 final boolean isInAsec; 13333 if (installOnExternalAsec(installFlags)) { 13334 /* Apps on SD card are always in ASEC containers. */ 13335 isInAsec = true; 13336 } else if (installForwardLocked(installFlags) 13337 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13338 /* 13339 * Forward-locked apps are only in ASEC containers if they're the 13340 * new style 13341 */ 13342 isInAsec = true; 13343 } else { 13344 isInAsec = false; 13345 } 13346 13347 if (isInAsec) { 13348 return new AsecInstallArgs(codePath, instructionSets, 13349 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13350 } else { 13351 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13352 } 13353 } 13354 13355 static abstract class InstallArgs { 13356 /** @see InstallParams#origin */ 13357 final OriginInfo origin; 13358 /** @see InstallParams#move */ 13359 final MoveInfo move; 13360 13361 final IPackageInstallObserver2 observer; 13362 // Always refers to PackageManager flags only 13363 final int installFlags; 13364 final String installerPackageName; 13365 final String volumeUuid; 13366 final UserHandle user; 13367 final String abiOverride; 13368 final String[] installGrantPermissions; 13369 /** If non-null, drop an async trace when the install completes */ 13370 final String traceMethod; 13371 final int traceCookie; 13372 final Certificate[][] certificates; 13373 13374 // The list of instruction sets supported by this app. This is currently 13375 // only used during the rmdex() phase to clean up resources. We can get rid of this 13376 // if we move dex files under the common app path. 13377 /* nullable */ String[] instructionSets; 13378 13379 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13380 int installFlags, String installerPackageName, String volumeUuid, 13381 UserHandle user, String[] instructionSets, 13382 String abiOverride, String[] installGrantPermissions, 13383 String traceMethod, int traceCookie, Certificate[][] certificates) { 13384 this.origin = origin; 13385 this.move = move; 13386 this.installFlags = installFlags; 13387 this.observer = observer; 13388 this.installerPackageName = installerPackageName; 13389 this.volumeUuid = volumeUuid; 13390 this.user = user; 13391 this.instructionSets = instructionSets; 13392 this.abiOverride = abiOverride; 13393 this.installGrantPermissions = installGrantPermissions; 13394 this.traceMethod = traceMethod; 13395 this.traceCookie = traceCookie; 13396 this.certificates = certificates; 13397 } 13398 13399 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13400 abstract int doPreInstall(int status); 13401 13402 /** 13403 * Rename package into final resting place. All paths on the given 13404 * scanned package should be updated to reflect the rename. 13405 */ 13406 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13407 abstract int doPostInstall(int status, int uid); 13408 13409 /** @see PackageSettingBase#codePathString */ 13410 abstract String getCodePath(); 13411 /** @see PackageSettingBase#resourcePathString */ 13412 abstract String getResourcePath(); 13413 13414 // Need installer lock especially for dex file removal. 13415 abstract void cleanUpResourcesLI(); 13416 abstract boolean doPostDeleteLI(boolean delete); 13417 13418 /** 13419 * Called before the source arguments are copied. This is used mostly 13420 * for MoveParams when it needs to read the source file to put it in the 13421 * destination. 13422 */ 13423 int doPreCopy() { 13424 return PackageManager.INSTALL_SUCCEEDED; 13425 } 13426 13427 /** 13428 * Called after the source arguments are copied. This is used mostly for 13429 * MoveParams when it needs to read the source file to put it in the 13430 * destination. 13431 */ 13432 int doPostCopy(int uid) { 13433 return PackageManager.INSTALL_SUCCEEDED; 13434 } 13435 13436 protected boolean isFwdLocked() { 13437 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13438 } 13439 13440 protected boolean isExternalAsec() { 13441 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13442 } 13443 13444 protected boolean isEphemeral() { 13445 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13446 } 13447 13448 UserHandle getUser() { 13449 return user; 13450 } 13451 } 13452 13453 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13454 if (!allCodePaths.isEmpty()) { 13455 if (instructionSets == null) { 13456 throw new IllegalStateException("instructionSet == null"); 13457 } 13458 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13459 for (String codePath : allCodePaths) { 13460 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13461 try { 13462 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13463 } catch (InstallerException ignored) { 13464 } 13465 } 13466 } 13467 } 13468 } 13469 13470 /** 13471 * Logic to handle installation of non-ASEC applications, including copying 13472 * and renaming logic. 13473 */ 13474 class FileInstallArgs extends InstallArgs { 13475 private File codeFile; 13476 private File resourceFile; 13477 13478 // Example topology: 13479 // /data/app/com.example/base.apk 13480 // /data/app/com.example/split_foo.apk 13481 // /data/app/com.example/lib/arm/libfoo.so 13482 // /data/app/com.example/lib/arm64/libfoo.so 13483 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13484 13485 /** New install */ 13486 FileInstallArgs(InstallParams params) { 13487 super(params.origin, params.move, params.observer, params.installFlags, 13488 params.installerPackageName, params.volumeUuid, 13489 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13490 params.grantedRuntimePermissions, 13491 params.traceMethod, params.traceCookie, params.certificates); 13492 if (isFwdLocked()) { 13493 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13494 } 13495 } 13496 13497 /** Existing install */ 13498 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13499 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13500 null, null, null, 0, null /*certificates*/); 13501 this.codeFile = (codePath != null) ? new File(codePath) : null; 13502 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13503 } 13504 13505 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13506 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13507 try { 13508 return doCopyApk(imcs, temp); 13509 } finally { 13510 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13511 } 13512 } 13513 13514 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13515 if (origin.staged) { 13516 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13517 codeFile = origin.file; 13518 resourceFile = origin.file; 13519 return PackageManager.INSTALL_SUCCEEDED; 13520 } 13521 13522 try { 13523 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13524 final File tempDir = 13525 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13526 codeFile = tempDir; 13527 resourceFile = tempDir; 13528 } catch (IOException e) { 13529 Slog.w(TAG, "Failed to create copy file: " + e); 13530 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13531 } 13532 13533 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13534 @Override 13535 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13536 if (!FileUtils.isValidExtFilename(name)) { 13537 throw new IllegalArgumentException("Invalid filename: " + name); 13538 } 13539 try { 13540 final File file = new File(codeFile, name); 13541 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13542 O_RDWR | O_CREAT, 0644); 13543 Os.chmod(file.getAbsolutePath(), 0644); 13544 return new ParcelFileDescriptor(fd); 13545 } catch (ErrnoException e) { 13546 throw new RemoteException("Failed to open: " + e.getMessage()); 13547 } 13548 } 13549 }; 13550 13551 int ret = PackageManager.INSTALL_SUCCEEDED; 13552 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13553 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13554 Slog.e(TAG, "Failed to copy package"); 13555 return ret; 13556 } 13557 13558 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13559 NativeLibraryHelper.Handle handle = null; 13560 try { 13561 handle = NativeLibraryHelper.Handle.create(codeFile); 13562 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13563 abiOverride); 13564 } catch (IOException e) { 13565 Slog.e(TAG, "Copying native libraries failed", e); 13566 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13567 } finally { 13568 IoUtils.closeQuietly(handle); 13569 } 13570 13571 return ret; 13572 } 13573 13574 int doPreInstall(int status) { 13575 if (status != PackageManager.INSTALL_SUCCEEDED) { 13576 cleanUp(); 13577 } 13578 return status; 13579 } 13580 13581 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13582 if (status != PackageManager.INSTALL_SUCCEEDED) { 13583 cleanUp(); 13584 return false; 13585 } 13586 13587 final File targetDir = codeFile.getParentFile(); 13588 final File beforeCodeFile = codeFile; 13589 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13590 13591 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13592 try { 13593 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13594 } catch (ErrnoException e) { 13595 Slog.w(TAG, "Failed to rename", e); 13596 return false; 13597 } 13598 13599 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13600 Slog.w(TAG, "Failed to restorecon"); 13601 return false; 13602 } 13603 13604 // Reflect the rename internally 13605 codeFile = afterCodeFile; 13606 resourceFile = afterCodeFile; 13607 13608 // Reflect the rename in scanned details 13609 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13610 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13611 afterCodeFile, pkg.baseCodePath)); 13612 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13613 afterCodeFile, pkg.splitCodePaths)); 13614 13615 // Reflect the rename in app info 13616 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13617 pkg.setApplicationInfoCodePath(pkg.codePath); 13618 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13619 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13620 pkg.setApplicationInfoResourcePath(pkg.codePath); 13621 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13622 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13623 13624 return true; 13625 } 13626 13627 int doPostInstall(int status, int uid) { 13628 if (status != PackageManager.INSTALL_SUCCEEDED) { 13629 cleanUp(); 13630 } 13631 return status; 13632 } 13633 13634 @Override 13635 String getCodePath() { 13636 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13637 } 13638 13639 @Override 13640 String getResourcePath() { 13641 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13642 } 13643 13644 private boolean cleanUp() { 13645 if (codeFile == null || !codeFile.exists()) { 13646 return false; 13647 } 13648 13649 removeCodePathLI(codeFile); 13650 13651 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13652 resourceFile.delete(); 13653 } 13654 13655 return true; 13656 } 13657 13658 void cleanUpResourcesLI() { 13659 // Try enumerating all code paths before deleting 13660 List<String> allCodePaths = Collections.EMPTY_LIST; 13661 if (codeFile != null && codeFile.exists()) { 13662 try { 13663 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13664 allCodePaths = pkg.getAllCodePaths(); 13665 } catch (PackageParserException e) { 13666 // Ignored; we tried our best 13667 } 13668 } 13669 13670 cleanUp(); 13671 removeDexFiles(allCodePaths, instructionSets); 13672 } 13673 13674 boolean doPostDeleteLI(boolean delete) { 13675 // XXX err, shouldn't we respect the delete flag? 13676 cleanUpResourcesLI(); 13677 return true; 13678 } 13679 } 13680 13681 private boolean isAsecExternal(String cid) { 13682 final String asecPath = PackageHelper.getSdFilesystem(cid); 13683 return !asecPath.startsWith(mAsecInternalPath); 13684 } 13685 13686 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13687 PackageManagerException { 13688 if (copyRet < 0) { 13689 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13690 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13691 throw new PackageManagerException(copyRet, message); 13692 } 13693 } 13694 } 13695 13696 /** 13697 * Extract the MountService "container ID" from the full code path of an 13698 * .apk. 13699 */ 13700 static String cidFromCodePath(String fullCodePath) { 13701 int eidx = fullCodePath.lastIndexOf("/"); 13702 String subStr1 = fullCodePath.substring(0, eidx); 13703 int sidx = subStr1.lastIndexOf("/"); 13704 return subStr1.substring(sidx+1, eidx); 13705 } 13706 13707 /** 13708 * Logic to handle installation of ASEC applications, including copying and 13709 * renaming logic. 13710 */ 13711 class AsecInstallArgs extends InstallArgs { 13712 static final String RES_FILE_NAME = "pkg.apk"; 13713 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13714 13715 String cid; 13716 String packagePath; 13717 String resourcePath; 13718 13719 /** New install */ 13720 AsecInstallArgs(InstallParams params) { 13721 super(params.origin, params.move, params.observer, params.installFlags, 13722 params.installerPackageName, params.volumeUuid, 13723 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13724 params.grantedRuntimePermissions, 13725 params.traceMethod, params.traceCookie, params.certificates); 13726 } 13727 13728 /** Existing install */ 13729 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13730 boolean isExternal, boolean isForwardLocked) { 13731 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13732 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13733 instructionSets, null, null, null, 0, null /*certificates*/); 13734 // Hackily pretend we're still looking at a full code path 13735 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13736 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13737 } 13738 13739 // Extract cid from fullCodePath 13740 int eidx = fullCodePath.lastIndexOf("/"); 13741 String subStr1 = fullCodePath.substring(0, eidx); 13742 int sidx = subStr1.lastIndexOf("/"); 13743 cid = subStr1.substring(sidx+1, eidx); 13744 setMountPath(subStr1); 13745 } 13746 13747 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13748 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13749 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13750 instructionSets, null, null, null, 0, null /*certificates*/); 13751 this.cid = cid; 13752 setMountPath(PackageHelper.getSdDir(cid)); 13753 } 13754 13755 void createCopyFile() { 13756 cid = mInstallerService.allocateExternalStageCidLegacy(); 13757 } 13758 13759 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13760 if (origin.staged && origin.cid != null) { 13761 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13762 cid = origin.cid; 13763 setMountPath(PackageHelper.getSdDir(cid)); 13764 return PackageManager.INSTALL_SUCCEEDED; 13765 } 13766 13767 if (temp) { 13768 createCopyFile(); 13769 } else { 13770 /* 13771 * Pre-emptively destroy the container since it's destroyed if 13772 * copying fails due to it existing anyway. 13773 */ 13774 PackageHelper.destroySdDir(cid); 13775 } 13776 13777 final String newMountPath = imcs.copyPackageToContainer( 13778 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13779 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13780 13781 if (newMountPath != null) { 13782 setMountPath(newMountPath); 13783 return PackageManager.INSTALL_SUCCEEDED; 13784 } else { 13785 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13786 } 13787 } 13788 13789 @Override 13790 String getCodePath() { 13791 return packagePath; 13792 } 13793 13794 @Override 13795 String getResourcePath() { 13796 return resourcePath; 13797 } 13798 13799 int doPreInstall(int status) { 13800 if (status != PackageManager.INSTALL_SUCCEEDED) { 13801 // Destroy container 13802 PackageHelper.destroySdDir(cid); 13803 } else { 13804 boolean mounted = PackageHelper.isContainerMounted(cid); 13805 if (!mounted) { 13806 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13807 Process.SYSTEM_UID); 13808 if (newMountPath != null) { 13809 setMountPath(newMountPath); 13810 } else { 13811 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13812 } 13813 } 13814 } 13815 return status; 13816 } 13817 13818 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13819 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13820 String newMountPath = null; 13821 if (PackageHelper.isContainerMounted(cid)) { 13822 // Unmount the container 13823 if (!PackageHelper.unMountSdDir(cid)) { 13824 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13825 return false; 13826 } 13827 } 13828 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13829 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13830 " which might be stale. Will try to clean up."); 13831 // Clean up the stale container and proceed to recreate. 13832 if (!PackageHelper.destroySdDir(newCacheId)) { 13833 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13834 return false; 13835 } 13836 // Successfully cleaned up stale container. Try to rename again. 13837 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13838 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13839 + " inspite of cleaning it up."); 13840 return false; 13841 } 13842 } 13843 if (!PackageHelper.isContainerMounted(newCacheId)) { 13844 Slog.w(TAG, "Mounting container " + newCacheId); 13845 newMountPath = PackageHelper.mountSdDir(newCacheId, 13846 getEncryptKey(), Process.SYSTEM_UID); 13847 } else { 13848 newMountPath = PackageHelper.getSdDir(newCacheId); 13849 } 13850 if (newMountPath == null) { 13851 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13852 return false; 13853 } 13854 Log.i(TAG, "Succesfully renamed " + cid + 13855 " to " + newCacheId + 13856 " at new path: " + newMountPath); 13857 cid = newCacheId; 13858 13859 final File beforeCodeFile = new File(packagePath); 13860 setMountPath(newMountPath); 13861 final File afterCodeFile = new File(packagePath); 13862 13863 // Reflect the rename in scanned details 13864 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13865 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13866 afterCodeFile, pkg.baseCodePath)); 13867 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13868 afterCodeFile, pkg.splitCodePaths)); 13869 13870 // Reflect the rename in app info 13871 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13872 pkg.setApplicationInfoCodePath(pkg.codePath); 13873 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13874 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13875 pkg.setApplicationInfoResourcePath(pkg.codePath); 13876 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13877 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13878 13879 return true; 13880 } 13881 13882 private void setMountPath(String mountPath) { 13883 final File mountFile = new File(mountPath); 13884 13885 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13886 if (monolithicFile.exists()) { 13887 packagePath = monolithicFile.getAbsolutePath(); 13888 if (isFwdLocked()) { 13889 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13890 } else { 13891 resourcePath = packagePath; 13892 } 13893 } else { 13894 packagePath = mountFile.getAbsolutePath(); 13895 resourcePath = packagePath; 13896 } 13897 } 13898 13899 int doPostInstall(int status, int uid) { 13900 if (status != PackageManager.INSTALL_SUCCEEDED) { 13901 cleanUp(); 13902 } else { 13903 final int groupOwner; 13904 final String protectedFile; 13905 if (isFwdLocked()) { 13906 groupOwner = UserHandle.getSharedAppGid(uid); 13907 protectedFile = RES_FILE_NAME; 13908 } else { 13909 groupOwner = -1; 13910 protectedFile = null; 13911 } 13912 13913 if (uid < Process.FIRST_APPLICATION_UID 13914 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13915 Slog.e(TAG, "Failed to finalize " + cid); 13916 PackageHelper.destroySdDir(cid); 13917 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13918 } 13919 13920 boolean mounted = PackageHelper.isContainerMounted(cid); 13921 if (!mounted) { 13922 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13923 } 13924 } 13925 return status; 13926 } 13927 13928 private void cleanUp() { 13929 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13930 13931 // Destroy secure container 13932 PackageHelper.destroySdDir(cid); 13933 } 13934 13935 private List<String> getAllCodePaths() { 13936 final File codeFile = new File(getCodePath()); 13937 if (codeFile != null && codeFile.exists()) { 13938 try { 13939 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13940 return pkg.getAllCodePaths(); 13941 } catch (PackageParserException e) { 13942 // Ignored; we tried our best 13943 } 13944 } 13945 return Collections.EMPTY_LIST; 13946 } 13947 13948 void cleanUpResourcesLI() { 13949 // Enumerate all code paths before deleting 13950 cleanUpResourcesLI(getAllCodePaths()); 13951 } 13952 13953 private void cleanUpResourcesLI(List<String> allCodePaths) { 13954 cleanUp(); 13955 removeDexFiles(allCodePaths, instructionSets); 13956 } 13957 13958 String getPackageName() { 13959 return getAsecPackageName(cid); 13960 } 13961 13962 boolean doPostDeleteLI(boolean delete) { 13963 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13964 final List<String> allCodePaths = getAllCodePaths(); 13965 boolean mounted = PackageHelper.isContainerMounted(cid); 13966 if (mounted) { 13967 // Unmount first 13968 if (PackageHelper.unMountSdDir(cid)) { 13969 mounted = false; 13970 } 13971 } 13972 if (!mounted && delete) { 13973 cleanUpResourcesLI(allCodePaths); 13974 } 13975 return !mounted; 13976 } 13977 13978 @Override 13979 int doPreCopy() { 13980 if (isFwdLocked()) { 13981 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13982 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13983 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13984 } 13985 } 13986 13987 return PackageManager.INSTALL_SUCCEEDED; 13988 } 13989 13990 @Override 13991 int doPostCopy(int uid) { 13992 if (isFwdLocked()) { 13993 if (uid < Process.FIRST_APPLICATION_UID 13994 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13995 RES_FILE_NAME)) { 13996 Slog.e(TAG, "Failed to finalize " + cid); 13997 PackageHelper.destroySdDir(cid); 13998 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13999 } 14000 } 14001 14002 return PackageManager.INSTALL_SUCCEEDED; 14003 } 14004 } 14005 14006 /** 14007 * Logic to handle movement of existing installed applications. 14008 */ 14009 class MoveInstallArgs extends InstallArgs { 14010 private File codeFile; 14011 private File resourceFile; 14012 14013 /** New install */ 14014 MoveInstallArgs(InstallParams params) { 14015 super(params.origin, params.move, params.observer, params.installFlags, 14016 params.installerPackageName, params.volumeUuid, 14017 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14018 params.grantedRuntimePermissions, 14019 params.traceMethod, params.traceCookie, params.certificates); 14020 } 14021 14022 int copyApk(IMediaContainerService imcs, boolean temp) { 14023 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 14024 + move.fromUuid + " to " + move.toUuid); 14025 synchronized (mInstaller) { 14026 try { 14027 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 14028 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 14029 } catch (InstallerException e) { 14030 Slog.w(TAG, "Failed to move app", e); 14031 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14032 } 14033 } 14034 14035 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 14036 resourceFile = codeFile; 14037 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 14038 14039 return PackageManager.INSTALL_SUCCEEDED; 14040 } 14041 14042 int doPreInstall(int status) { 14043 if (status != PackageManager.INSTALL_SUCCEEDED) { 14044 cleanUp(move.toUuid); 14045 } 14046 return status; 14047 } 14048 14049 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14050 if (status != PackageManager.INSTALL_SUCCEEDED) { 14051 cleanUp(move.toUuid); 14052 return false; 14053 } 14054 14055 // Reflect the move in app info 14056 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14057 pkg.setApplicationInfoCodePath(pkg.codePath); 14058 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14059 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14060 pkg.setApplicationInfoResourcePath(pkg.codePath); 14061 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14062 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14063 14064 return true; 14065 } 14066 14067 int doPostInstall(int status, int uid) { 14068 if (status == PackageManager.INSTALL_SUCCEEDED) { 14069 cleanUp(move.fromUuid); 14070 } else { 14071 cleanUp(move.toUuid); 14072 } 14073 return status; 14074 } 14075 14076 @Override 14077 String getCodePath() { 14078 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14079 } 14080 14081 @Override 14082 String getResourcePath() { 14083 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14084 } 14085 14086 private boolean cleanUp(String volumeUuid) { 14087 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14088 move.dataAppName); 14089 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14090 final int[] userIds = sUserManager.getUserIds(); 14091 synchronized (mInstallLock) { 14092 // Clean up both app data and code 14093 // All package moves are frozen until finished 14094 for (int userId : userIds) { 14095 try { 14096 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14097 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14098 } catch (InstallerException e) { 14099 Slog.w(TAG, String.valueOf(e)); 14100 } 14101 } 14102 removeCodePathLI(codeFile); 14103 } 14104 return true; 14105 } 14106 14107 void cleanUpResourcesLI() { 14108 throw new UnsupportedOperationException(); 14109 } 14110 14111 boolean doPostDeleteLI(boolean delete) { 14112 throw new UnsupportedOperationException(); 14113 } 14114 } 14115 14116 static String getAsecPackageName(String packageCid) { 14117 int idx = packageCid.lastIndexOf("-"); 14118 if (idx == -1) { 14119 return packageCid; 14120 } 14121 return packageCid.substring(0, idx); 14122 } 14123 14124 // Utility method used to create code paths based on package name and available index. 14125 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14126 String idxStr = ""; 14127 int idx = 1; 14128 // Fall back to default value of idx=1 if prefix is not 14129 // part of oldCodePath 14130 if (oldCodePath != null) { 14131 String subStr = oldCodePath; 14132 // Drop the suffix right away 14133 if (suffix != null && subStr.endsWith(suffix)) { 14134 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14135 } 14136 // If oldCodePath already contains prefix find out the 14137 // ending index to either increment or decrement. 14138 int sidx = subStr.lastIndexOf(prefix); 14139 if (sidx != -1) { 14140 subStr = subStr.substring(sidx + prefix.length()); 14141 if (subStr != null) { 14142 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14143 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14144 } 14145 try { 14146 idx = Integer.parseInt(subStr); 14147 if (idx <= 1) { 14148 idx++; 14149 } else { 14150 idx--; 14151 } 14152 } catch(NumberFormatException e) { 14153 } 14154 } 14155 } 14156 } 14157 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14158 return prefix + idxStr; 14159 } 14160 14161 private File getNextCodePath(File targetDir, String packageName) { 14162 int suffix = 1; 14163 File result; 14164 do { 14165 result = new File(targetDir, packageName + "-" + suffix); 14166 suffix++; 14167 } while (result.exists()); 14168 return result; 14169 } 14170 14171 // Utility method that returns the relative package path with respect 14172 // to the installation directory. Like say for /data/data/com.test-1.apk 14173 // string com.test-1 is returned. 14174 static String deriveCodePathName(String codePath) { 14175 if (codePath == null) { 14176 return null; 14177 } 14178 final File codeFile = new File(codePath); 14179 final String name = codeFile.getName(); 14180 if (codeFile.isDirectory()) { 14181 return name; 14182 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14183 final int lastDot = name.lastIndexOf('.'); 14184 return name.substring(0, lastDot); 14185 } else { 14186 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14187 return null; 14188 } 14189 } 14190 14191 static class PackageInstalledInfo { 14192 String name; 14193 int uid; 14194 // The set of users that originally had this package installed. 14195 int[] origUsers; 14196 // The set of users that now have this package installed. 14197 int[] newUsers; 14198 PackageParser.Package pkg; 14199 int returnCode; 14200 String returnMsg; 14201 PackageRemovedInfo removedInfo; 14202 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14203 14204 public void setError(int code, String msg) { 14205 setReturnCode(code); 14206 setReturnMessage(msg); 14207 Slog.w(TAG, msg); 14208 } 14209 14210 public void setError(String msg, PackageParserException e) { 14211 setReturnCode(e.error); 14212 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14213 Slog.w(TAG, msg, e); 14214 } 14215 14216 public void setError(String msg, PackageManagerException e) { 14217 returnCode = e.error; 14218 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14219 Slog.w(TAG, msg, e); 14220 } 14221 14222 public void setReturnCode(int returnCode) { 14223 this.returnCode = returnCode; 14224 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14225 for (int i = 0; i < childCount; i++) { 14226 addedChildPackages.valueAt(i).returnCode = returnCode; 14227 } 14228 } 14229 14230 private void setReturnMessage(String returnMsg) { 14231 this.returnMsg = returnMsg; 14232 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14233 for (int i = 0; i < childCount; i++) { 14234 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14235 } 14236 } 14237 14238 // In some error cases we want to convey more info back to the observer 14239 String origPackage; 14240 String origPermission; 14241 } 14242 14243 /* 14244 * Install a non-existing package. 14245 */ 14246 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14247 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14248 PackageInstalledInfo res) { 14249 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14250 14251 // Remember this for later, in case we need to rollback this install 14252 String pkgName = pkg.packageName; 14253 14254 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14255 14256 synchronized(mPackages) { 14257 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 14258 if (renamedPackage != null) { 14259 // A package with the same name is already installed, though 14260 // it has been renamed to an older name. The package we 14261 // are trying to install should be installed as an update to 14262 // the existing one, but that has not been requested, so bail. 14263 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14264 + " without first uninstalling package running as " 14265 + renamedPackage); 14266 return; 14267 } 14268 if (mPackages.containsKey(pkgName)) { 14269 // Don't allow installation over an existing package with the same name. 14270 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14271 + " without first uninstalling."); 14272 return; 14273 } 14274 } 14275 14276 try { 14277 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14278 System.currentTimeMillis(), user); 14279 14280 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14281 14282 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14283 prepareAppDataAfterInstallLIF(newPackage); 14284 14285 } else { 14286 // Remove package from internal structures, but keep around any 14287 // data that might have already existed 14288 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14289 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14290 } 14291 } catch (PackageManagerException e) { 14292 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14293 } 14294 14295 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14296 } 14297 14298 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14299 // Can't rotate keys during boot or if sharedUser. 14300 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14301 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14302 return false; 14303 } 14304 // app is using upgradeKeySets; make sure all are valid 14305 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14306 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14307 for (int i = 0; i < upgradeKeySets.length; i++) { 14308 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14309 Slog.wtf(TAG, "Package " 14310 + (oldPs.name != null ? oldPs.name : "<null>") 14311 + " contains upgrade-key-set reference to unknown key-set: " 14312 + upgradeKeySets[i] 14313 + " reverting to signatures check."); 14314 return false; 14315 } 14316 } 14317 return true; 14318 } 14319 14320 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14321 // Upgrade keysets are being used. Determine if new package has a superset of the 14322 // required keys. 14323 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14324 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14325 for (int i = 0; i < upgradeKeySets.length; i++) { 14326 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14327 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14328 return true; 14329 } 14330 } 14331 return false; 14332 } 14333 14334 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14335 try (DigestInputStream digestStream = 14336 new DigestInputStream(new FileInputStream(file), digest)) { 14337 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14338 } 14339 } 14340 14341 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14342 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14343 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14344 14345 final PackageParser.Package oldPackage; 14346 final String pkgName = pkg.packageName; 14347 final int[] allUsers; 14348 final int[] installedUsers; 14349 14350 synchronized(mPackages) { 14351 oldPackage = mPackages.get(pkgName); 14352 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14353 14354 // don't allow upgrade to target a release SDK from a pre-release SDK 14355 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14356 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14357 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14358 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14359 if (oldTargetsPreRelease 14360 && !newTargetsPreRelease 14361 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14362 Slog.w(TAG, "Can't install package targeting released sdk"); 14363 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14364 return; 14365 } 14366 14367 // don't allow an upgrade from full to ephemeral 14368 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14369 if (isEphemeral && !oldIsEphemeral) { 14370 // can't downgrade from full to ephemeral 14371 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14372 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14373 return; 14374 } 14375 14376 // verify signatures are valid 14377 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14378 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14379 if (!checkUpgradeKeySetLP(ps, pkg)) { 14380 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14381 "New package not signed by keys specified by upgrade-keysets: " 14382 + pkgName); 14383 return; 14384 } 14385 } else { 14386 // default to original signature matching 14387 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14388 != PackageManager.SIGNATURE_MATCH) { 14389 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14390 "New package has a different signature: " + pkgName); 14391 return; 14392 } 14393 } 14394 14395 // don't allow a system upgrade unless the upgrade hash matches 14396 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14397 byte[] digestBytes = null; 14398 try { 14399 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14400 updateDigest(digest, new File(pkg.baseCodePath)); 14401 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14402 for (String path : pkg.splitCodePaths) { 14403 updateDigest(digest, new File(path)); 14404 } 14405 } 14406 digestBytes = digest.digest(); 14407 } catch (NoSuchAlgorithmException | IOException e) { 14408 res.setError(INSTALL_FAILED_INVALID_APK, 14409 "Could not compute hash: " + pkgName); 14410 return; 14411 } 14412 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14413 res.setError(INSTALL_FAILED_INVALID_APK, 14414 "New package fails restrict-update check: " + pkgName); 14415 return; 14416 } 14417 // retain upgrade restriction 14418 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14419 } 14420 14421 // Check for shared user id changes 14422 String invalidPackageName = 14423 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14424 if (invalidPackageName != null) { 14425 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14426 "Package " + invalidPackageName + " tried to change user " 14427 + oldPackage.mSharedUserId); 14428 return; 14429 } 14430 14431 // In case of rollback, remember per-user/profile install state 14432 allUsers = sUserManager.getUserIds(); 14433 installedUsers = ps.queryInstalledUsers(allUsers, true); 14434 } 14435 14436 // Update what is removed 14437 res.removedInfo = new PackageRemovedInfo(); 14438 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14439 res.removedInfo.removedPackage = oldPackage.packageName; 14440 res.removedInfo.isUpdate = true; 14441 res.removedInfo.origUsers = installedUsers; 14442 final int childCount = (oldPackage.childPackages != null) 14443 ? oldPackage.childPackages.size() : 0; 14444 for (int i = 0; i < childCount; i++) { 14445 boolean childPackageUpdated = false; 14446 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14447 if (res.addedChildPackages != null) { 14448 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14449 if (childRes != null) { 14450 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14451 childRes.removedInfo.removedPackage = childPkg.packageName; 14452 childRes.removedInfo.isUpdate = true; 14453 childPackageUpdated = true; 14454 } 14455 } 14456 if (!childPackageUpdated) { 14457 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14458 childRemovedRes.removedPackage = childPkg.packageName; 14459 childRemovedRes.isUpdate = false; 14460 childRemovedRes.dataRemoved = true; 14461 synchronized (mPackages) { 14462 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14463 if (childPs != null) { 14464 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14465 } 14466 } 14467 if (res.removedInfo.removedChildPackages == null) { 14468 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14469 } 14470 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14471 } 14472 } 14473 14474 boolean sysPkg = (isSystemApp(oldPackage)); 14475 if (sysPkg) { 14476 // Set the system/privileged flags as needed 14477 final boolean privileged = 14478 (oldPackage.applicationInfo.privateFlags 14479 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14480 final int systemPolicyFlags = policyFlags 14481 | PackageParser.PARSE_IS_SYSTEM 14482 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14483 14484 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14485 user, allUsers, installerPackageName, res); 14486 } else { 14487 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14488 user, allUsers, installerPackageName, res); 14489 } 14490 } 14491 14492 public List<String> getPreviousCodePaths(String packageName) { 14493 final PackageSetting ps = mSettings.mPackages.get(packageName); 14494 final List<String> result = new ArrayList<String>(); 14495 if (ps != null && ps.oldCodePaths != null) { 14496 result.addAll(ps.oldCodePaths); 14497 } 14498 return result; 14499 } 14500 14501 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14502 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14503 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14504 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14505 + deletedPackage); 14506 14507 String pkgName = deletedPackage.packageName; 14508 boolean deletedPkg = true; 14509 boolean addedPkg = false; 14510 boolean updatedSettings = false; 14511 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14512 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14513 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14514 14515 final long origUpdateTime = (pkg.mExtras != null) 14516 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14517 14518 // First delete the existing package while retaining the data directory 14519 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14520 res.removedInfo, true, pkg)) { 14521 // If the existing package wasn't successfully deleted 14522 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14523 deletedPkg = false; 14524 } else { 14525 // Successfully deleted the old package; proceed with replace. 14526 14527 // If deleted package lived in a container, give users a chance to 14528 // relinquish resources before killing. 14529 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14530 if (DEBUG_INSTALL) { 14531 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14532 } 14533 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14534 final ArrayList<String> pkgList = new ArrayList<String>(1); 14535 pkgList.add(deletedPackage.applicationInfo.packageName); 14536 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14537 } 14538 14539 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14540 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14541 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14542 14543 try { 14544 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14545 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14546 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14547 14548 // Update the in-memory copy of the previous code paths. 14549 PackageSetting ps = mSettings.mPackages.get(pkgName); 14550 if (!killApp) { 14551 if (ps.oldCodePaths == null) { 14552 ps.oldCodePaths = new ArraySet<>(); 14553 } 14554 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14555 if (deletedPackage.splitCodePaths != null) { 14556 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14557 } 14558 } else { 14559 ps.oldCodePaths = null; 14560 } 14561 if (ps.childPackageNames != null) { 14562 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14563 final String childPkgName = ps.childPackageNames.get(i); 14564 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14565 childPs.oldCodePaths = ps.oldCodePaths; 14566 } 14567 } 14568 prepareAppDataAfterInstallLIF(newPackage); 14569 addedPkg = true; 14570 } catch (PackageManagerException e) { 14571 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14572 } 14573 } 14574 14575 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14576 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14577 14578 // Revert all internal state mutations and added folders for the failed install 14579 if (addedPkg) { 14580 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14581 res.removedInfo, true, null); 14582 } 14583 14584 // Restore the old package 14585 if (deletedPkg) { 14586 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14587 File restoreFile = new File(deletedPackage.codePath); 14588 // Parse old package 14589 boolean oldExternal = isExternal(deletedPackage); 14590 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14591 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14592 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14593 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14594 try { 14595 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14596 null); 14597 } catch (PackageManagerException e) { 14598 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14599 + e.getMessage()); 14600 return; 14601 } 14602 14603 synchronized (mPackages) { 14604 // Ensure the installer package name up to date 14605 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14606 14607 // Update permissions for restored package 14608 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14609 14610 mSettings.writeLPr(); 14611 } 14612 14613 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14614 } 14615 } else { 14616 synchronized (mPackages) { 14617 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14618 if (ps != null) { 14619 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14620 if (res.removedInfo.removedChildPackages != null) { 14621 final int childCount = res.removedInfo.removedChildPackages.size(); 14622 // Iterate in reverse as we may modify the collection 14623 for (int i = childCount - 1; i >= 0; i--) { 14624 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14625 if (res.addedChildPackages.containsKey(childPackageName)) { 14626 res.removedInfo.removedChildPackages.removeAt(i); 14627 } else { 14628 PackageRemovedInfo childInfo = res.removedInfo 14629 .removedChildPackages.valueAt(i); 14630 childInfo.removedForAllUsers = mPackages.get( 14631 childInfo.removedPackage) == null; 14632 } 14633 } 14634 } 14635 } 14636 } 14637 } 14638 } 14639 14640 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14641 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14642 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14643 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14644 + ", old=" + deletedPackage); 14645 14646 final boolean disabledSystem; 14647 14648 // Remove existing system package 14649 removePackageLI(deletedPackage, true); 14650 14651 synchronized (mPackages) { 14652 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14653 } 14654 if (!disabledSystem) { 14655 // We didn't need to disable the .apk as a current system package, 14656 // which means we are replacing another update that is already 14657 // installed. We need to make sure to delete the older one's .apk. 14658 res.removedInfo.args = createInstallArgsForExisting(0, 14659 deletedPackage.applicationInfo.getCodePath(), 14660 deletedPackage.applicationInfo.getResourcePath(), 14661 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14662 } else { 14663 res.removedInfo.args = null; 14664 } 14665 14666 // Successfully disabled the old package. Now proceed with re-installation 14667 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14668 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14669 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14670 14671 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14672 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14673 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14674 14675 PackageParser.Package newPackage = null; 14676 try { 14677 // Add the package to the internal data structures 14678 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14679 14680 // Set the update and install times 14681 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14682 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14683 System.currentTimeMillis()); 14684 14685 // Update the package dynamic state if succeeded 14686 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14687 // Now that the install succeeded make sure we remove data 14688 // directories for any child package the update removed. 14689 final int deletedChildCount = (deletedPackage.childPackages != null) 14690 ? deletedPackage.childPackages.size() : 0; 14691 final int newChildCount = (newPackage.childPackages != null) 14692 ? newPackage.childPackages.size() : 0; 14693 for (int i = 0; i < deletedChildCount; i++) { 14694 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14695 boolean childPackageDeleted = true; 14696 for (int j = 0; j < newChildCount; j++) { 14697 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14698 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14699 childPackageDeleted = false; 14700 break; 14701 } 14702 } 14703 if (childPackageDeleted) { 14704 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14705 deletedChildPkg.packageName); 14706 if (ps != null && res.removedInfo.removedChildPackages != null) { 14707 PackageRemovedInfo removedChildRes = res.removedInfo 14708 .removedChildPackages.get(deletedChildPkg.packageName); 14709 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14710 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14711 } 14712 } 14713 } 14714 14715 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14716 prepareAppDataAfterInstallLIF(newPackage); 14717 } 14718 } catch (PackageManagerException e) { 14719 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14720 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14721 } 14722 14723 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14724 // Re installation failed. Restore old information 14725 // Remove new pkg information 14726 if (newPackage != null) { 14727 removeInstalledPackageLI(newPackage, true); 14728 } 14729 // Add back the old system package 14730 try { 14731 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14732 } catch (PackageManagerException e) { 14733 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14734 } 14735 14736 synchronized (mPackages) { 14737 if (disabledSystem) { 14738 enableSystemPackageLPw(deletedPackage); 14739 } 14740 14741 // Ensure the installer package name up to date 14742 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14743 14744 // Update permissions for restored package 14745 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14746 14747 mSettings.writeLPr(); 14748 } 14749 14750 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14751 + " after failed upgrade"); 14752 } 14753 } 14754 14755 /** 14756 * Checks whether the parent or any of the child packages have a change shared 14757 * user. For a package to be a valid update the shred users of the parent and 14758 * the children should match. We may later support changing child shared users. 14759 * @param oldPkg The updated package. 14760 * @param newPkg The update package. 14761 * @return The shared user that change between the versions. 14762 */ 14763 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14764 PackageParser.Package newPkg) { 14765 // Check parent shared user 14766 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14767 return newPkg.packageName; 14768 } 14769 // Check child shared users 14770 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14771 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14772 for (int i = 0; i < newChildCount; i++) { 14773 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14774 // If this child was present, did it have the same shared user? 14775 for (int j = 0; j < oldChildCount; j++) { 14776 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14777 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14778 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14779 return newChildPkg.packageName; 14780 } 14781 } 14782 } 14783 return null; 14784 } 14785 14786 private void removeNativeBinariesLI(PackageSetting ps) { 14787 // Remove the lib path for the parent package 14788 if (ps != null) { 14789 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14790 // Remove the lib path for the child packages 14791 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14792 for (int i = 0; i < childCount; i++) { 14793 PackageSetting childPs = null; 14794 synchronized (mPackages) { 14795 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14796 } 14797 if (childPs != null) { 14798 NativeLibraryHelper.removeNativeBinariesLI(childPs 14799 .legacyNativeLibraryPathString); 14800 } 14801 } 14802 } 14803 } 14804 14805 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14806 // Enable the parent package 14807 mSettings.enableSystemPackageLPw(pkg.packageName); 14808 // Enable the child packages 14809 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14810 for (int i = 0; i < childCount; i++) { 14811 PackageParser.Package childPkg = pkg.childPackages.get(i); 14812 mSettings.enableSystemPackageLPw(childPkg.packageName); 14813 } 14814 } 14815 14816 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14817 PackageParser.Package newPkg) { 14818 // Disable the parent package (parent always replaced) 14819 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14820 // Disable the child packages 14821 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14822 for (int i = 0; i < childCount; i++) { 14823 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14824 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14825 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14826 } 14827 return disabled; 14828 } 14829 14830 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14831 String installerPackageName) { 14832 // Enable the parent package 14833 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14834 // Enable the child packages 14835 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14836 for (int i = 0; i < childCount; i++) { 14837 PackageParser.Package childPkg = pkg.childPackages.get(i); 14838 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14839 } 14840 } 14841 14842 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14843 // Collect all used permissions in the UID 14844 ArraySet<String> usedPermissions = new ArraySet<>(); 14845 final int packageCount = su.packages.size(); 14846 for (int i = 0; i < packageCount; i++) { 14847 PackageSetting ps = su.packages.valueAt(i); 14848 if (ps.pkg == null) { 14849 continue; 14850 } 14851 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14852 for (int j = 0; j < requestedPermCount; j++) { 14853 String permission = ps.pkg.requestedPermissions.get(j); 14854 BasePermission bp = mSettings.mPermissions.get(permission); 14855 if (bp != null) { 14856 usedPermissions.add(permission); 14857 } 14858 } 14859 } 14860 14861 PermissionsState permissionsState = su.getPermissionsState(); 14862 // Prune install permissions 14863 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14864 final int installPermCount = installPermStates.size(); 14865 for (int i = installPermCount - 1; i >= 0; i--) { 14866 PermissionState permissionState = installPermStates.get(i); 14867 if (!usedPermissions.contains(permissionState.getName())) { 14868 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14869 if (bp != null) { 14870 permissionsState.revokeInstallPermission(bp); 14871 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14872 PackageManager.MASK_PERMISSION_FLAGS, 0); 14873 } 14874 } 14875 } 14876 14877 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14878 14879 // Prune runtime permissions 14880 for (int userId : allUserIds) { 14881 List<PermissionState> runtimePermStates = permissionsState 14882 .getRuntimePermissionStates(userId); 14883 final int runtimePermCount = runtimePermStates.size(); 14884 for (int i = runtimePermCount - 1; i >= 0; i--) { 14885 PermissionState permissionState = runtimePermStates.get(i); 14886 if (!usedPermissions.contains(permissionState.getName())) { 14887 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14888 if (bp != null) { 14889 permissionsState.revokeRuntimePermission(bp, userId); 14890 permissionsState.updatePermissionFlags(bp, userId, 14891 PackageManager.MASK_PERMISSION_FLAGS, 0); 14892 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14893 runtimePermissionChangedUserIds, userId); 14894 } 14895 } 14896 } 14897 } 14898 14899 return runtimePermissionChangedUserIds; 14900 } 14901 14902 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14903 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14904 // Update the parent package setting 14905 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14906 res, user); 14907 // Update the child packages setting 14908 final int childCount = (newPackage.childPackages != null) 14909 ? newPackage.childPackages.size() : 0; 14910 for (int i = 0; i < childCount; i++) { 14911 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14912 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14913 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14914 childRes.origUsers, childRes, user); 14915 } 14916 } 14917 14918 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14919 String installerPackageName, int[] allUsers, int[] installedForUsers, 14920 PackageInstalledInfo res, UserHandle user) { 14921 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14922 14923 String pkgName = newPackage.packageName; 14924 synchronized (mPackages) { 14925 //write settings. the installStatus will be incomplete at this stage. 14926 //note that the new package setting would have already been 14927 //added to mPackages. It hasn't been persisted yet. 14928 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14929 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14930 mSettings.writeLPr(); 14931 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14932 } 14933 14934 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14935 synchronized (mPackages) { 14936 updatePermissionsLPw(newPackage.packageName, newPackage, 14937 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14938 ? UPDATE_PERMISSIONS_ALL : 0)); 14939 // For system-bundled packages, we assume that installing an upgraded version 14940 // of the package implies that the user actually wants to run that new code, 14941 // so we enable the package. 14942 PackageSetting ps = mSettings.mPackages.get(pkgName); 14943 final int userId = user.getIdentifier(); 14944 if (ps != null) { 14945 if (isSystemApp(newPackage)) { 14946 if (DEBUG_INSTALL) { 14947 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14948 } 14949 // Enable system package for requested users 14950 if (res.origUsers != null) { 14951 for (int origUserId : res.origUsers) { 14952 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14953 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14954 origUserId, installerPackageName); 14955 } 14956 } 14957 } 14958 // Also convey the prior install/uninstall state 14959 if (allUsers != null && installedForUsers != null) { 14960 for (int currentUserId : allUsers) { 14961 final boolean installed = ArrayUtils.contains( 14962 installedForUsers, currentUserId); 14963 if (DEBUG_INSTALL) { 14964 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14965 } 14966 ps.setInstalled(installed, currentUserId); 14967 } 14968 // these install state changes will be persisted in the 14969 // upcoming call to mSettings.writeLPr(). 14970 } 14971 } 14972 // It's implied that when a user requests installation, they want the app to be 14973 // installed and enabled. 14974 if (userId != UserHandle.USER_ALL) { 14975 ps.setInstalled(true, userId); 14976 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14977 } 14978 } 14979 res.name = pkgName; 14980 res.uid = newPackage.applicationInfo.uid; 14981 res.pkg = newPackage; 14982 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14983 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14984 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14985 //to update install status 14986 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14987 mSettings.writeLPr(); 14988 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14989 } 14990 14991 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14992 } 14993 14994 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14995 try { 14996 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14997 installPackageLI(args, res); 14998 } finally { 14999 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15000 } 15001 } 15002 15003 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 15004 final int installFlags = args.installFlags; 15005 final String installerPackageName = args.installerPackageName; 15006 final String volumeUuid = args.volumeUuid; 15007 final File tmpPackageFile = new File(args.getCodePath()); 15008 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 15009 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 15010 || (args.volumeUuid != null)); 15011 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 15012 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 15013 boolean replace = false; 15014 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 15015 if (args.move != null) { 15016 // moving a complete application; perform an initial scan on the new install location 15017 scanFlags |= SCAN_INITIAL; 15018 } 15019 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 15020 scanFlags |= SCAN_DONT_KILL_APP; 15021 } 15022 15023 // Result object to be returned 15024 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15025 15026 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 15027 15028 // Sanity check 15029 if (ephemeral && (forwardLocked || onExternal)) { 15030 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 15031 + " external=" + onExternal); 15032 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15033 return; 15034 } 15035 15036 // Retrieve PackageSettings and parse package 15037 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 15038 | PackageParser.PARSE_ENFORCE_CODE 15039 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 15040 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 15041 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 15042 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 15043 PackageParser pp = new PackageParser(); 15044 pp.setSeparateProcesses(mSeparateProcesses); 15045 pp.setDisplayMetrics(mMetrics); 15046 15047 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 15048 final PackageParser.Package pkg; 15049 try { 15050 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 15051 } catch (PackageParserException e) { 15052 res.setError("Failed parse during installPackageLI", e); 15053 return; 15054 } finally { 15055 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15056 } 15057 15058 // If we are installing a clustered package add results for the children 15059 if (pkg.childPackages != null) { 15060 synchronized (mPackages) { 15061 final int childCount = pkg.childPackages.size(); 15062 for (int i = 0; i < childCount; i++) { 15063 PackageParser.Package childPkg = pkg.childPackages.get(i); 15064 PackageInstalledInfo childRes = new PackageInstalledInfo(); 15065 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15066 childRes.pkg = childPkg; 15067 childRes.name = childPkg.packageName; 15068 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15069 if (childPs != null) { 15070 childRes.origUsers = childPs.queryInstalledUsers( 15071 sUserManager.getUserIds(), true); 15072 } 15073 if ((mPackages.containsKey(childPkg.packageName))) { 15074 childRes.removedInfo = new PackageRemovedInfo(); 15075 childRes.removedInfo.removedPackage = childPkg.packageName; 15076 } 15077 if (res.addedChildPackages == null) { 15078 res.addedChildPackages = new ArrayMap<>(); 15079 } 15080 res.addedChildPackages.put(childPkg.packageName, childRes); 15081 } 15082 } 15083 } 15084 15085 // If package doesn't declare API override, mark that we have an install 15086 // time CPU ABI override. 15087 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15088 pkg.cpuAbiOverride = args.abiOverride; 15089 } 15090 15091 String pkgName = res.name = pkg.packageName; 15092 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15093 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15094 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15095 return; 15096 } 15097 } 15098 15099 try { 15100 // either use what we've been given or parse directly from the APK 15101 if (args.certificates != null) { 15102 try { 15103 PackageParser.populateCertificates(pkg, args.certificates); 15104 } catch (PackageParserException e) { 15105 // there was something wrong with the certificates we were given; 15106 // try to pull them from the APK 15107 PackageParser.collectCertificates(pkg, parseFlags); 15108 } 15109 } else { 15110 PackageParser.collectCertificates(pkg, parseFlags); 15111 } 15112 } catch (PackageParserException e) { 15113 res.setError("Failed collect during installPackageLI", e); 15114 return; 15115 } 15116 15117 // Get rid of all references to package scan path via parser. 15118 pp = null; 15119 String oldCodePath = null; 15120 boolean systemApp = false; 15121 synchronized (mPackages) { 15122 // Check if installing already existing package 15123 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15124 String oldName = mSettings.getRenamedPackageLPr(pkgName); 15125 if (pkg.mOriginalPackages != null 15126 && pkg.mOriginalPackages.contains(oldName) 15127 && mPackages.containsKey(oldName)) { 15128 // This package is derived from an original package, 15129 // and this device has been updating from that original 15130 // name. We must continue using the original name, so 15131 // rename the new package here. 15132 pkg.setPackageName(oldName); 15133 pkgName = pkg.packageName; 15134 replace = true; 15135 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15136 + oldName + " pkgName=" + pkgName); 15137 } else if (mPackages.containsKey(pkgName)) { 15138 // This package, under its official name, already exists 15139 // on the device; we should replace it. 15140 replace = true; 15141 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15142 } 15143 15144 // Child packages are installed through the parent package 15145 if (pkg.parentPackage != null) { 15146 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15147 "Package " + pkg.packageName + " is child of package " 15148 + pkg.parentPackage.parentPackage + ". Child packages " 15149 + "can be updated only through the parent package."); 15150 return; 15151 } 15152 15153 if (replace) { 15154 // Prevent apps opting out from runtime permissions 15155 PackageParser.Package oldPackage = mPackages.get(pkgName); 15156 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15157 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15158 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15159 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15160 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15161 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15162 + " doesn't support runtime permissions but the old" 15163 + " target SDK " + oldTargetSdk + " does."); 15164 return; 15165 } 15166 15167 // Prevent installing of child packages 15168 if (oldPackage.parentPackage != null) { 15169 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15170 "Package " + pkg.packageName + " is child of package " 15171 + oldPackage.parentPackage + ". Child packages " 15172 + "can be updated only through the parent package."); 15173 return; 15174 } 15175 } 15176 } 15177 15178 PackageSetting ps = mSettings.mPackages.get(pkgName); 15179 if (ps != null) { 15180 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15181 15182 // Quick sanity check that we're signed correctly if updating; 15183 // we'll check this again later when scanning, but we want to 15184 // bail early here before tripping over redefined permissions. 15185 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15186 if (!checkUpgradeKeySetLP(ps, pkg)) { 15187 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15188 + pkg.packageName + " upgrade keys do not match the " 15189 + "previously installed version"); 15190 return; 15191 } 15192 } else { 15193 try { 15194 verifySignaturesLP(ps, pkg); 15195 } catch (PackageManagerException e) { 15196 res.setError(e.error, e.getMessage()); 15197 return; 15198 } 15199 } 15200 15201 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15202 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15203 systemApp = (ps.pkg.applicationInfo.flags & 15204 ApplicationInfo.FLAG_SYSTEM) != 0; 15205 } 15206 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15207 } 15208 15209 // Check whether the newly-scanned package wants to define an already-defined perm 15210 int N = pkg.permissions.size(); 15211 for (int i = N-1; i >= 0; i--) { 15212 PackageParser.Permission perm = pkg.permissions.get(i); 15213 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15214 if (bp != null) { 15215 // If the defining package is signed with our cert, it's okay. This 15216 // also includes the "updating the same package" case, of course. 15217 // "updating same package" could also involve key-rotation. 15218 final boolean sigsOk; 15219 if (bp.sourcePackage.equals(pkg.packageName) 15220 && (bp.packageSetting instanceof PackageSetting) 15221 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15222 scanFlags))) { 15223 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15224 } else { 15225 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15226 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15227 } 15228 if (!sigsOk) { 15229 // If the owning package is the system itself, we log but allow 15230 // install to proceed; we fail the install on all other permission 15231 // redefinitions. 15232 if (!bp.sourcePackage.equals("android")) { 15233 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15234 + pkg.packageName + " attempting to redeclare permission " 15235 + perm.info.name + " already owned by " + bp.sourcePackage); 15236 res.origPermission = perm.info.name; 15237 res.origPackage = bp.sourcePackage; 15238 return; 15239 } else { 15240 Slog.w(TAG, "Package " + pkg.packageName 15241 + " attempting to redeclare system permission " 15242 + perm.info.name + "; ignoring new declaration"); 15243 pkg.permissions.remove(i); 15244 } 15245 } 15246 } 15247 } 15248 } 15249 15250 if (systemApp) { 15251 if (onExternal) { 15252 // Abort update; system app can't be replaced with app on sdcard 15253 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15254 "Cannot install updates to system apps on sdcard"); 15255 return; 15256 } else if (ephemeral) { 15257 // Abort update; system app can't be replaced with an ephemeral app 15258 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15259 "Cannot update a system app with an ephemeral app"); 15260 return; 15261 } 15262 } 15263 15264 if (args.move != null) { 15265 // We did an in-place move, so dex is ready to roll 15266 scanFlags |= SCAN_NO_DEX; 15267 scanFlags |= SCAN_MOVE; 15268 15269 synchronized (mPackages) { 15270 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15271 if (ps == null) { 15272 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15273 "Missing settings for moved package " + pkgName); 15274 } 15275 15276 // We moved the entire application as-is, so bring over the 15277 // previously derived ABI information. 15278 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15279 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15280 } 15281 15282 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15283 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15284 scanFlags |= SCAN_NO_DEX; 15285 15286 try { 15287 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15288 args.abiOverride : pkg.cpuAbiOverride); 15289 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15290 true /* extract libs */); 15291 } catch (PackageManagerException pme) { 15292 Slog.e(TAG, "Error deriving application ABI", pme); 15293 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15294 return; 15295 } 15296 15297 // Shared libraries for the package need to be updated. 15298 synchronized (mPackages) { 15299 try { 15300 updateSharedLibrariesLPw(pkg, null); 15301 } catch (PackageManagerException e) { 15302 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15303 } 15304 } 15305 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15306 // Do not run PackageDexOptimizer through the local performDexOpt 15307 // method because `pkg` may not be in `mPackages` yet. 15308 // 15309 // Also, don't fail application installs if the dexopt step fails. 15310 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15311 null /* instructionSets */, false /* checkProfiles */, 15312 getCompilerFilterForReason(REASON_INSTALL), 15313 getOrCreateCompilerPackageStats(pkg)); 15314 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15315 15316 // Notify BackgroundDexOptService that the package has been changed. 15317 // If this is an update of a package which used to fail to compile, 15318 // BDOS will remove it from its blacklist. 15319 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15320 } 15321 15322 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15323 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15324 return; 15325 } 15326 15327 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15328 15329 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15330 "installPackageLI")) { 15331 if (replace) { 15332 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15333 installerPackageName, res); 15334 } else { 15335 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15336 args.user, installerPackageName, volumeUuid, res); 15337 } 15338 } 15339 synchronized (mPackages) { 15340 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15341 if (ps != null) { 15342 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15343 } 15344 15345 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15346 for (int i = 0; i < childCount; i++) { 15347 PackageParser.Package childPkg = pkg.childPackages.get(i); 15348 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15349 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15350 if (childPs != null) { 15351 childRes.newUsers = childPs.queryInstalledUsers( 15352 sUserManager.getUserIds(), true); 15353 } 15354 } 15355 } 15356 } 15357 15358 private void startIntentFilterVerifications(int userId, boolean replacing, 15359 PackageParser.Package pkg) { 15360 if (mIntentFilterVerifierComponent == null) { 15361 Slog.w(TAG, "No IntentFilter verification will not be done as " 15362 + "there is no IntentFilterVerifier available!"); 15363 return; 15364 } 15365 15366 final int verifierUid = getPackageUid( 15367 mIntentFilterVerifierComponent.getPackageName(), 15368 MATCH_DEBUG_TRIAGED_MISSING, 15369 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15370 15371 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15372 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15373 mHandler.sendMessage(msg); 15374 15375 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15376 for (int i = 0; i < childCount; i++) { 15377 PackageParser.Package childPkg = pkg.childPackages.get(i); 15378 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15379 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15380 mHandler.sendMessage(msg); 15381 } 15382 } 15383 15384 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15385 PackageParser.Package pkg) { 15386 int size = pkg.activities.size(); 15387 if (size == 0) { 15388 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15389 "No activity, so no need to verify any IntentFilter!"); 15390 return; 15391 } 15392 15393 final boolean hasDomainURLs = hasDomainURLs(pkg); 15394 if (!hasDomainURLs) { 15395 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15396 "No domain URLs, so no need to verify any IntentFilter!"); 15397 return; 15398 } 15399 15400 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15401 + " if any IntentFilter from the " + size 15402 + " Activities needs verification ..."); 15403 15404 int count = 0; 15405 final String packageName = pkg.packageName; 15406 15407 synchronized (mPackages) { 15408 // If this is a new install and we see that we've already run verification for this 15409 // package, we have nothing to do: it means the state was restored from backup. 15410 if (!replacing) { 15411 IntentFilterVerificationInfo ivi = 15412 mSettings.getIntentFilterVerificationLPr(packageName); 15413 if (ivi != null) { 15414 if (DEBUG_DOMAIN_VERIFICATION) { 15415 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15416 + ivi.getStatusString()); 15417 } 15418 return; 15419 } 15420 } 15421 15422 // If any filters need to be verified, then all need to be. 15423 boolean needToVerify = false; 15424 for (PackageParser.Activity a : pkg.activities) { 15425 for (ActivityIntentInfo filter : a.intents) { 15426 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15427 if (DEBUG_DOMAIN_VERIFICATION) { 15428 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15429 } 15430 needToVerify = true; 15431 break; 15432 } 15433 } 15434 } 15435 15436 if (needToVerify) { 15437 final int verificationId = mIntentFilterVerificationToken++; 15438 for (PackageParser.Activity a : pkg.activities) { 15439 for (ActivityIntentInfo filter : a.intents) { 15440 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15441 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15442 "Verification needed for IntentFilter:" + filter.toString()); 15443 mIntentFilterVerifier.addOneIntentFilterVerification( 15444 verifierUid, userId, verificationId, filter, packageName); 15445 count++; 15446 } 15447 } 15448 } 15449 } 15450 } 15451 15452 if (count > 0) { 15453 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15454 + " IntentFilter verification" + (count > 1 ? "s" : "") 15455 + " for userId:" + userId); 15456 mIntentFilterVerifier.startVerifications(userId); 15457 } else { 15458 if (DEBUG_DOMAIN_VERIFICATION) { 15459 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15460 } 15461 } 15462 } 15463 15464 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15465 final ComponentName cn = filter.activity.getComponentName(); 15466 final String packageName = cn.getPackageName(); 15467 15468 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15469 packageName); 15470 if (ivi == null) { 15471 return true; 15472 } 15473 int status = ivi.getStatus(); 15474 switch (status) { 15475 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15476 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15477 return true; 15478 15479 default: 15480 // Nothing to do 15481 return false; 15482 } 15483 } 15484 15485 private static boolean isMultiArch(ApplicationInfo info) { 15486 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15487 } 15488 15489 private static boolean isExternal(PackageParser.Package pkg) { 15490 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15491 } 15492 15493 private static boolean isExternal(PackageSetting ps) { 15494 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15495 } 15496 15497 private static boolean isEphemeral(PackageParser.Package pkg) { 15498 return pkg.applicationInfo.isEphemeralApp(); 15499 } 15500 15501 private static boolean isEphemeral(PackageSetting ps) { 15502 return ps.pkg != null && isEphemeral(ps.pkg); 15503 } 15504 15505 private static boolean isSystemApp(PackageParser.Package pkg) { 15506 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15507 } 15508 15509 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15510 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15511 } 15512 15513 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15514 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15515 } 15516 15517 private static boolean isSystemApp(PackageSetting ps) { 15518 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15519 } 15520 15521 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15522 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15523 } 15524 15525 private int packageFlagsToInstallFlags(PackageSetting ps) { 15526 int installFlags = 0; 15527 if (isEphemeral(ps)) { 15528 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15529 } 15530 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15531 // This existing package was an external ASEC install when we have 15532 // the external flag without a UUID 15533 installFlags |= PackageManager.INSTALL_EXTERNAL; 15534 } 15535 if (ps.isForwardLocked()) { 15536 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15537 } 15538 return installFlags; 15539 } 15540 15541 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15542 if (isExternal(pkg)) { 15543 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15544 return StorageManager.UUID_PRIMARY_PHYSICAL; 15545 } else { 15546 return pkg.volumeUuid; 15547 } 15548 } else { 15549 return StorageManager.UUID_PRIVATE_INTERNAL; 15550 } 15551 } 15552 15553 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15554 if (isExternal(pkg)) { 15555 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15556 return mSettings.getExternalVersion(); 15557 } else { 15558 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15559 } 15560 } else { 15561 return mSettings.getInternalVersion(); 15562 } 15563 } 15564 15565 private void deleteTempPackageFiles() { 15566 final FilenameFilter filter = new FilenameFilter() { 15567 public boolean accept(File dir, String name) { 15568 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15569 } 15570 }; 15571 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15572 file.delete(); 15573 } 15574 } 15575 15576 @Override 15577 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15578 int flags) { 15579 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15580 flags); 15581 } 15582 15583 @Override 15584 public void deletePackage(final String packageName, 15585 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15586 mContext.enforceCallingOrSelfPermission( 15587 android.Manifest.permission.DELETE_PACKAGES, null); 15588 Preconditions.checkNotNull(packageName); 15589 Preconditions.checkNotNull(observer); 15590 final int uid = Binder.getCallingUid(); 15591 if (!isOrphaned(packageName) 15592 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 15593 try { 15594 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 15595 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 15596 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 15597 observer.onUserActionRequired(intent); 15598 } catch (RemoteException re) { 15599 } 15600 return; 15601 } 15602 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15603 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15604 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15605 mContext.enforceCallingOrSelfPermission( 15606 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15607 "deletePackage for user " + userId); 15608 } 15609 15610 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15611 try { 15612 observer.onPackageDeleted(packageName, 15613 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15614 } catch (RemoteException re) { 15615 } 15616 return; 15617 } 15618 15619 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15620 try { 15621 observer.onPackageDeleted(packageName, 15622 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15623 } catch (RemoteException re) { 15624 } 15625 return; 15626 } 15627 15628 if (DEBUG_REMOVE) { 15629 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15630 + " deleteAllUsers: " + deleteAllUsers ); 15631 } 15632 // Queue up an async operation since the package deletion may take a little while. 15633 mHandler.post(new Runnable() { 15634 public void run() { 15635 mHandler.removeCallbacks(this); 15636 int returnCode; 15637 if (!deleteAllUsers) { 15638 returnCode = deletePackageX(packageName, userId, deleteFlags); 15639 } else { 15640 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15641 // If nobody is blocking uninstall, proceed with delete for all users 15642 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15643 returnCode = deletePackageX(packageName, userId, deleteFlags); 15644 } else { 15645 // Otherwise uninstall individually for users with blockUninstalls=false 15646 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15647 for (int userId : users) { 15648 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15649 returnCode = deletePackageX(packageName, userId, userFlags); 15650 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15651 Slog.w(TAG, "Package delete failed for user " + userId 15652 + ", returnCode " + returnCode); 15653 } 15654 } 15655 } 15656 // The app has only been marked uninstalled for certain users. 15657 // We still need to report that delete was blocked 15658 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15659 } 15660 } 15661 try { 15662 observer.onPackageDeleted(packageName, returnCode, null); 15663 } catch (RemoteException e) { 15664 Log.i(TAG, "Observer no longer exists."); 15665 } //end catch 15666 } //end run 15667 }); 15668 } 15669 15670 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 15671 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 15672 || callingUid == Process.SYSTEM_UID) { 15673 return true; 15674 } 15675 final int callingUserId = UserHandle.getUserId(callingUid); 15676 // If the caller installed the pkgName, then allow it to silently uninstall. 15677 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 15678 return true; 15679 } 15680 15681 // Allow package verifier to silently uninstall. 15682 if (mRequiredVerifierPackage != null && 15683 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 15684 return true; 15685 } 15686 15687 // Allow package uninstaller to silently uninstall. 15688 if (mRequiredUninstallerPackage != null && 15689 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 15690 return true; 15691 } 15692 15693 // Allow storage manager to silently uninstall. 15694 if (mStorageManagerPackage != null && 15695 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 15696 return true; 15697 } 15698 return false; 15699 } 15700 15701 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15702 int[] result = EMPTY_INT_ARRAY; 15703 for (int userId : userIds) { 15704 if (getBlockUninstallForUser(packageName, userId)) { 15705 result = ArrayUtils.appendInt(result, userId); 15706 } 15707 } 15708 return result; 15709 } 15710 15711 @Override 15712 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15713 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15714 } 15715 15716 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15717 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15718 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15719 try { 15720 if (dpm != null) { 15721 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15722 /* callingUserOnly =*/ false); 15723 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15724 : deviceOwnerComponentName.getPackageName(); 15725 // Does the package contains the device owner? 15726 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15727 // this check is probably not needed, since DO should be registered as a device 15728 // admin on some user too. (Original bug for this: b/17657954) 15729 if (packageName.equals(deviceOwnerPackageName)) { 15730 return true; 15731 } 15732 // Does it contain a device admin for any user? 15733 int[] users; 15734 if (userId == UserHandle.USER_ALL) { 15735 users = sUserManager.getUserIds(); 15736 } else { 15737 users = new int[]{userId}; 15738 } 15739 for (int i = 0; i < users.length; ++i) { 15740 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15741 return true; 15742 } 15743 } 15744 } 15745 } catch (RemoteException e) { 15746 } 15747 return false; 15748 } 15749 15750 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15751 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15752 } 15753 15754 /** 15755 * This method is an internal method that could be get invoked either 15756 * to delete an installed package or to clean up a failed installation. 15757 * After deleting an installed package, a broadcast is sent to notify any 15758 * listeners that the package has been removed. For cleaning up a failed 15759 * installation, the broadcast is not necessary since the package's 15760 * installation wouldn't have sent the initial broadcast either 15761 * The key steps in deleting a package are 15762 * deleting the package information in internal structures like mPackages, 15763 * deleting the packages base directories through installd 15764 * updating mSettings to reflect current status 15765 * persisting settings for later use 15766 * sending a broadcast if necessary 15767 */ 15768 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15769 final PackageRemovedInfo info = new PackageRemovedInfo(); 15770 final boolean res; 15771 15772 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15773 ? UserHandle.USER_ALL : userId; 15774 15775 if (isPackageDeviceAdmin(packageName, removeUser)) { 15776 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15777 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15778 } 15779 15780 PackageSetting uninstalledPs = null; 15781 15782 // for the uninstall-updates case and restricted profiles, remember the per- 15783 // user handle installed state 15784 int[] allUsers; 15785 synchronized (mPackages) { 15786 uninstalledPs = mSettings.mPackages.get(packageName); 15787 if (uninstalledPs == null) { 15788 Slog.w(TAG, "Not removing non-existent package " + packageName); 15789 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15790 } 15791 allUsers = sUserManager.getUserIds(); 15792 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15793 } 15794 15795 final int freezeUser; 15796 if (isUpdatedSystemApp(uninstalledPs) 15797 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15798 // We're downgrading a system app, which will apply to all users, so 15799 // freeze them all during the downgrade 15800 freezeUser = UserHandle.USER_ALL; 15801 } else { 15802 freezeUser = removeUser; 15803 } 15804 15805 synchronized (mInstallLock) { 15806 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15807 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15808 deleteFlags, "deletePackageX")) { 15809 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15810 deleteFlags | REMOVE_CHATTY, info, true, null); 15811 } 15812 synchronized (mPackages) { 15813 if (res) { 15814 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15815 } 15816 } 15817 } 15818 15819 if (res) { 15820 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15821 info.sendPackageRemovedBroadcasts(killApp); 15822 info.sendSystemPackageUpdatedBroadcasts(); 15823 info.sendSystemPackageAppearedBroadcasts(); 15824 } 15825 // Force a gc here. 15826 Runtime.getRuntime().gc(); 15827 // Delete the resources here after sending the broadcast to let 15828 // other processes clean up before deleting resources. 15829 if (info.args != null) { 15830 synchronized (mInstallLock) { 15831 info.args.doPostDeleteLI(true); 15832 } 15833 } 15834 15835 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15836 } 15837 15838 class PackageRemovedInfo { 15839 String removedPackage; 15840 int uid = -1; 15841 int removedAppId = -1; 15842 int[] origUsers; 15843 int[] removedUsers = null; 15844 boolean isRemovedPackageSystemUpdate = false; 15845 boolean isUpdate; 15846 boolean dataRemoved; 15847 boolean removedForAllUsers; 15848 // Clean up resources deleted packages. 15849 InstallArgs args = null; 15850 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15851 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15852 15853 void sendPackageRemovedBroadcasts(boolean killApp) { 15854 sendPackageRemovedBroadcastInternal(killApp); 15855 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15856 for (int i = 0; i < childCount; i++) { 15857 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15858 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15859 } 15860 } 15861 15862 void sendSystemPackageUpdatedBroadcasts() { 15863 if (isRemovedPackageSystemUpdate) { 15864 sendSystemPackageUpdatedBroadcastsInternal(); 15865 final int childCount = (removedChildPackages != null) 15866 ? removedChildPackages.size() : 0; 15867 for (int i = 0; i < childCount; i++) { 15868 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15869 if (childInfo.isRemovedPackageSystemUpdate) { 15870 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15871 } 15872 } 15873 } 15874 } 15875 15876 void sendSystemPackageAppearedBroadcasts() { 15877 final int packageCount = (appearedChildPackages != null) 15878 ? appearedChildPackages.size() : 0; 15879 for (int i = 0; i < packageCount; i++) { 15880 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15881 for (int userId : installedInfo.newUsers) { 15882 sendPackageAddedForUser(installedInfo.name, true, 15883 UserHandle.getAppId(installedInfo.uid), userId); 15884 } 15885 } 15886 } 15887 15888 private void sendSystemPackageUpdatedBroadcastsInternal() { 15889 Bundle extras = new Bundle(2); 15890 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15891 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15892 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15893 extras, 0, null, null, null); 15894 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15895 extras, 0, null, null, null); 15896 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15897 null, 0, removedPackage, null, null); 15898 } 15899 15900 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15901 Bundle extras = new Bundle(2); 15902 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15903 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15904 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15905 if (isUpdate || isRemovedPackageSystemUpdate) { 15906 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15907 } 15908 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15909 if (removedPackage != null) { 15910 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15911 extras, 0, null, null, removedUsers); 15912 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15913 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15914 removedPackage, extras, 0, null, null, removedUsers); 15915 } 15916 } 15917 if (removedAppId >= 0) { 15918 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15919 removedUsers); 15920 } 15921 } 15922 } 15923 15924 /* 15925 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15926 * flag is not set, the data directory is removed as well. 15927 * make sure this flag is set for partially installed apps. If not its meaningless to 15928 * delete a partially installed application. 15929 */ 15930 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15931 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15932 String packageName = ps.name; 15933 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15934 // Retrieve object to delete permissions for shared user later on 15935 final PackageParser.Package deletedPkg; 15936 final PackageSetting deletedPs; 15937 // reader 15938 synchronized (mPackages) { 15939 deletedPkg = mPackages.get(packageName); 15940 deletedPs = mSettings.mPackages.get(packageName); 15941 if (outInfo != null) { 15942 outInfo.removedPackage = packageName; 15943 outInfo.removedUsers = deletedPs != null 15944 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15945 : null; 15946 } 15947 } 15948 15949 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15950 15951 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15952 final PackageParser.Package resolvedPkg; 15953 if (deletedPkg != null) { 15954 resolvedPkg = deletedPkg; 15955 } else { 15956 // We don't have a parsed package when it lives on an ejected 15957 // adopted storage device, so fake something together 15958 resolvedPkg = new PackageParser.Package(ps.name); 15959 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15960 } 15961 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15962 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15963 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15964 if (outInfo != null) { 15965 outInfo.dataRemoved = true; 15966 } 15967 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15968 } 15969 15970 // writer 15971 synchronized (mPackages) { 15972 if (deletedPs != null) { 15973 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15974 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15975 clearDefaultBrowserIfNeeded(packageName); 15976 if (outInfo != null) { 15977 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15978 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15979 } 15980 updatePermissionsLPw(deletedPs.name, null, 0); 15981 if (deletedPs.sharedUser != null) { 15982 // Remove permissions associated with package. Since runtime 15983 // permissions are per user we have to kill the removed package 15984 // or packages running under the shared user of the removed 15985 // package if revoking the permissions requested only by the removed 15986 // package is successful and this causes a change in gids. 15987 for (int userId : UserManagerService.getInstance().getUserIds()) { 15988 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15989 userId); 15990 if (userIdToKill == UserHandle.USER_ALL 15991 || userIdToKill >= UserHandle.USER_SYSTEM) { 15992 // If gids changed for this user, kill all affected packages. 15993 mHandler.post(new Runnable() { 15994 @Override 15995 public void run() { 15996 // This has to happen with no lock held. 15997 killApplication(deletedPs.name, deletedPs.appId, 15998 KILL_APP_REASON_GIDS_CHANGED); 15999 } 16000 }); 16001 break; 16002 } 16003 } 16004 } 16005 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 16006 } 16007 // make sure to preserve per-user disabled state if this removal was just 16008 // a downgrade of a system app to the factory package 16009 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 16010 if (DEBUG_REMOVE) { 16011 Slog.d(TAG, "Propagating install state across downgrade"); 16012 } 16013 for (int userId : allUserHandles) { 16014 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16015 if (DEBUG_REMOVE) { 16016 Slog.d(TAG, " user " + userId + " => " + installed); 16017 } 16018 ps.setInstalled(installed, userId); 16019 } 16020 } 16021 } 16022 // can downgrade to reader 16023 if (writeSettings) { 16024 // Save settings now 16025 mSettings.writeLPr(); 16026 } 16027 } 16028 if (outInfo != null) { 16029 // A user ID was deleted here. Go through all users and remove it 16030 // from KeyStore. 16031 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 16032 } 16033 } 16034 16035 static boolean locationIsPrivileged(File path) { 16036 try { 16037 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 16038 .getCanonicalPath(); 16039 return path.getCanonicalPath().startsWith(privilegedAppDir); 16040 } catch (IOException e) { 16041 Slog.e(TAG, "Unable to access code path " + path); 16042 } 16043 return false; 16044 } 16045 16046 /* 16047 * Tries to delete system package. 16048 */ 16049 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 16050 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 16051 boolean writeSettings) { 16052 if (deletedPs.parentPackageName != null) { 16053 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 16054 return false; 16055 } 16056 16057 final boolean applyUserRestrictions 16058 = (allUserHandles != null) && (outInfo.origUsers != null); 16059 final PackageSetting disabledPs; 16060 // Confirm if the system package has been updated 16061 // An updated system app can be deleted. This will also have to restore 16062 // the system pkg from system partition 16063 // reader 16064 synchronized (mPackages) { 16065 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 16066 } 16067 16068 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 16069 + " disabledPs=" + disabledPs); 16070 16071 if (disabledPs == null) { 16072 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 16073 return false; 16074 } else if (DEBUG_REMOVE) { 16075 Slog.d(TAG, "Deleting system pkg from data partition"); 16076 } 16077 16078 if (DEBUG_REMOVE) { 16079 if (applyUserRestrictions) { 16080 Slog.d(TAG, "Remembering install states:"); 16081 for (int userId : allUserHandles) { 16082 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 16083 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 16084 } 16085 } 16086 } 16087 16088 // Delete the updated package 16089 outInfo.isRemovedPackageSystemUpdate = true; 16090 if (outInfo.removedChildPackages != null) { 16091 final int childCount = (deletedPs.childPackageNames != null) 16092 ? deletedPs.childPackageNames.size() : 0; 16093 for (int i = 0; i < childCount; i++) { 16094 String childPackageName = deletedPs.childPackageNames.get(i); 16095 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16096 .contains(childPackageName)) { 16097 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16098 childPackageName); 16099 if (childInfo != null) { 16100 childInfo.isRemovedPackageSystemUpdate = true; 16101 } 16102 } 16103 } 16104 } 16105 16106 if (disabledPs.versionCode < deletedPs.versionCode) { 16107 // Delete data for downgrades 16108 flags &= ~PackageManager.DELETE_KEEP_DATA; 16109 } else { 16110 // Preserve data by setting flag 16111 flags |= PackageManager.DELETE_KEEP_DATA; 16112 } 16113 16114 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16115 outInfo, writeSettings, disabledPs.pkg); 16116 if (!ret) { 16117 return false; 16118 } 16119 16120 // writer 16121 synchronized (mPackages) { 16122 // Reinstate the old system package 16123 enableSystemPackageLPw(disabledPs.pkg); 16124 // Remove any native libraries from the upgraded package. 16125 removeNativeBinariesLI(deletedPs); 16126 } 16127 16128 // Install the system package 16129 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16130 int parseFlags = mDefParseFlags 16131 | PackageParser.PARSE_MUST_BE_APK 16132 | PackageParser.PARSE_IS_SYSTEM 16133 | PackageParser.PARSE_IS_SYSTEM_DIR; 16134 if (locationIsPrivileged(disabledPs.codePath)) { 16135 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16136 } 16137 16138 final PackageParser.Package newPkg; 16139 try { 16140 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 16141 } catch (PackageManagerException e) { 16142 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16143 + e.getMessage()); 16144 return false; 16145 } 16146 try { 16147 // update shared libraries for the newly re-installed system package 16148 updateSharedLibrariesLPw(newPkg, null); 16149 } catch (PackageManagerException e) { 16150 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16151 } 16152 16153 prepareAppDataAfterInstallLIF(newPkg); 16154 16155 // writer 16156 synchronized (mPackages) { 16157 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16158 16159 // Propagate the permissions state as we do not want to drop on the floor 16160 // runtime permissions. The update permissions method below will take 16161 // care of removing obsolete permissions and grant install permissions. 16162 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16163 updatePermissionsLPw(newPkg.packageName, newPkg, 16164 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16165 16166 if (applyUserRestrictions) { 16167 if (DEBUG_REMOVE) { 16168 Slog.d(TAG, "Propagating install state across reinstall"); 16169 } 16170 for (int userId : allUserHandles) { 16171 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16172 if (DEBUG_REMOVE) { 16173 Slog.d(TAG, " user " + userId + " => " + installed); 16174 } 16175 ps.setInstalled(installed, userId); 16176 16177 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16178 } 16179 // Regardless of writeSettings we need to ensure that this restriction 16180 // state propagation is persisted 16181 mSettings.writeAllUsersPackageRestrictionsLPr(); 16182 } 16183 // can downgrade to reader here 16184 if (writeSettings) { 16185 mSettings.writeLPr(); 16186 } 16187 } 16188 return true; 16189 } 16190 16191 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16192 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16193 PackageRemovedInfo outInfo, boolean writeSettings, 16194 PackageParser.Package replacingPackage) { 16195 synchronized (mPackages) { 16196 if (outInfo != null) { 16197 outInfo.uid = ps.appId; 16198 } 16199 16200 if (outInfo != null && outInfo.removedChildPackages != null) { 16201 final int childCount = (ps.childPackageNames != null) 16202 ? ps.childPackageNames.size() : 0; 16203 for (int i = 0; i < childCount; i++) { 16204 String childPackageName = ps.childPackageNames.get(i); 16205 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16206 if (childPs == null) { 16207 return false; 16208 } 16209 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16210 childPackageName); 16211 if (childInfo != null) { 16212 childInfo.uid = childPs.appId; 16213 } 16214 } 16215 } 16216 } 16217 16218 // Delete package data from internal structures and also remove data if flag is set 16219 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16220 16221 // Delete the child packages data 16222 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16223 for (int i = 0; i < childCount; i++) { 16224 PackageSetting childPs; 16225 synchronized (mPackages) { 16226 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16227 } 16228 if (childPs != null) { 16229 PackageRemovedInfo childOutInfo = (outInfo != null 16230 && outInfo.removedChildPackages != null) 16231 ? outInfo.removedChildPackages.get(childPs.name) : null; 16232 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16233 && (replacingPackage != null 16234 && !replacingPackage.hasChildPackage(childPs.name)) 16235 ? flags & ~DELETE_KEEP_DATA : flags; 16236 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16237 deleteFlags, writeSettings); 16238 } 16239 } 16240 16241 // Delete application code and resources only for parent packages 16242 if (ps.parentPackageName == null) { 16243 if (deleteCodeAndResources && (outInfo != null)) { 16244 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16245 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16246 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16247 } 16248 } 16249 16250 return true; 16251 } 16252 16253 @Override 16254 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16255 int userId) { 16256 mContext.enforceCallingOrSelfPermission( 16257 android.Manifest.permission.DELETE_PACKAGES, null); 16258 synchronized (mPackages) { 16259 PackageSetting ps = mSettings.mPackages.get(packageName); 16260 if (ps == null) { 16261 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16262 return false; 16263 } 16264 if (!ps.getInstalled(userId)) { 16265 // Can't block uninstall for an app that is not installed or enabled. 16266 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16267 return false; 16268 } 16269 ps.setBlockUninstall(blockUninstall, userId); 16270 mSettings.writePackageRestrictionsLPr(userId); 16271 } 16272 return true; 16273 } 16274 16275 @Override 16276 public boolean getBlockUninstallForUser(String packageName, int userId) { 16277 synchronized (mPackages) { 16278 PackageSetting ps = mSettings.mPackages.get(packageName); 16279 if (ps == null) { 16280 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16281 return false; 16282 } 16283 return ps.getBlockUninstall(userId); 16284 } 16285 } 16286 16287 @Override 16288 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16289 int callingUid = Binder.getCallingUid(); 16290 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16291 throw new SecurityException( 16292 "setRequiredForSystemUser can only be run by the system or root"); 16293 } 16294 synchronized (mPackages) { 16295 PackageSetting ps = mSettings.mPackages.get(packageName); 16296 if (ps == null) { 16297 Log.w(TAG, "Package doesn't exist: " + packageName); 16298 return false; 16299 } 16300 if (systemUserApp) { 16301 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16302 } else { 16303 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16304 } 16305 mSettings.writeLPr(); 16306 } 16307 return true; 16308 } 16309 16310 /* 16311 * This method handles package deletion in general 16312 */ 16313 private boolean deletePackageLIF(String packageName, UserHandle user, 16314 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16315 PackageRemovedInfo outInfo, boolean writeSettings, 16316 PackageParser.Package replacingPackage) { 16317 if (packageName == null) { 16318 Slog.w(TAG, "Attempt to delete null packageName."); 16319 return false; 16320 } 16321 16322 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16323 16324 PackageSetting ps; 16325 16326 synchronized (mPackages) { 16327 ps = mSettings.mPackages.get(packageName); 16328 if (ps == null) { 16329 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16330 return false; 16331 } 16332 16333 if (ps.parentPackageName != null && (!isSystemApp(ps) 16334 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16335 if (DEBUG_REMOVE) { 16336 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16337 + ((user == null) ? UserHandle.USER_ALL : user)); 16338 } 16339 final int removedUserId = (user != null) ? user.getIdentifier() 16340 : UserHandle.USER_ALL; 16341 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16342 return false; 16343 } 16344 markPackageUninstalledForUserLPw(ps, user); 16345 scheduleWritePackageRestrictionsLocked(user); 16346 return true; 16347 } 16348 } 16349 16350 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16351 && user.getIdentifier() != UserHandle.USER_ALL)) { 16352 // The caller is asking that the package only be deleted for a single 16353 // user. To do this, we just mark its uninstalled state and delete 16354 // its data. If this is a system app, we only allow this to happen if 16355 // they have set the special DELETE_SYSTEM_APP which requests different 16356 // semantics than normal for uninstalling system apps. 16357 markPackageUninstalledForUserLPw(ps, user); 16358 16359 if (!isSystemApp(ps)) { 16360 // Do not uninstall the APK if an app should be cached 16361 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16362 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16363 // Other user still have this package installed, so all 16364 // we need to do is clear this user's data and save that 16365 // it is uninstalled. 16366 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16367 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16368 return false; 16369 } 16370 scheduleWritePackageRestrictionsLocked(user); 16371 return true; 16372 } else { 16373 // We need to set it back to 'installed' so the uninstall 16374 // broadcasts will be sent correctly. 16375 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16376 ps.setInstalled(true, user.getIdentifier()); 16377 } 16378 } else { 16379 // This is a system app, so we assume that the 16380 // other users still have this package installed, so all 16381 // we need to do is clear this user's data and save that 16382 // it is uninstalled. 16383 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16384 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16385 return false; 16386 } 16387 scheduleWritePackageRestrictionsLocked(user); 16388 return true; 16389 } 16390 } 16391 16392 // If we are deleting a composite package for all users, keep track 16393 // of result for each child. 16394 if (ps.childPackageNames != null && outInfo != null) { 16395 synchronized (mPackages) { 16396 final int childCount = ps.childPackageNames.size(); 16397 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16398 for (int i = 0; i < childCount; i++) { 16399 String childPackageName = ps.childPackageNames.get(i); 16400 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16401 childInfo.removedPackage = childPackageName; 16402 outInfo.removedChildPackages.put(childPackageName, childInfo); 16403 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16404 if (childPs != null) { 16405 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16406 } 16407 } 16408 } 16409 } 16410 16411 boolean ret = false; 16412 if (isSystemApp(ps)) { 16413 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16414 // When an updated system application is deleted we delete the existing resources 16415 // as well and fall back to existing code in system partition 16416 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16417 } else { 16418 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16419 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16420 outInfo, writeSettings, replacingPackage); 16421 } 16422 16423 // Take a note whether we deleted the package for all users 16424 if (outInfo != null) { 16425 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16426 if (outInfo.removedChildPackages != null) { 16427 synchronized (mPackages) { 16428 final int childCount = outInfo.removedChildPackages.size(); 16429 for (int i = 0; i < childCount; i++) { 16430 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16431 if (childInfo != null) { 16432 childInfo.removedForAllUsers = mPackages.get( 16433 childInfo.removedPackage) == null; 16434 } 16435 } 16436 } 16437 } 16438 // If we uninstalled an update to a system app there may be some 16439 // child packages that appeared as they are declared in the system 16440 // app but were not declared in the update. 16441 if (isSystemApp(ps)) { 16442 synchronized (mPackages) { 16443 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16444 final int childCount = (updatedPs.childPackageNames != null) 16445 ? updatedPs.childPackageNames.size() : 0; 16446 for (int i = 0; i < childCount; i++) { 16447 String childPackageName = updatedPs.childPackageNames.get(i); 16448 if (outInfo.removedChildPackages == null 16449 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16450 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16451 if (childPs == null) { 16452 continue; 16453 } 16454 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16455 installRes.name = childPackageName; 16456 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16457 installRes.pkg = mPackages.get(childPackageName); 16458 installRes.uid = childPs.pkg.applicationInfo.uid; 16459 if (outInfo.appearedChildPackages == null) { 16460 outInfo.appearedChildPackages = new ArrayMap<>(); 16461 } 16462 outInfo.appearedChildPackages.put(childPackageName, installRes); 16463 } 16464 } 16465 } 16466 } 16467 } 16468 16469 return ret; 16470 } 16471 16472 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16473 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16474 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16475 for (int nextUserId : userIds) { 16476 if (DEBUG_REMOVE) { 16477 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16478 } 16479 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16480 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16481 false /*hidden*/, false /*suspended*/, null, null, null, 16482 false /*blockUninstall*/, 16483 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16484 } 16485 } 16486 16487 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16488 PackageRemovedInfo outInfo) { 16489 final PackageParser.Package pkg; 16490 synchronized (mPackages) { 16491 pkg = mPackages.get(ps.name); 16492 } 16493 16494 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16495 : new int[] {userId}; 16496 for (int nextUserId : userIds) { 16497 if (DEBUG_REMOVE) { 16498 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16499 + nextUserId); 16500 } 16501 16502 destroyAppDataLIF(pkg, userId, 16503 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16504 destroyAppProfilesLIF(pkg, userId); 16505 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16506 schedulePackageCleaning(ps.name, nextUserId, false); 16507 synchronized (mPackages) { 16508 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16509 scheduleWritePackageRestrictionsLocked(nextUserId); 16510 } 16511 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16512 } 16513 } 16514 16515 if (outInfo != null) { 16516 outInfo.removedPackage = ps.name; 16517 outInfo.removedAppId = ps.appId; 16518 outInfo.removedUsers = userIds; 16519 } 16520 16521 return true; 16522 } 16523 16524 private final class ClearStorageConnection implements ServiceConnection { 16525 IMediaContainerService mContainerService; 16526 16527 @Override 16528 public void onServiceConnected(ComponentName name, IBinder service) { 16529 synchronized (this) { 16530 mContainerService = IMediaContainerService.Stub.asInterface(service); 16531 notifyAll(); 16532 } 16533 } 16534 16535 @Override 16536 public void onServiceDisconnected(ComponentName name) { 16537 } 16538 } 16539 16540 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16541 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16542 16543 final boolean mounted; 16544 if (Environment.isExternalStorageEmulated()) { 16545 mounted = true; 16546 } else { 16547 final String status = Environment.getExternalStorageState(); 16548 16549 mounted = status.equals(Environment.MEDIA_MOUNTED) 16550 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16551 } 16552 16553 if (!mounted) { 16554 return; 16555 } 16556 16557 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16558 int[] users; 16559 if (userId == UserHandle.USER_ALL) { 16560 users = sUserManager.getUserIds(); 16561 } else { 16562 users = new int[] { userId }; 16563 } 16564 final ClearStorageConnection conn = new ClearStorageConnection(); 16565 if (mContext.bindServiceAsUser( 16566 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16567 try { 16568 for (int curUser : users) { 16569 long timeout = SystemClock.uptimeMillis() + 5000; 16570 synchronized (conn) { 16571 long now; 16572 while (conn.mContainerService == null && 16573 (now = SystemClock.uptimeMillis()) < timeout) { 16574 try { 16575 conn.wait(timeout - now); 16576 } catch (InterruptedException e) { 16577 } 16578 } 16579 } 16580 if (conn.mContainerService == null) { 16581 return; 16582 } 16583 16584 final UserEnvironment userEnv = new UserEnvironment(curUser); 16585 clearDirectory(conn.mContainerService, 16586 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16587 if (allData) { 16588 clearDirectory(conn.mContainerService, 16589 userEnv.buildExternalStorageAppDataDirs(packageName)); 16590 clearDirectory(conn.mContainerService, 16591 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16592 } 16593 } 16594 } finally { 16595 mContext.unbindService(conn); 16596 } 16597 } 16598 } 16599 16600 @Override 16601 public void clearApplicationProfileData(String packageName) { 16602 enforceSystemOrRoot("Only the system can clear all profile data"); 16603 16604 final PackageParser.Package pkg; 16605 synchronized (mPackages) { 16606 pkg = mPackages.get(packageName); 16607 } 16608 16609 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16610 synchronized (mInstallLock) { 16611 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16612 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16613 true /* removeBaseMarker */); 16614 } 16615 } 16616 } 16617 16618 @Override 16619 public void clearApplicationUserData(final String packageName, 16620 final IPackageDataObserver observer, final int userId) { 16621 mContext.enforceCallingOrSelfPermission( 16622 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16623 16624 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16625 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16626 16627 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16628 throw new SecurityException("Cannot clear data for a protected package: " 16629 + packageName); 16630 } 16631 // Queue up an async operation since the package deletion may take a little while. 16632 mHandler.post(new Runnable() { 16633 public void run() { 16634 mHandler.removeCallbacks(this); 16635 final boolean succeeded; 16636 try (PackageFreezer freezer = freezePackage(packageName, 16637 "clearApplicationUserData")) { 16638 synchronized (mInstallLock) { 16639 succeeded = clearApplicationUserDataLIF(packageName, userId); 16640 } 16641 clearExternalStorageDataSync(packageName, userId, true); 16642 } 16643 if (succeeded) { 16644 // invoke DeviceStorageMonitor's update method to clear any notifications 16645 DeviceStorageMonitorInternal dsm = LocalServices 16646 .getService(DeviceStorageMonitorInternal.class); 16647 if (dsm != null) { 16648 dsm.checkMemory(); 16649 } 16650 } 16651 if(observer != null) { 16652 try { 16653 observer.onRemoveCompleted(packageName, succeeded); 16654 } catch (RemoteException e) { 16655 Log.i(TAG, "Observer no longer exists."); 16656 } 16657 } //end if observer 16658 } //end run 16659 }); 16660 } 16661 16662 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16663 if (packageName == null) { 16664 Slog.w(TAG, "Attempt to delete null packageName."); 16665 return false; 16666 } 16667 16668 // Try finding details about the requested package 16669 PackageParser.Package pkg; 16670 synchronized (mPackages) { 16671 pkg = mPackages.get(packageName); 16672 if (pkg == null) { 16673 final PackageSetting ps = mSettings.mPackages.get(packageName); 16674 if (ps != null) { 16675 pkg = ps.pkg; 16676 } 16677 } 16678 16679 if (pkg == null) { 16680 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16681 return false; 16682 } 16683 16684 PackageSetting ps = (PackageSetting) pkg.mExtras; 16685 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16686 } 16687 16688 clearAppDataLIF(pkg, userId, 16689 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16690 16691 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16692 removeKeystoreDataIfNeeded(userId, appId); 16693 16694 UserManagerInternal umInternal = getUserManagerInternal(); 16695 final int flags; 16696 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16697 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16698 } else if (umInternal.isUserRunning(userId)) { 16699 flags = StorageManager.FLAG_STORAGE_DE; 16700 } else { 16701 flags = 0; 16702 } 16703 prepareAppDataContentsLIF(pkg, userId, flags); 16704 16705 return true; 16706 } 16707 16708 /** 16709 * Reverts user permission state changes (permissions and flags) in 16710 * all packages for a given user. 16711 * 16712 * @param userId The device user for which to do a reset. 16713 */ 16714 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16715 final int packageCount = mPackages.size(); 16716 for (int i = 0; i < packageCount; i++) { 16717 PackageParser.Package pkg = mPackages.valueAt(i); 16718 PackageSetting ps = (PackageSetting) pkg.mExtras; 16719 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16720 } 16721 } 16722 16723 private void resetNetworkPolicies(int userId) { 16724 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16725 } 16726 16727 /** 16728 * Reverts user permission state changes (permissions and flags). 16729 * 16730 * @param ps The package for which to reset. 16731 * @param userId The device user for which to do a reset. 16732 */ 16733 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16734 final PackageSetting ps, final int userId) { 16735 if (ps.pkg == null) { 16736 return; 16737 } 16738 16739 // These are flags that can change base on user actions. 16740 final int userSettableMask = FLAG_PERMISSION_USER_SET 16741 | FLAG_PERMISSION_USER_FIXED 16742 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16743 | FLAG_PERMISSION_REVIEW_REQUIRED; 16744 16745 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16746 | FLAG_PERMISSION_POLICY_FIXED; 16747 16748 boolean writeInstallPermissions = false; 16749 boolean writeRuntimePermissions = false; 16750 16751 final int permissionCount = ps.pkg.requestedPermissions.size(); 16752 for (int i = 0; i < permissionCount; i++) { 16753 String permission = ps.pkg.requestedPermissions.get(i); 16754 16755 BasePermission bp = mSettings.mPermissions.get(permission); 16756 if (bp == null) { 16757 continue; 16758 } 16759 16760 // If shared user we just reset the state to which only this app contributed. 16761 if (ps.sharedUser != null) { 16762 boolean used = false; 16763 final int packageCount = ps.sharedUser.packages.size(); 16764 for (int j = 0; j < packageCount; j++) { 16765 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16766 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16767 && pkg.pkg.requestedPermissions.contains(permission)) { 16768 used = true; 16769 break; 16770 } 16771 } 16772 if (used) { 16773 continue; 16774 } 16775 } 16776 16777 PermissionsState permissionsState = ps.getPermissionsState(); 16778 16779 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16780 16781 // Always clear the user settable flags. 16782 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16783 bp.name) != null; 16784 // If permission review is enabled and this is a legacy app, mark the 16785 // permission as requiring a review as this is the initial state. 16786 int flags = 0; 16787 if (mPermissionReviewRequired 16788 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16789 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16790 } 16791 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16792 if (hasInstallState) { 16793 writeInstallPermissions = true; 16794 } else { 16795 writeRuntimePermissions = true; 16796 } 16797 } 16798 16799 // Below is only runtime permission handling. 16800 if (!bp.isRuntime()) { 16801 continue; 16802 } 16803 16804 // Never clobber system or policy. 16805 if ((oldFlags & policyOrSystemFlags) != 0) { 16806 continue; 16807 } 16808 16809 // If this permission was granted by default, make sure it is. 16810 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16811 if (permissionsState.grantRuntimePermission(bp, userId) 16812 != PERMISSION_OPERATION_FAILURE) { 16813 writeRuntimePermissions = true; 16814 } 16815 // If permission review is enabled the permissions for a legacy apps 16816 // are represented as constantly granted runtime ones, so don't revoke. 16817 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16818 // Otherwise, reset the permission. 16819 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16820 switch (revokeResult) { 16821 case PERMISSION_OPERATION_SUCCESS: 16822 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16823 writeRuntimePermissions = true; 16824 final int appId = ps.appId; 16825 mHandler.post(new Runnable() { 16826 @Override 16827 public void run() { 16828 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16829 } 16830 }); 16831 } break; 16832 } 16833 } 16834 } 16835 16836 // Synchronously write as we are taking permissions away. 16837 if (writeRuntimePermissions) { 16838 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16839 } 16840 16841 // Synchronously write as we are taking permissions away. 16842 if (writeInstallPermissions) { 16843 mSettings.writeLPr(); 16844 } 16845 } 16846 16847 /** 16848 * Remove entries from the keystore daemon. Will only remove it if the 16849 * {@code appId} is valid. 16850 */ 16851 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16852 if (appId < 0) { 16853 return; 16854 } 16855 16856 final KeyStore keyStore = KeyStore.getInstance(); 16857 if (keyStore != null) { 16858 if (userId == UserHandle.USER_ALL) { 16859 for (final int individual : sUserManager.getUserIds()) { 16860 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16861 } 16862 } else { 16863 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16864 } 16865 } else { 16866 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16867 } 16868 } 16869 16870 @Override 16871 public void deleteApplicationCacheFiles(final String packageName, 16872 final IPackageDataObserver observer) { 16873 final int userId = UserHandle.getCallingUserId(); 16874 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16875 } 16876 16877 @Override 16878 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16879 final IPackageDataObserver observer) { 16880 mContext.enforceCallingOrSelfPermission( 16881 android.Manifest.permission.DELETE_CACHE_FILES, null); 16882 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16883 /* requireFullPermission= */ true, /* checkShell= */ false, 16884 "delete application cache files"); 16885 16886 final PackageParser.Package pkg; 16887 synchronized (mPackages) { 16888 pkg = mPackages.get(packageName); 16889 } 16890 16891 // Queue up an async operation since the package deletion may take a little while. 16892 mHandler.post(new Runnable() { 16893 public void run() { 16894 synchronized (mInstallLock) { 16895 final int flags = StorageManager.FLAG_STORAGE_DE 16896 | StorageManager.FLAG_STORAGE_CE; 16897 // We're only clearing cache files, so we don't care if the 16898 // app is unfrozen and still able to run 16899 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16900 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16901 } 16902 clearExternalStorageDataSync(packageName, userId, false); 16903 if (observer != null) { 16904 try { 16905 observer.onRemoveCompleted(packageName, true); 16906 } catch (RemoteException e) { 16907 Log.i(TAG, "Observer no longer exists."); 16908 } 16909 } 16910 } 16911 }); 16912 } 16913 16914 @Override 16915 public void getPackageSizeInfo(final String packageName, int userHandle, 16916 final IPackageStatsObserver observer) { 16917 mContext.enforceCallingOrSelfPermission( 16918 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16919 if (packageName == null) { 16920 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16921 } 16922 16923 PackageStats stats = new PackageStats(packageName, userHandle); 16924 16925 /* 16926 * Queue up an async operation since the package measurement may take a 16927 * little while. 16928 */ 16929 Message msg = mHandler.obtainMessage(INIT_COPY); 16930 msg.obj = new MeasureParams(stats, observer); 16931 mHandler.sendMessage(msg); 16932 } 16933 16934 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16935 final PackageSetting ps; 16936 synchronized (mPackages) { 16937 ps = mSettings.mPackages.get(packageName); 16938 if (ps == null) { 16939 Slog.w(TAG, "Failed to find settings for " + packageName); 16940 return false; 16941 } 16942 } 16943 try { 16944 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16945 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16946 ps.getCeDataInode(userId), ps.codePathString, stats); 16947 } catch (InstallerException e) { 16948 Slog.w(TAG, String.valueOf(e)); 16949 return false; 16950 } 16951 16952 // For now, ignore code size of packages on system partition 16953 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16954 stats.codeSize = 0; 16955 } 16956 16957 return true; 16958 } 16959 16960 private int getUidTargetSdkVersionLockedLPr(int uid) { 16961 Object obj = mSettings.getUserIdLPr(uid); 16962 if (obj instanceof SharedUserSetting) { 16963 final SharedUserSetting sus = (SharedUserSetting) obj; 16964 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16965 final Iterator<PackageSetting> it = sus.packages.iterator(); 16966 while (it.hasNext()) { 16967 final PackageSetting ps = it.next(); 16968 if (ps.pkg != null) { 16969 int v = ps.pkg.applicationInfo.targetSdkVersion; 16970 if (v < vers) vers = v; 16971 } 16972 } 16973 return vers; 16974 } else if (obj instanceof PackageSetting) { 16975 final PackageSetting ps = (PackageSetting) obj; 16976 if (ps.pkg != null) { 16977 return ps.pkg.applicationInfo.targetSdkVersion; 16978 } 16979 } 16980 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16981 } 16982 16983 @Override 16984 public void addPreferredActivity(IntentFilter filter, int match, 16985 ComponentName[] set, ComponentName activity, int userId) { 16986 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16987 "Adding preferred"); 16988 } 16989 16990 private void addPreferredActivityInternal(IntentFilter filter, int match, 16991 ComponentName[] set, ComponentName activity, boolean always, int userId, 16992 String opname) { 16993 // writer 16994 int callingUid = Binder.getCallingUid(); 16995 enforceCrossUserPermission(callingUid, userId, 16996 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16997 if (filter.countActions() == 0) { 16998 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16999 return; 17000 } 17001 synchronized (mPackages) { 17002 if (mContext.checkCallingOrSelfPermission( 17003 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17004 != PackageManager.PERMISSION_GRANTED) { 17005 if (getUidTargetSdkVersionLockedLPr(callingUid) 17006 < Build.VERSION_CODES.FROYO) { 17007 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 17008 + callingUid); 17009 return; 17010 } 17011 mContext.enforceCallingOrSelfPermission( 17012 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17013 } 17014 17015 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 17016 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 17017 + userId + ":"); 17018 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17019 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 17020 scheduleWritePackageRestrictionsLocked(userId); 17021 postPreferredActivityChangedBroadcast(userId); 17022 } 17023 } 17024 17025 private void postPreferredActivityChangedBroadcast(int userId) { 17026 mHandler.post(() -> { 17027 final IActivityManager am = ActivityManagerNative.getDefault(); 17028 if (am == null) { 17029 return; 17030 } 17031 17032 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 17033 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17034 try { 17035 am.broadcastIntent(null, intent, null, null, 17036 0, null, null, null, android.app.AppOpsManager.OP_NONE, 17037 null, false, false, userId); 17038 } catch (RemoteException e) { 17039 } 17040 }); 17041 } 17042 17043 @Override 17044 public void replacePreferredActivity(IntentFilter filter, int match, 17045 ComponentName[] set, ComponentName activity, int userId) { 17046 if (filter.countActions() != 1) { 17047 throw new IllegalArgumentException( 17048 "replacePreferredActivity expects filter to have only 1 action."); 17049 } 17050 if (filter.countDataAuthorities() != 0 17051 || filter.countDataPaths() != 0 17052 || filter.countDataSchemes() > 1 17053 || filter.countDataTypes() != 0) { 17054 throw new IllegalArgumentException( 17055 "replacePreferredActivity expects filter to have no data authorities, " + 17056 "paths, or types; and at most one scheme."); 17057 } 17058 17059 final int callingUid = Binder.getCallingUid(); 17060 enforceCrossUserPermission(callingUid, userId, 17061 true /* requireFullPermission */, false /* checkShell */, 17062 "replace preferred activity"); 17063 synchronized (mPackages) { 17064 if (mContext.checkCallingOrSelfPermission( 17065 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17066 != PackageManager.PERMISSION_GRANTED) { 17067 if (getUidTargetSdkVersionLockedLPr(callingUid) 17068 < Build.VERSION_CODES.FROYO) { 17069 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 17070 + Binder.getCallingUid()); 17071 return; 17072 } 17073 mContext.enforceCallingOrSelfPermission( 17074 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17075 } 17076 17077 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17078 if (pir != null) { 17079 // Get all of the existing entries that exactly match this filter. 17080 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 17081 if (existing != null && existing.size() == 1) { 17082 PreferredActivity cur = existing.get(0); 17083 if (DEBUG_PREFERRED) { 17084 Slog.i(TAG, "Checking replace of preferred:"); 17085 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17086 if (!cur.mPref.mAlways) { 17087 Slog.i(TAG, " -- CUR; not mAlways!"); 17088 } else { 17089 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 17090 Slog.i(TAG, " -- CUR: mSet=" 17091 + Arrays.toString(cur.mPref.mSetComponents)); 17092 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 17093 Slog.i(TAG, " -- NEW: mMatch=" 17094 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 17095 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17096 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17097 } 17098 } 17099 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17100 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17101 && cur.mPref.sameSet(set)) { 17102 // Setting the preferred activity to what it happens to be already 17103 if (DEBUG_PREFERRED) { 17104 Slog.i(TAG, "Replacing with same preferred activity " 17105 + cur.mPref.mShortComponent + " for user " 17106 + userId + ":"); 17107 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17108 } 17109 return; 17110 } 17111 } 17112 17113 if (existing != null) { 17114 if (DEBUG_PREFERRED) { 17115 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17116 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17117 } 17118 for (int i = 0; i < existing.size(); i++) { 17119 PreferredActivity pa = existing.get(i); 17120 if (DEBUG_PREFERRED) { 17121 Slog.i(TAG, "Removing existing preferred activity " 17122 + pa.mPref.mComponent + ":"); 17123 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17124 } 17125 pir.removeFilter(pa); 17126 } 17127 } 17128 } 17129 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17130 "Replacing preferred"); 17131 } 17132 } 17133 17134 @Override 17135 public void clearPackagePreferredActivities(String packageName) { 17136 final int uid = Binder.getCallingUid(); 17137 // writer 17138 synchronized (mPackages) { 17139 PackageParser.Package pkg = mPackages.get(packageName); 17140 if (pkg == null || pkg.applicationInfo.uid != uid) { 17141 if (mContext.checkCallingOrSelfPermission( 17142 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17143 != PackageManager.PERMISSION_GRANTED) { 17144 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17145 < Build.VERSION_CODES.FROYO) { 17146 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17147 + Binder.getCallingUid()); 17148 return; 17149 } 17150 mContext.enforceCallingOrSelfPermission( 17151 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17152 } 17153 } 17154 17155 int user = UserHandle.getCallingUserId(); 17156 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17157 scheduleWritePackageRestrictionsLocked(user); 17158 } 17159 } 17160 } 17161 17162 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17163 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17164 ArrayList<PreferredActivity> removed = null; 17165 boolean changed = false; 17166 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17167 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17168 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17169 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17170 continue; 17171 } 17172 Iterator<PreferredActivity> it = pir.filterIterator(); 17173 while (it.hasNext()) { 17174 PreferredActivity pa = it.next(); 17175 // Mark entry for removal only if it matches the package name 17176 // and the entry is of type "always". 17177 if (packageName == null || 17178 (pa.mPref.mComponent.getPackageName().equals(packageName) 17179 && pa.mPref.mAlways)) { 17180 if (removed == null) { 17181 removed = new ArrayList<PreferredActivity>(); 17182 } 17183 removed.add(pa); 17184 } 17185 } 17186 if (removed != null) { 17187 for (int j=0; j<removed.size(); j++) { 17188 PreferredActivity pa = removed.get(j); 17189 pir.removeFilter(pa); 17190 } 17191 changed = true; 17192 } 17193 } 17194 if (changed) { 17195 postPreferredActivityChangedBroadcast(userId); 17196 } 17197 return changed; 17198 } 17199 17200 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17201 private void clearIntentFilterVerificationsLPw(int userId) { 17202 final int packageCount = mPackages.size(); 17203 for (int i = 0; i < packageCount; i++) { 17204 PackageParser.Package pkg = mPackages.valueAt(i); 17205 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17206 } 17207 } 17208 17209 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17210 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17211 if (userId == UserHandle.USER_ALL) { 17212 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17213 sUserManager.getUserIds())) { 17214 for (int oneUserId : sUserManager.getUserIds()) { 17215 scheduleWritePackageRestrictionsLocked(oneUserId); 17216 } 17217 } 17218 } else { 17219 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17220 scheduleWritePackageRestrictionsLocked(userId); 17221 } 17222 } 17223 } 17224 17225 void clearDefaultBrowserIfNeeded(String packageName) { 17226 for (int oneUserId : sUserManager.getUserIds()) { 17227 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17228 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17229 if (packageName.equals(defaultBrowserPackageName)) { 17230 setDefaultBrowserPackageName(null, oneUserId); 17231 } 17232 } 17233 } 17234 17235 @Override 17236 public void resetApplicationPreferences(int userId) { 17237 mContext.enforceCallingOrSelfPermission( 17238 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17239 final long identity = Binder.clearCallingIdentity(); 17240 // writer 17241 try { 17242 synchronized (mPackages) { 17243 clearPackagePreferredActivitiesLPw(null, userId); 17244 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17245 // TODO: We have to reset the default SMS and Phone. This requires 17246 // significant refactoring to keep all default apps in the package 17247 // manager (cleaner but more work) or have the services provide 17248 // callbacks to the package manager to request a default app reset. 17249 applyFactoryDefaultBrowserLPw(userId); 17250 clearIntentFilterVerificationsLPw(userId); 17251 primeDomainVerificationsLPw(userId); 17252 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17253 scheduleWritePackageRestrictionsLocked(userId); 17254 } 17255 resetNetworkPolicies(userId); 17256 } finally { 17257 Binder.restoreCallingIdentity(identity); 17258 } 17259 } 17260 17261 @Override 17262 public int getPreferredActivities(List<IntentFilter> outFilters, 17263 List<ComponentName> outActivities, String packageName) { 17264 17265 int num = 0; 17266 final int userId = UserHandle.getCallingUserId(); 17267 // reader 17268 synchronized (mPackages) { 17269 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17270 if (pir != null) { 17271 final Iterator<PreferredActivity> it = pir.filterIterator(); 17272 while (it.hasNext()) { 17273 final PreferredActivity pa = it.next(); 17274 if (packageName == null 17275 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17276 && pa.mPref.mAlways)) { 17277 if (outFilters != null) { 17278 outFilters.add(new IntentFilter(pa)); 17279 } 17280 if (outActivities != null) { 17281 outActivities.add(pa.mPref.mComponent); 17282 } 17283 } 17284 } 17285 } 17286 } 17287 17288 return num; 17289 } 17290 17291 @Override 17292 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17293 int userId) { 17294 int callingUid = Binder.getCallingUid(); 17295 if (callingUid != Process.SYSTEM_UID) { 17296 throw new SecurityException( 17297 "addPersistentPreferredActivity can only be run by the system"); 17298 } 17299 if (filter.countActions() == 0) { 17300 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17301 return; 17302 } 17303 synchronized (mPackages) { 17304 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17305 ":"); 17306 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17307 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17308 new PersistentPreferredActivity(filter, activity)); 17309 scheduleWritePackageRestrictionsLocked(userId); 17310 postPreferredActivityChangedBroadcast(userId); 17311 } 17312 } 17313 17314 @Override 17315 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17316 int callingUid = Binder.getCallingUid(); 17317 if (callingUid != Process.SYSTEM_UID) { 17318 throw new SecurityException( 17319 "clearPackagePersistentPreferredActivities can only be run by the system"); 17320 } 17321 ArrayList<PersistentPreferredActivity> removed = null; 17322 boolean changed = false; 17323 synchronized (mPackages) { 17324 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17325 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17326 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17327 .valueAt(i); 17328 if (userId != thisUserId) { 17329 continue; 17330 } 17331 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17332 while (it.hasNext()) { 17333 PersistentPreferredActivity ppa = it.next(); 17334 // Mark entry for removal only if it matches the package name. 17335 if (ppa.mComponent.getPackageName().equals(packageName)) { 17336 if (removed == null) { 17337 removed = new ArrayList<PersistentPreferredActivity>(); 17338 } 17339 removed.add(ppa); 17340 } 17341 } 17342 if (removed != null) { 17343 for (int j=0; j<removed.size(); j++) { 17344 PersistentPreferredActivity ppa = removed.get(j); 17345 ppir.removeFilter(ppa); 17346 } 17347 changed = true; 17348 } 17349 } 17350 17351 if (changed) { 17352 scheduleWritePackageRestrictionsLocked(userId); 17353 postPreferredActivityChangedBroadcast(userId); 17354 } 17355 } 17356 } 17357 17358 /** 17359 * Common machinery for picking apart a restored XML blob and passing 17360 * it to a caller-supplied functor to be applied to the running system. 17361 */ 17362 private void restoreFromXml(XmlPullParser parser, int userId, 17363 String expectedStartTag, BlobXmlRestorer functor) 17364 throws IOException, XmlPullParserException { 17365 int type; 17366 while ((type = parser.next()) != XmlPullParser.START_TAG 17367 && type != XmlPullParser.END_DOCUMENT) { 17368 } 17369 if (type != XmlPullParser.START_TAG) { 17370 // oops didn't find a start tag?! 17371 if (DEBUG_BACKUP) { 17372 Slog.e(TAG, "Didn't find start tag during restore"); 17373 } 17374 return; 17375 } 17376Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17377 // this is supposed to be TAG_PREFERRED_BACKUP 17378 if (!expectedStartTag.equals(parser.getName())) { 17379 if (DEBUG_BACKUP) { 17380 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17381 } 17382 return; 17383 } 17384 17385 // skip interfering stuff, then we're aligned with the backing implementation 17386 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17387Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17388 functor.apply(parser, userId); 17389 } 17390 17391 private interface BlobXmlRestorer { 17392 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17393 } 17394 17395 /** 17396 * Non-Binder method, support for the backup/restore mechanism: write the 17397 * full set of preferred activities in its canonical XML format. Returns the 17398 * XML output as a byte array, or null if there is none. 17399 */ 17400 @Override 17401 public byte[] getPreferredActivityBackup(int userId) { 17402 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17403 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17404 } 17405 17406 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17407 try { 17408 final XmlSerializer serializer = new FastXmlSerializer(); 17409 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17410 serializer.startDocument(null, true); 17411 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17412 17413 synchronized (mPackages) { 17414 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17415 } 17416 17417 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17418 serializer.endDocument(); 17419 serializer.flush(); 17420 } catch (Exception e) { 17421 if (DEBUG_BACKUP) { 17422 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17423 } 17424 return null; 17425 } 17426 17427 return dataStream.toByteArray(); 17428 } 17429 17430 @Override 17431 public void restorePreferredActivities(byte[] backup, int userId) { 17432 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17433 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17434 } 17435 17436 try { 17437 final XmlPullParser parser = Xml.newPullParser(); 17438 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17439 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17440 new BlobXmlRestorer() { 17441 @Override 17442 public void apply(XmlPullParser parser, int userId) 17443 throws XmlPullParserException, IOException { 17444 synchronized (mPackages) { 17445 mSettings.readPreferredActivitiesLPw(parser, userId); 17446 } 17447 } 17448 } ); 17449 } catch (Exception e) { 17450 if (DEBUG_BACKUP) { 17451 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17452 } 17453 } 17454 } 17455 17456 /** 17457 * Non-Binder method, support for the backup/restore mechanism: write the 17458 * default browser (etc) settings in its canonical XML format. Returns the default 17459 * browser XML representation as a byte array, or null if there is none. 17460 */ 17461 @Override 17462 public byte[] getDefaultAppsBackup(int userId) { 17463 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17464 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17465 } 17466 17467 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17468 try { 17469 final XmlSerializer serializer = new FastXmlSerializer(); 17470 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17471 serializer.startDocument(null, true); 17472 serializer.startTag(null, TAG_DEFAULT_APPS); 17473 17474 synchronized (mPackages) { 17475 mSettings.writeDefaultAppsLPr(serializer, userId); 17476 } 17477 17478 serializer.endTag(null, TAG_DEFAULT_APPS); 17479 serializer.endDocument(); 17480 serializer.flush(); 17481 } catch (Exception e) { 17482 if (DEBUG_BACKUP) { 17483 Slog.e(TAG, "Unable to write default apps for backup", e); 17484 } 17485 return null; 17486 } 17487 17488 return dataStream.toByteArray(); 17489 } 17490 17491 @Override 17492 public void restoreDefaultApps(byte[] backup, int userId) { 17493 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17494 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17495 } 17496 17497 try { 17498 final XmlPullParser parser = Xml.newPullParser(); 17499 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17500 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17501 new BlobXmlRestorer() { 17502 @Override 17503 public void apply(XmlPullParser parser, int userId) 17504 throws XmlPullParserException, IOException { 17505 synchronized (mPackages) { 17506 mSettings.readDefaultAppsLPw(parser, userId); 17507 } 17508 } 17509 } ); 17510 } catch (Exception e) { 17511 if (DEBUG_BACKUP) { 17512 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17513 } 17514 } 17515 } 17516 17517 @Override 17518 public byte[] getIntentFilterVerificationBackup(int userId) { 17519 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17520 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17521 } 17522 17523 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17524 try { 17525 final XmlSerializer serializer = new FastXmlSerializer(); 17526 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17527 serializer.startDocument(null, true); 17528 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17529 17530 synchronized (mPackages) { 17531 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17532 } 17533 17534 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17535 serializer.endDocument(); 17536 serializer.flush(); 17537 } catch (Exception e) { 17538 if (DEBUG_BACKUP) { 17539 Slog.e(TAG, "Unable to write default apps for backup", e); 17540 } 17541 return null; 17542 } 17543 17544 return dataStream.toByteArray(); 17545 } 17546 17547 @Override 17548 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17549 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17550 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17551 } 17552 17553 try { 17554 final XmlPullParser parser = Xml.newPullParser(); 17555 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17556 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17557 new BlobXmlRestorer() { 17558 @Override 17559 public void apply(XmlPullParser parser, int userId) 17560 throws XmlPullParserException, IOException { 17561 synchronized (mPackages) { 17562 mSettings.readAllDomainVerificationsLPr(parser, userId); 17563 mSettings.writeLPr(); 17564 } 17565 } 17566 } ); 17567 } catch (Exception e) { 17568 if (DEBUG_BACKUP) { 17569 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17570 } 17571 } 17572 } 17573 17574 @Override 17575 public byte[] getPermissionGrantBackup(int userId) { 17576 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17577 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17578 } 17579 17580 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17581 try { 17582 final XmlSerializer serializer = new FastXmlSerializer(); 17583 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17584 serializer.startDocument(null, true); 17585 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17586 17587 synchronized (mPackages) { 17588 serializeRuntimePermissionGrantsLPr(serializer, userId); 17589 } 17590 17591 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17592 serializer.endDocument(); 17593 serializer.flush(); 17594 } catch (Exception e) { 17595 if (DEBUG_BACKUP) { 17596 Slog.e(TAG, "Unable to write default apps for backup", e); 17597 } 17598 return null; 17599 } 17600 17601 return dataStream.toByteArray(); 17602 } 17603 17604 @Override 17605 public void restorePermissionGrants(byte[] backup, int userId) { 17606 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17607 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17608 } 17609 17610 try { 17611 final XmlPullParser parser = Xml.newPullParser(); 17612 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17613 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17614 new BlobXmlRestorer() { 17615 @Override 17616 public void apply(XmlPullParser parser, int userId) 17617 throws XmlPullParserException, IOException { 17618 synchronized (mPackages) { 17619 processRestoredPermissionGrantsLPr(parser, userId); 17620 } 17621 } 17622 } ); 17623 } catch (Exception e) { 17624 if (DEBUG_BACKUP) { 17625 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17626 } 17627 } 17628 } 17629 17630 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17631 throws IOException { 17632 serializer.startTag(null, TAG_ALL_GRANTS); 17633 17634 final int N = mSettings.mPackages.size(); 17635 for (int i = 0; i < N; i++) { 17636 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17637 boolean pkgGrantsKnown = false; 17638 17639 PermissionsState packagePerms = ps.getPermissionsState(); 17640 17641 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17642 final int grantFlags = state.getFlags(); 17643 // only look at grants that are not system/policy fixed 17644 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17645 final boolean isGranted = state.isGranted(); 17646 // And only back up the user-twiddled state bits 17647 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17648 final String packageName = mSettings.mPackages.keyAt(i); 17649 if (!pkgGrantsKnown) { 17650 serializer.startTag(null, TAG_GRANT); 17651 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17652 pkgGrantsKnown = true; 17653 } 17654 17655 final boolean userSet = 17656 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17657 final boolean userFixed = 17658 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17659 final boolean revoke = 17660 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17661 17662 serializer.startTag(null, TAG_PERMISSION); 17663 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17664 if (isGranted) { 17665 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17666 } 17667 if (userSet) { 17668 serializer.attribute(null, ATTR_USER_SET, "true"); 17669 } 17670 if (userFixed) { 17671 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17672 } 17673 if (revoke) { 17674 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17675 } 17676 serializer.endTag(null, TAG_PERMISSION); 17677 } 17678 } 17679 } 17680 17681 if (pkgGrantsKnown) { 17682 serializer.endTag(null, TAG_GRANT); 17683 } 17684 } 17685 17686 serializer.endTag(null, TAG_ALL_GRANTS); 17687 } 17688 17689 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17690 throws XmlPullParserException, IOException { 17691 String pkgName = null; 17692 int outerDepth = parser.getDepth(); 17693 int type; 17694 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17695 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17696 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17697 continue; 17698 } 17699 17700 final String tagName = parser.getName(); 17701 if (tagName.equals(TAG_GRANT)) { 17702 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17703 if (DEBUG_BACKUP) { 17704 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17705 } 17706 } else if (tagName.equals(TAG_PERMISSION)) { 17707 17708 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17709 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17710 17711 int newFlagSet = 0; 17712 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17713 newFlagSet |= FLAG_PERMISSION_USER_SET; 17714 } 17715 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17716 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17717 } 17718 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17719 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17720 } 17721 if (DEBUG_BACKUP) { 17722 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17723 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17724 } 17725 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17726 if (ps != null) { 17727 // Already installed so we apply the grant immediately 17728 if (DEBUG_BACKUP) { 17729 Slog.v(TAG, " + already installed; applying"); 17730 } 17731 PermissionsState perms = ps.getPermissionsState(); 17732 BasePermission bp = mSettings.mPermissions.get(permName); 17733 if (bp != null) { 17734 if (isGranted) { 17735 perms.grantRuntimePermission(bp, userId); 17736 } 17737 if (newFlagSet != 0) { 17738 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17739 } 17740 } 17741 } else { 17742 // Need to wait for post-restore install to apply the grant 17743 if (DEBUG_BACKUP) { 17744 Slog.v(TAG, " - not yet installed; saving for later"); 17745 } 17746 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17747 isGranted, newFlagSet, userId); 17748 } 17749 } else { 17750 PackageManagerService.reportSettingsProblem(Log.WARN, 17751 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17752 XmlUtils.skipCurrentTag(parser); 17753 } 17754 } 17755 17756 scheduleWriteSettingsLocked(); 17757 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17758 } 17759 17760 @Override 17761 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17762 int sourceUserId, int targetUserId, int flags) { 17763 mContext.enforceCallingOrSelfPermission( 17764 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17765 int callingUid = Binder.getCallingUid(); 17766 enforceOwnerRights(ownerPackage, callingUid); 17767 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17768 if (intentFilter.countActions() == 0) { 17769 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17770 return; 17771 } 17772 synchronized (mPackages) { 17773 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17774 ownerPackage, targetUserId, flags); 17775 CrossProfileIntentResolver resolver = 17776 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17777 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17778 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17779 if (existing != null) { 17780 int size = existing.size(); 17781 for (int i = 0; i < size; i++) { 17782 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17783 return; 17784 } 17785 } 17786 } 17787 resolver.addFilter(newFilter); 17788 scheduleWritePackageRestrictionsLocked(sourceUserId); 17789 } 17790 } 17791 17792 @Override 17793 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17794 mContext.enforceCallingOrSelfPermission( 17795 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17796 int callingUid = Binder.getCallingUid(); 17797 enforceOwnerRights(ownerPackage, callingUid); 17798 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17799 synchronized (mPackages) { 17800 CrossProfileIntentResolver resolver = 17801 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17802 ArraySet<CrossProfileIntentFilter> set = 17803 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17804 for (CrossProfileIntentFilter filter : set) { 17805 if (filter.getOwnerPackage().equals(ownerPackage)) { 17806 resolver.removeFilter(filter); 17807 } 17808 } 17809 scheduleWritePackageRestrictionsLocked(sourceUserId); 17810 } 17811 } 17812 17813 // Enforcing that callingUid is owning pkg on userId 17814 private void enforceOwnerRights(String pkg, int callingUid) { 17815 // The system owns everything. 17816 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17817 return; 17818 } 17819 int callingUserId = UserHandle.getUserId(callingUid); 17820 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17821 if (pi == null) { 17822 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17823 + callingUserId); 17824 } 17825 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17826 throw new SecurityException("Calling uid " + callingUid 17827 + " does not own package " + pkg); 17828 } 17829 } 17830 17831 @Override 17832 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17833 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17834 } 17835 17836 private Intent getHomeIntent() { 17837 Intent intent = new Intent(Intent.ACTION_MAIN); 17838 intent.addCategory(Intent.CATEGORY_HOME); 17839 intent.addCategory(Intent.CATEGORY_DEFAULT); 17840 return intent; 17841 } 17842 17843 private IntentFilter getHomeFilter() { 17844 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17845 filter.addCategory(Intent.CATEGORY_HOME); 17846 filter.addCategory(Intent.CATEGORY_DEFAULT); 17847 return filter; 17848 } 17849 17850 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17851 int userId) { 17852 Intent intent = getHomeIntent(); 17853 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17854 PackageManager.GET_META_DATA, userId); 17855 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17856 true, false, false, userId); 17857 17858 allHomeCandidates.clear(); 17859 if (list != null) { 17860 for (ResolveInfo ri : list) { 17861 allHomeCandidates.add(ri); 17862 } 17863 } 17864 return (preferred == null || preferred.activityInfo == null) 17865 ? null 17866 : new ComponentName(preferred.activityInfo.packageName, 17867 preferred.activityInfo.name); 17868 } 17869 17870 @Override 17871 public void setHomeActivity(ComponentName comp, int userId) { 17872 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17873 getHomeActivitiesAsUser(homeActivities, userId); 17874 17875 boolean found = false; 17876 17877 final int size = homeActivities.size(); 17878 final ComponentName[] set = new ComponentName[size]; 17879 for (int i = 0; i < size; i++) { 17880 final ResolveInfo candidate = homeActivities.get(i); 17881 final ActivityInfo info = candidate.activityInfo; 17882 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17883 set[i] = activityName; 17884 if (!found && activityName.equals(comp)) { 17885 found = true; 17886 } 17887 } 17888 if (!found) { 17889 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17890 + userId); 17891 } 17892 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17893 set, comp, userId); 17894 } 17895 17896 private @Nullable String getSetupWizardPackageName() { 17897 final Intent intent = new Intent(Intent.ACTION_MAIN); 17898 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17899 17900 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17901 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17902 | MATCH_DISABLED_COMPONENTS, 17903 UserHandle.myUserId()); 17904 if (matches.size() == 1) { 17905 return matches.get(0).getComponentInfo().packageName; 17906 } else { 17907 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17908 + ": matches=" + matches); 17909 return null; 17910 } 17911 } 17912 17913 private @Nullable String getStorageManagerPackageName() { 17914 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 17915 17916 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17917 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17918 | MATCH_DISABLED_COMPONENTS, 17919 UserHandle.myUserId()); 17920 if (matches.size() == 1) { 17921 return matches.get(0).getComponentInfo().packageName; 17922 } else { 17923 Slog.e(TAG, "There should probably be exactly one storage manager; found " 17924 + matches.size() + ": matches=" + matches); 17925 return null; 17926 } 17927 } 17928 17929 @Override 17930 public void setApplicationEnabledSetting(String appPackageName, 17931 int newState, int flags, int userId, String callingPackage) { 17932 if (!sUserManager.exists(userId)) return; 17933 if (callingPackage == null) { 17934 callingPackage = Integer.toString(Binder.getCallingUid()); 17935 } 17936 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17937 } 17938 17939 @Override 17940 public void setComponentEnabledSetting(ComponentName componentName, 17941 int newState, int flags, int userId) { 17942 if (!sUserManager.exists(userId)) return; 17943 setEnabledSetting(componentName.getPackageName(), 17944 componentName.getClassName(), newState, flags, userId, null); 17945 } 17946 17947 private void setEnabledSetting(final String packageName, String className, int newState, 17948 final int flags, int userId, String callingPackage) { 17949 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17950 || newState == COMPONENT_ENABLED_STATE_ENABLED 17951 || newState == COMPONENT_ENABLED_STATE_DISABLED 17952 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17953 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17954 throw new IllegalArgumentException("Invalid new component state: " 17955 + newState); 17956 } 17957 PackageSetting pkgSetting; 17958 final int uid = Binder.getCallingUid(); 17959 final int permission; 17960 if (uid == Process.SYSTEM_UID) { 17961 permission = PackageManager.PERMISSION_GRANTED; 17962 } else { 17963 permission = mContext.checkCallingOrSelfPermission( 17964 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17965 } 17966 enforceCrossUserPermission(uid, userId, 17967 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17968 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17969 boolean sendNow = false; 17970 boolean isApp = (className == null); 17971 String componentName = isApp ? packageName : className; 17972 int packageUid = -1; 17973 ArrayList<String> components; 17974 17975 // writer 17976 synchronized (mPackages) { 17977 pkgSetting = mSettings.mPackages.get(packageName); 17978 if (pkgSetting == null) { 17979 if (className == null) { 17980 throw new IllegalArgumentException("Unknown package: " + packageName); 17981 } 17982 throw new IllegalArgumentException( 17983 "Unknown component: " + packageName + "/" + className); 17984 } 17985 } 17986 17987 // Limit who can change which apps 17988 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17989 // Don't allow apps that don't have permission to modify other apps 17990 if (!allowedByPermission) { 17991 throw new SecurityException( 17992 "Permission Denial: attempt to change component state from pid=" 17993 + Binder.getCallingPid() 17994 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17995 } 17996 // Don't allow changing protected packages. 17997 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17998 throw new SecurityException("Cannot disable a protected package: " + packageName); 17999 } 18000 } 18001 18002 synchronized (mPackages) { 18003 if (uid == Process.SHELL_UID) { 18004 // Shell can only change whole packages between ENABLED and DISABLED_USER states 18005 int oldState = pkgSetting.getEnabled(userId); 18006 if (className == null 18007 && 18008 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 18009 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 18010 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 18011 && 18012 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18013 || newState == COMPONENT_ENABLED_STATE_DEFAULT 18014 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 18015 // ok 18016 } else { 18017 throw new SecurityException( 18018 "Shell cannot change component state for " + packageName + "/" 18019 + className + " to " + newState); 18020 } 18021 } 18022 if (className == null) { 18023 // We're dealing with an application/package level state change 18024 if (pkgSetting.getEnabled(userId) == newState) { 18025 // Nothing to do 18026 return; 18027 } 18028 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 18029 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 18030 // Don't care about who enables an app. 18031 callingPackage = null; 18032 } 18033 pkgSetting.setEnabled(newState, userId, callingPackage); 18034 // pkgSetting.pkg.mSetEnabled = newState; 18035 } else { 18036 // We're dealing with a component level state change 18037 // First, verify that this is a valid class name. 18038 PackageParser.Package pkg = pkgSetting.pkg; 18039 if (pkg == null || !pkg.hasComponentClassName(className)) { 18040 if (pkg != null && 18041 pkg.applicationInfo.targetSdkVersion >= 18042 Build.VERSION_CODES.JELLY_BEAN) { 18043 throw new IllegalArgumentException("Component class " + className 18044 + " does not exist in " + packageName); 18045 } else { 18046 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 18047 + className + " does not exist in " + packageName); 18048 } 18049 } 18050 switch (newState) { 18051 case COMPONENT_ENABLED_STATE_ENABLED: 18052 if (!pkgSetting.enableComponentLPw(className, userId)) { 18053 return; 18054 } 18055 break; 18056 case COMPONENT_ENABLED_STATE_DISABLED: 18057 if (!pkgSetting.disableComponentLPw(className, userId)) { 18058 return; 18059 } 18060 break; 18061 case COMPONENT_ENABLED_STATE_DEFAULT: 18062 if (!pkgSetting.restoreComponentLPw(className, userId)) { 18063 return; 18064 } 18065 break; 18066 default: 18067 Slog.e(TAG, "Invalid new component state: " + newState); 18068 return; 18069 } 18070 } 18071 scheduleWritePackageRestrictionsLocked(userId); 18072 components = mPendingBroadcasts.get(userId, packageName); 18073 final boolean newPackage = components == null; 18074 if (newPackage) { 18075 components = new ArrayList<String>(); 18076 } 18077 if (!components.contains(componentName)) { 18078 components.add(componentName); 18079 } 18080 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 18081 sendNow = true; 18082 // Purge entry from pending broadcast list if another one exists already 18083 // since we are sending one right away. 18084 mPendingBroadcasts.remove(userId, packageName); 18085 } else { 18086 if (newPackage) { 18087 mPendingBroadcasts.put(userId, packageName, components); 18088 } 18089 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 18090 // Schedule a message 18091 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 18092 } 18093 } 18094 } 18095 18096 long callingId = Binder.clearCallingIdentity(); 18097 try { 18098 if (sendNow) { 18099 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18100 sendPackageChangedBroadcast(packageName, 18101 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18102 } 18103 } finally { 18104 Binder.restoreCallingIdentity(callingId); 18105 } 18106 } 18107 18108 @Override 18109 public void flushPackageRestrictionsAsUser(int userId) { 18110 if (!sUserManager.exists(userId)) { 18111 return; 18112 } 18113 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18114 false /* checkShell */, "flushPackageRestrictions"); 18115 synchronized (mPackages) { 18116 mSettings.writePackageRestrictionsLPr(userId); 18117 mDirtyUsers.remove(userId); 18118 if (mDirtyUsers.isEmpty()) { 18119 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18120 } 18121 } 18122 } 18123 18124 private void sendPackageChangedBroadcast(String packageName, 18125 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18126 if (DEBUG_INSTALL) 18127 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18128 + componentNames); 18129 Bundle extras = new Bundle(4); 18130 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18131 String nameList[] = new String[componentNames.size()]; 18132 componentNames.toArray(nameList); 18133 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18134 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18135 extras.putInt(Intent.EXTRA_UID, packageUid); 18136 // If this is not reporting a change of the overall package, then only send it 18137 // to registered receivers. We don't want to launch a swath of apps for every 18138 // little component state change. 18139 final int flags = !componentNames.contains(packageName) 18140 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18141 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18142 new int[] {UserHandle.getUserId(packageUid)}); 18143 } 18144 18145 @Override 18146 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18147 if (!sUserManager.exists(userId)) return; 18148 final int uid = Binder.getCallingUid(); 18149 final int permission = mContext.checkCallingOrSelfPermission( 18150 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18151 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18152 enforceCrossUserPermission(uid, userId, 18153 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18154 // writer 18155 synchronized (mPackages) { 18156 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18157 allowedByPermission, uid, userId)) { 18158 scheduleWritePackageRestrictionsLocked(userId); 18159 } 18160 } 18161 } 18162 18163 @Override 18164 public String getInstallerPackageName(String packageName) { 18165 // reader 18166 synchronized (mPackages) { 18167 return mSettings.getInstallerPackageNameLPr(packageName); 18168 } 18169 } 18170 18171 public boolean isOrphaned(String packageName) { 18172 // reader 18173 synchronized (mPackages) { 18174 return mSettings.isOrphaned(packageName); 18175 } 18176 } 18177 18178 @Override 18179 public int getApplicationEnabledSetting(String packageName, int userId) { 18180 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18181 int uid = Binder.getCallingUid(); 18182 enforceCrossUserPermission(uid, userId, 18183 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18184 // reader 18185 synchronized (mPackages) { 18186 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18187 } 18188 } 18189 18190 @Override 18191 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18192 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18193 int uid = Binder.getCallingUid(); 18194 enforceCrossUserPermission(uid, userId, 18195 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18196 // reader 18197 synchronized (mPackages) { 18198 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18199 } 18200 } 18201 18202 @Override 18203 public void enterSafeMode() { 18204 enforceSystemOrRoot("Only the system can request entering safe mode"); 18205 18206 if (!mSystemReady) { 18207 mSafeMode = true; 18208 } 18209 } 18210 18211 @Override 18212 public void systemReady() { 18213 mSystemReady = true; 18214 18215 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18216 // disabled after already being started. 18217 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18218 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18219 18220 // Read the compatibilty setting when the system is ready. 18221 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18222 mContext.getContentResolver(), 18223 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18224 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18225 if (DEBUG_SETTINGS) { 18226 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18227 } 18228 18229 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18230 18231 synchronized (mPackages) { 18232 // Verify that all of the preferred activity components actually 18233 // exist. It is possible for applications to be updated and at 18234 // that point remove a previously declared activity component that 18235 // had been set as a preferred activity. We try to clean this up 18236 // the next time we encounter that preferred activity, but it is 18237 // possible for the user flow to never be able to return to that 18238 // situation so here we do a sanity check to make sure we haven't 18239 // left any junk around. 18240 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18241 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18242 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18243 removed.clear(); 18244 for (PreferredActivity pa : pir.filterSet()) { 18245 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18246 removed.add(pa); 18247 } 18248 } 18249 if (removed.size() > 0) { 18250 for (int r=0; r<removed.size(); r++) { 18251 PreferredActivity pa = removed.get(r); 18252 Slog.w(TAG, "Removing dangling preferred activity: " 18253 + pa.mPref.mComponent); 18254 pir.removeFilter(pa); 18255 } 18256 mSettings.writePackageRestrictionsLPr( 18257 mSettings.mPreferredActivities.keyAt(i)); 18258 } 18259 } 18260 18261 for (int userId : UserManagerService.getInstance().getUserIds()) { 18262 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18263 grantPermissionsUserIds = ArrayUtils.appendInt( 18264 grantPermissionsUserIds, userId); 18265 } 18266 } 18267 } 18268 sUserManager.systemReady(); 18269 18270 // If we upgraded grant all default permissions before kicking off. 18271 for (int userId : grantPermissionsUserIds) { 18272 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18273 } 18274 18275 // If we did not grant default permissions, we preload from this the 18276 // default permission exceptions lazily to ensure we don't hit the 18277 // disk on a new user creation. 18278 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18279 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18280 } 18281 18282 // Kick off any messages waiting for system ready 18283 if (mPostSystemReadyMessages != null) { 18284 for (Message msg : mPostSystemReadyMessages) { 18285 msg.sendToTarget(); 18286 } 18287 mPostSystemReadyMessages = null; 18288 } 18289 18290 // Watch for external volumes that come and go over time 18291 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18292 storage.registerListener(mStorageListener); 18293 18294 mInstallerService.systemReady(); 18295 mPackageDexOptimizer.systemReady(); 18296 18297 MountServiceInternal mountServiceInternal = LocalServices.getService( 18298 MountServiceInternal.class); 18299 mountServiceInternal.addExternalStoragePolicy( 18300 new MountServiceInternal.ExternalStorageMountPolicy() { 18301 @Override 18302 public int getMountMode(int uid, String packageName) { 18303 if (Process.isIsolated(uid)) { 18304 return Zygote.MOUNT_EXTERNAL_NONE; 18305 } 18306 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18307 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18308 } 18309 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18310 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18311 } 18312 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18313 return Zygote.MOUNT_EXTERNAL_READ; 18314 } 18315 return Zygote.MOUNT_EXTERNAL_WRITE; 18316 } 18317 18318 @Override 18319 public boolean hasExternalStorage(int uid, String packageName) { 18320 return true; 18321 } 18322 }); 18323 18324 // Now that we're mostly running, clean up stale users and apps 18325 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18326 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18327 } 18328 18329 @Override 18330 public boolean isSafeMode() { 18331 return mSafeMode; 18332 } 18333 18334 @Override 18335 public boolean hasSystemUidErrors() { 18336 return mHasSystemUidErrors; 18337 } 18338 18339 static String arrayToString(int[] array) { 18340 StringBuffer buf = new StringBuffer(128); 18341 buf.append('['); 18342 if (array != null) { 18343 for (int i=0; i<array.length; i++) { 18344 if (i > 0) buf.append(", "); 18345 buf.append(array[i]); 18346 } 18347 } 18348 buf.append(']'); 18349 return buf.toString(); 18350 } 18351 18352 static class DumpState { 18353 public static final int DUMP_LIBS = 1 << 0; 18354 public static final int DUMP_FEATURES = 1 << 1; 18355 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18356 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18357 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18358 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18359 public static final int DUMP_PERMISSIONS = 1 << 6; 18360 public static final int DUMP_PACKAGES = 1 << 7; 18361 public static final int DUMP_SHARED_USERS = 1 << 8; 18362 public static final int DUMP_MESSAGES = 1 << 9; 18363 public static final int DUMP_PROVIDERS = 1 << 10; 18364 public static final int DUMP_VERIFIERS = 1 << 11; 18365 public static final int DUMP_PREFERRED = 1 << 12; 18366 public static final int DUMP_PREFERRED_XML = 1 << 13; 18367 public static final int DUMP_KEYSETS = 1 << 14; 18368 public static final int DUMP_VERSION = 1 << 15; 18369 public static final int DUMP_INSTALLS = 1 << 16; 18370 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18371 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18372 public static final int DUMP_FROZEN = 1 << 19; 18373 public static final int DUMP_DEXOPT = 1 << 20; 18374 public static final int DUMP_COMPILER_STATS = 1 << 21; 18375 18376 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18377 18378 private int mTypes; 18379 18380 private int mOptions; 18381 18382 private boolean mTitlePrinted; 18383 18384 private SharedUserSetting mSharedUser; 18385 18386 public boolean isDumping(int type) { 18387 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18388 return true; 18389 } 18390 18391 return (mTypes & type) != 0; 18392 } 18393 18394 public void setDump(int type) { 18395 mTypes |= type; 18396 } 18397 18398 public boolean isOptionEnabled(int option) { 18399 return (mOptions & option) != 0; 18400 } 18401 18402 public void setOptionEnabled(int option) { 18403 mOptions |= option; 18404 } 18405 18406 public boolean onTitlePrinted() { 18407 final boolean printed = mTitlePrinted; 18408 mTitlePrinted = true; 18409 return printed; 18410 } 18411 18412 public boolean getTitlePrinted() { 18413 return mTitlePrinted; 18414 } 18415 18416 public void setTitlePrinted(boolean enabled) { 18417 mTitlePrinted = enabled; 18418 } 18419 18420 public SharedUserSetting getSharedUser() { 18421 return mSharedUser; 18422 } 18423 18424 public void setSharedUser(SharedUserSetting user) { 18425 mSharedUser = user; 18426 } 18427 } 18428 18429 @Override 18430 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18431 FileDescriptor err, String[] args, ShellCallback callback, 18432 ResultReceiver resultReceiver) { 18433 (new PackageManagerShellCommand(this)).exec( 18434 this, in, out, err, args, callback, resultReceiver); 18435 } 18436 18437 @Override 18438 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18439 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18440 != PackageManager.PERMISSION_GRANTED) { 18441 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18442 + Binder.getCallingPid() 18443 + ", uid=" + Binder.getCallingUid() 18444 + " without permission " 18445 + android.Manifest.permission.DUMP); 18446 return; 18447 } 18448 18449 DumpState dumpState = new DumpState(); 18450 boolean fullPreferred = false; 18451 boolean checkin = false; 18452 18453 String packageName = null; 18454 ArraySet<String> permissionNames = null; 18455 18456 int opti = 0; 18457 while (opti < args.length) { 18458 String opt = args[opti]; 18459 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18460 break; 18461 } 18462 opti++; 18463 18464 if ("-a".equals(opt)) { 18465 // Right now we only know how to print all. 18466 } else if ("-h".equals(opt)) { 18467 pw.println("Package manager dump options:"); 18468 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18469 pw.println(" --checkin: dump for a checkin"); 18470 pw.println(" -f: print details of intent filters"); 18471 pw.println(" -h: print this help"); 18472 pw.println(" cmd may be one of:"); 18473 pw.println(" l[ibraries]: list known shared libraries"); 18474 pw.println(" f[eatures]: list device features"); 18475 pw.println(" k[eysets]: print known keysets"); 18476 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18477 pw.println(" perm[issions]: dump permissions"); 18478 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18479 pw.println(" pref[erred]: print preferred package settings"); 18480 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18481 pw.println(" prov[iders]: dump content providers"); 18482 pw.println(" p[ackages]: dump installed packages"); 18483 pw.println(" s[hared-users]: dump shared user IDs"); 18484 pw.println(" m[essages]: print collected runtime messages"); 18485 pw.println(" v[erifiers]: print package verifier info"); 18486 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18487 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18488 pw.println(" version: print database version info"); 18489 pw.println(" write: write current settings now"); 18490 pw.println(" installs: details about install sessions"); 18491 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18492 pw.println(" dexopt: dump dexopt state"); 18493 pw.println(" compiler-stats: dump compiler statistics"); 18494 pw.println(" <package.name>: info about given package"); 18495 return; 18496 } else if ("--checkin".equals(opt)) { 18497 checkin = true; 18498 } else if ("-f".equals(opt)) { 18499 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18500 } else { 18501 pw.println("Unknown argument: " + opt + "; use -h for help"); 18502 } 18503 } 18504 18505 // Is the caller requesting to dump a particular piece of data? 18506 if (opti < args.length) { 18507 String cmd = args[opti]; 18508 opti++; 18509 // Is this a package name? 18510 if ("android".equals(cmd) || cmd.contains(".")) { 18511 packageName = cmd; 18512 // When dumping a single package, we always dump all of its 18513 // filter information since the amount of data will be reasonable. 18514 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18515 } else if ("check-permission".equals(cmd)) { 18516 if (opti >= args.length) { 18517 pw.println("Error: check-permission missing permission argument"); 18518 return; 18519 } 18520 String perm = args[opti]; 18521 opti++; 18522 if (opti >= args.length) { 18523 pw.println("Error: check-permission missing package argument"); 18524 return; 18525 } 18526 String pkg = args[opti]; 18527 opti++; 18528 int user = UserHandle.getUserId(Binder.getCallingUid()); 18529 if (opti < args.length) { 18530 try { 18531 user = Integer.parseInt(args[opti]); 18532 } catch (NumberFormatException e) { 18533 pw.println("Error: check-permission user argument is not a number: " 18534 + args[opti]); 18535 return; 18536 } 18537 } 18538 pw.println(checkPermission(perm, pkg, user)); 18539 return; 18540 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18541 dumpState.setDump(DumpState.DUMP_LIBS); 18542 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18543 dumpState.setDump(DumpState.DUMP_FEATURES); 18544 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18545 if (opti >= args.length) { 18546 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18547 | DumpState.DUMP_SERVICE_RESOLVERS 18548 | DumpState.DUMP_RECEIVER_RESOLVERS 18549 | DumpState.DUMP_CONTENT_RESOLVERS); 18550 } else { 18551 while (opti < args.length) { 18552 String name = args[opti]; 18553 if ("a".equals(name) || "activity".equals(name)) { 18554 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18555 } else if ("s".equals(name) || "service".equals(name)) { 18556 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18557 } else if ("r".equals(name) || "receiver".equals(name)) { 18558 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18559 } else if ("c".equals(name) || "content".equals(name)) { 18560 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18561 } else { 18562 pw.println("Error: unknown resolver table type: " + name); 18563 return; 18564 } 18565 opti++; 18566 } 18567 } 18568 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18569 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18570 } else if ("permission".equals(cmd)) { 18571 if (opti >= args.length) { 18572 pw.println("Error: permission requires permission name"); 18573 return; 18574 } 18575 permissionNames = new ArraySet<>(); 18576 while (opti < args.length) { 18577 permissionNames.add(args[opti]); 18578 opti++; 18579 } 18580 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18581 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18582 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18583 dumpState.setDump(DumpState.DUMP_PREFERRED); 18584 } else if ("preferred-xml".equals(cmd)) { 18585 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18586 if (opti < args.length && "--full".equals(args[opti])) { 18587 fullPreferred = true; 18588 opti++; 18589 } 18590 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18591 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18592 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18593 dumpState.setDump(DumpState.DUMP_PACKAGES); 18594 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18595 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18596 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18597 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18598 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18599 dumpState.setDump(DumpState.DUMP_MESSAGES); 18600 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18601 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18602 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18603 || "intent-filter-verifiers".equals(cmd)) { 18604 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18605 } else if ("version".equals(cmd)) { 18606 dumpState.setDump(DumpState.DUMP_VERSION); 18607 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18608 dumpState.setDump(DumpState.DUMP_KEYSETS); 18609 } else if ("installs".equals(cmd)) { 18610 dumpState.setDump(DumpState.DUMP_INSTALLS); 18611 } else if ("frozen".equals(cmd)) { 18612 dumpState.setDump(DumpState.DUMP_FROZEN); 18613 } else if ("dexopt".equals(cmd)) { 18614 dumpState.setDump(DumpState.DUMP_DEXOPT); 18615 } else if ("compiler-stats".equals(cmd)) { 18616 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18617 } else if ("write".equals(cmd)) { 18618 synchronized (mPackages) { 18619 mSettings.writeLPr(); 18620 pw.println("Settings written."); 18621 return; 18622 } 18623 } 18624 } 18625 18626 if (checkin) { 18627 pw.println("vers,1"); 18628 } 18629 18630 // reader 18631 synchronized (mPackages) { 18632 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18633 if (!checkin) { 18634 if (dumpState.onTitlePrinted()) 18635 pw.println(); 18636 pw.println("Database versions:"); 18637 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18638 } 18639 } 18640 18641 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18642 if (!checkin) { 18643 if (dumpState.onTitlePrinted()) 18644 pw.println(); 18645 pw.println("Verifiers:"); 18646 pw.print(" Required: "); 18647 pw.print(mRequiredVerifierPackage); 18648 pw.print(" (uid="); 18649 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18650 UserHandle.USER_SYSTEM)); 18651 pw.println(")"); 18652 } else if (mRequiredVerifierPackage != null) { 18653 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18654 pw.print(","); 18655 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18656 UserHandle.USER_SYSTEM)); 18657 } 18658 } 18659 18660 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18661 packageName == null) { 18662 if (mIntentFilterVerifierComponent != null) { 18663 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18664 if (!checkin) { 18665 if (dumpState.onTitlePrinted()) 18666 pw.println(); 18667 pw.println("Intent Filter Verifier:"); 18668 pw.print(" Using: "); 18669 pw.print(verifierPackageName); 18670 pw.print(" (uid="); 18671 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18672 UserHandle.USER_SYSTEM)); 18673 pw.println(")"); 18674 } else if (verifierPackageName != null) { 18675 pw.print("ifv,"); pw.print(verifierPackageName); 18676 pw.print(","); 18677 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18678 UserHandle.USER_SYSTEM)); 18679 } 18680 } else { 18681 pw.println(); 18682 pw.println("No Intent Filter Verifier available!"); 18683 } 18684 } 18685 18686 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18687 boolean printedHeader = false; 18688 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18689 while (it.hasNext()) { 18690 String name = it.next(); 18691 SharedLibraryEntry ent = mSharedLibraries.get(name); 18692 if (!checkin) { 18693 if (!printedHeader) { 18694 if (dumpState.onTitlePrinted()) 18695 pw.println(); 18696 pw.println("Libraries:"); 18697 printedHeader = true; 18698 } 18699 pw.print(" "); 18700 } else { 18701 pw.print("lib,"); 18702 } 18703 pw.print(name); 18704 if (!checkin) { 18705 pw.print(" -> "); 18706 } 18707 if (ent.path != null) { 18708 if (!checkin) { 18709 pw.print("(jar) "); 18710 pw.print(ent.path); 18711 } else { 18712 pw.print(",jar,"); 18713 pw.print(ent.path); 18714 } 18715 } else { 18716 if (!checkin) { 18717 pw.print("(apk) "); 18718 pw.print(ent.apk); 18719 } else { 18720 pw.print(",apk,"); 18721 pw.print(ent.apk); 18722 } 18723 } 18724 pw.println(); 18725 } 18726 } 18727 18728 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18729 if (dumpState.onTitlePrinted()) 18730 pw.println(); 18731 if (!checkin) { 18732 pw.println("Features:"); 18733 } 18734 18735 for (FeatureInfo feat : mAvailableFeatures.values()) { 18736 if (checkin) { 18737 pw.print("feat,"); 18738 pw.print(feat.name); 18739 pw.print(","); 18740 pw.println(feat.version); 18741 } else { 18742 pw.print(" "); 18743 pw.print(feat.name); 18744 if (feat.version > 0) { 18745 pw.print(" version="); 18746 pw.print(feat.version); 18747 } 18748 pw.println(); 18749 } 18750 } 18751 } 18752 18753 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18754 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18755 : "Activity Resolver Table:", " ", packageName, 18756 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18757 dumpState.setTitlePrinted(true); 18758 } 18759 } 18760 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18761 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18762 : "Receiver Resolver Table:", " ", packageName, 18763 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18764 dumpState.setTitlePrinted(true); 18765 } 18766 } 18767 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18768 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18769 : "Service Resolver Table:", " ", packageName, 18770 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18771 dumpState.setTitlePrinted(true); 18772 } 18773 } 18774 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18775 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18776 : "Provider Resolver Table:", " ", packageName, 18777 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18778 dumpState.setTitlePrinted(true); 18779 } 18780 } 18781 18782 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18783 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18784 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18785 int user = mSettings.mPreferredActivities.keyAt(i); 18786 if (pir.dump(pw, 18787 dumpState.getTitlePrinted() 18788 ? "\nPreferred Activities User " + user + ":" 18789 : "Preferred Activities User " + user + ":", " ", 18790 packageName, true, false)) { 18791 dumpState.setTitlePrinted(true); 18792 } 18793 } 18794 } 18795 18796 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18797 pw.flush(); 18798 FileOutputStream fout = new FileOutputStream(fd); 18799 BufferedOutputStream str = new BufferedOutputStream(fout); 18800 XmlSerializer serializer = new FastXmlSerializer(); 18801 try { 18802 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18803 serializer.startDocument(null, true); 18804 serializer.setFeature( 18805 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18806 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18807 serializer.endDocument(); 18808 serializer.flush(); 18809 } catch (IllegalArgumentException e) { 18810 pw.println("Failed writing: " + e); 18811 } catch (IllegalStateException e) { 18812 pw.println("Failed writing: " + e); 18813 } catch (IOException e) { 18814 pw.println("Failed writing: " + e); 18815 } 18816 } 18817 18818 if (!checkin 18819 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18820 && packageName == null) { 18821 pw.println(); 18822 int count = mSettings.mPackages.size(); 18823 if (count == 0) { 18824 pw.println("No applications!"); 18825 pw.println(); 18826 } else { 18827 final String prefix = " "; 18828 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18829 if (allPackageSettings.size() == 0) { 18830 pw.println("No domain preferred apps!"); 18831 pw.println(); 18832 } else { 18833 pw.println("App verification status:"); 18834 pw.println(); 18835 count = 0; 18836 for (PackageSetting ps : allPackageSettings) { 18837 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18838 if (ivi == null || ivi.getPackageName() == null) continue; 18839 pw.println(prefix + "Package: " + ivi.getPackageName()); 18840 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18841 pw.println(prefix + "Status: " + ivi.getStatusString()); 18842 pw.println(); 18843 count++; 18844 } 18845 if (count == 0) { 18846 pw.println(prefix + "No app verification established."); 18847 pw.println(); 18848 } 18849 for (int userId : sUserManager.getUserIds()) { 18850 pw.println("App linkages for user " + userId + ":"); 18851 pw.println(); 18852 count = 0; 18853 for (PackageSetting ps : allPackageSettings) { 18854 final long status = ps.getDomainVerificationStatusForUser(userId); 18855 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18856 continue; 18857 } 18858 pw.println(prefix + "Package: " + ps.name); 18859 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18860 String statusStr = IntentFilterVerificationInfo. 18861 getStatusStringFromValue(status); 18862 pw.println(prefix + "Status: " + statusStr); 18863 pw.println(); 18864 count++; 18865 } 18866 if (count == 0) { 18867 pw.println(prefix + "No configured app linkages."); 18868 pw.println(); 18869 } 18870 } 18871 } 18872 } 18873 } 18874 18875 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18876 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18877 if (packageName == null && permissionNames == null) { 18878 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18879 if (iperm == 0) { 18880 if (dumpState.onTitlePrinted()) 18881 pw.println(); 18882 pw.println("AppOp Permissions:"); 18883 } 18884 pw.print(" AppOp Permission "); 18885 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18886 pw.println(":"); 18887 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18888 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18889 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18890 } 18891 } 18892 } 18893 } 18894 18895 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18896 boolean printedSomething = false; 18897 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18898 if (packageName != null && !packageName.equals(p.info.packageName)) { 18899 continue; 18900 } 18901 if (!printedSomething) { 18902 if (dumpState.onTitlePrinted()) 18903 pw.println(); 18904 pw.println("Registered ContentProviders:"); 18905 printedSomething = true; 18906 } 18907 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18908 pw.print(" "); pw.println(p.toString()); 18909 } 18910 printedSomething = false; 18911 for (Map.Entry<String, PackageParser.Provider> entry : 18912 mProvidersByAuthority.entrySet()) { 18913 PackageParser.Provider p = entry.getValue(); 18914 if (packageName != null && !packageName.equals(p.info.packageName)) { 18915 continue; 18916 } 18917 if (!printedSomething) { 18918 if (dumpState.onTitlePrinted()) 18919 pw.println(); 18920 pw.println("ContentProvider Authorities:"); 18921 printedSomething = true; 18922 } 18923 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18924 pw.print(" "); pw.println(p.toString()); 18925 if (p.info != null && p.info.applicationInfo != null) { 18926 final String appInfo = p.info.applicationInfo.toString(); 18927 pw.print(" applicationInfo="); pw.println(appInfo); 18928 } 18929 } 18930 } 18931 18932 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18933 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18934 } 18935 18936 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18937 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18938 } 18939 18940 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18941 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18942 } 18943 18944 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18945 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18946 } 18947 18948 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18949 // XXX should handle packageName != null by dumping only install data that 18950 // the given package is involved with. 18951 if (dumpState.onTitlePrinted()) pw.println(); 18952 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18953 } 18954 18955 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18956 // XXX should handle packageName != null by dumping only install data that 18957 // the given package is involved with. 18958 if (dumpState.onTitlePrinted()) pw.println(); 18959 18960 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18961 ipw.println(); 18962 ipw.println("Frozen packages:"); 18963 ipw.increaseIndent(); 18964 if (mFrozenPackages.size() == 0) { 18965 ipw.println("(none)"); 18966 } else { 18967 for (int i = 0; i < mFrozenPackages.size(); i++) { 18968 ipw.println(mFrozenPackages.valueAt(i)); 18969 } 18970 } 18971 ipw.decreaseIndent(); 18972 } 18973 18974 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18975 if (dumpState.onTitlePrinted()) pw.println(); 18976 dumpDexoptStateLPr(pw, packageName); 18977 } 18978 18979 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 18980 if (dumpState.onTitlePrinted()) pw.println(); 18981 dumpCompilerStatsLPr(pw, packageName); 18982 } 18983 18984 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18985 if (dumpState.onTitlePrinted()) pw.println(); 18986 mSettings.dumpReadMessagesLPr(pw, dumpState); 18987 18988 pw.println(); 18989 pw.println("Package warning messages:"); 18990 BufferedReader in = null; 18991 String line = null; 18992 try { 18993 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18994 while ((line = in.readLine()) != null) { 18995 if (line.contains("ignored: updated version")) continue; 18996 pw.println(line); 18997 } 18998 } catch (IOException ignored) { 18999 } finally { 19000 IoUtils.closeQuietly(in); 19001 } 19002 } 19003 19004 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 19005 BufferedReader in = null; 19006 String line = null; 19007 try { 19008 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19009 while ((line = in.readLine()) != null) { 19010 if (line.contains("ignored: updated version")) continue; 19011 pw.print("msg,"); 19012 pw.println(line); 19013 } 19014 } catch (IOException ignored) { 19015 } finally { 19016 IoUtils.closeQuietly(in); 19017 } 19018 } 19019 } 19020 } 19021 19022 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 19023 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19024 ipw.println(); 19025 ipw.println("Dexopt state:"); 19026 ipw.increaseIndent(); 19027 Collection<PackageParser.Package> packages = null; 19028 if (packageName != null) { 19029 PackageParser.Package targetPackage = mPackages.get(packageName); 19030 if (targetPackage != null) { 19031 packages = Collections.singletonList(targetPackage); 19032 } else { 19033 ipw.println("Unable to find package: " + packageName); 19034 return; 19035 } 19036 } else { 19037 packages = mPackages.values(); 19038 } 19039 19040 for (PackageParser.Package pkg : packages) { 19041 ipw.println("[" + pkg.packageName + "]"); 19042 ipw.increaseIndent(); 19043 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 19044 ipw.decreaseIndent(); 19045 } 19046 } 19047 19048 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 19049 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19050 ipw.println(); 19051 ipw.println("Compiler stats:"); 19052 ipw.increaseIndent(); 19053 Collection<PackageParser.Package> packages = null; 19054 if (packageName != null) { 19055 PackageParser.Package targetPackage = mPackages.get(packageName); 19056 if (targetPackage != null) { 19057 packages = Collections.singletonList(targetPackage); 19058 } else { 19059 ipw.println("Unable to find package: " + packageName); 19060 return; 19061 } 19062 } else { 19063 packages = mPackages.values(); 19064 } 19065 19066 for (PackageParser.Package pkg : packages) { 19067 ipw.println("[" + pkg.packageName + "]"); 19068 ipw.increaseIndent(); 19069 19070 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 19071 if (stats == null) { 19072 ipw.println("(No recorded stats)"); 19073 } else { 19074 stats.dump(ipw); 19075 } 19076 ipw.decreaseIndent(); 19077 } 19078 } 19079 19080 private String dumpDomainString(String packageName) { 19081 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 19082 .getList(); 19083 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 19084 19085 ArraySet<String> result = new ArraySet<>(); 19086 if (iviList.size() > 0) { 19087 for (IntentFilterVerificationInfo ivi : iviList) { 19088 for (String host : ivi.getDomains()) { 19089 result.add(host); 19090 } 19091 } 19092 } 19093 if (filters != null && filters.size() > 0) { 19094 for (IntentFilter filter : filters) { 19095 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 19096 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19097 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19098 result.addAll(filter.getHostsList()); 19099 } 19100 } 19101 } 19102 19103 StringBuilder sb = new StringBuilder(result.size() * 16); 19104 for (String domain : result) { 19105 if (sb.length() > 0) sb.append(" "); 19106 sb.append(domain); 19107 } 19108 return sb.toString(); 19109 } 19110 19111 // ------- apps on sdcard specific code ------- 19112 static final boolean DEBUG_SD_INSTALL = false; 19113 19114 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19115 19116 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19117 19118 private boolean mMediaMounted = false; 19119 19120 static String getEncryptKey() { 19121 try { 19122 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19123 SD_ENCRYPTION_KEYSTORE_NAME); 19124 if (sdEncKey == null) { 19125 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19126 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19127 if (sdEncKey == null) { 19128 Slog.e(TAG, "Failed to create encryption keys"); 19129 return null; 19130 } 19131 } 19132 return sdEncKey; 19133 } catch (NoSuchAlgorithmException nsae) { 19134 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19135 return null; 19136 } catch (IOException ioe) { 19137 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19138 return null; 19139 } 19140 } 19141 19142 /* 19143 * Update media status on PackageManager. 19144 */ 19145 @Override 19146 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19147 int callingUid = Binder.getCallingUid(); 19148 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19149 throw new SecurityException("Media status can only be updated by the system"); 19150 } 19151 // reader; this apparently protects mMediaMounted, but should probably 19152 // be a different lock in that case. 19153 synchronized (mPackages) { 19154 Log.i(TAG, "Updating external media status from " 19155 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19156 + (mediaStatus ? "mounted" : "unmounted")); 19157 if (DEBUG_SD_INSTALL) 19158 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19159 + ", mMediaMounted=" + mMediaMounted); 19160 if (mediaStatus == mMediaMounted) { 19161 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19162 : 0, -1); 19163 mHandler.sendMessage(msg); 19164 return; 19165 } 19166 mMediaMounted = mediaStatus; 19167 } 19168 // Queue up an async operation since the package installation may take a 19169 // little while. 19170 mHandler.post(new Runnable() { 19171 public void run() { 19172 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19173 } 19174 }); 19175 } 19176 19177 /** 19178 * Called by MountService when the initial ASECs to scan are available. 19179 * Should block until all the ASEC containers are finished being scanned. 19180 */ 19181 public void scanAvailableAsecs() { 19182 updateExternalMediaStatusInner(true, false, false); 19183 } 19184 19185 /* 19186 * Collect information of applications on external media, map them against 19187 * existing containers and update information based on current mount status. 19188 * Please note that we always have to report status if reportStatus has been 19189 * set to true especially when unloading packages. 19190 */ 19191 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19192 boolean externalStorage) { 19193 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19194 int[] uidArr = EmptyArray.INT; 19195 19196 final String[] list = PackageHelper.getSecureContainerList(); 19197 if (ArrayUtils.isEmpty(list)) { 19198 Log.i(TAG, "No secure containers found"); 19199 } else { 19200 // Process list of secure containers and categorize them 19201 // as active or stale based on their package internal state. 19202 19203 // reader 19204 synchronized (mPackages) { 19205 for (String cid : list) { 19206 // Leave stages untouched for now; installer service owns them 19207 if (PackageInstallerService.isStageName(cid)) continue; 19208 19209 if (DEBUG_SD_INSTALL) 19210 Log.i(TAG, "Processing container " + cid); 19211 String pkgName = getAsecPackageName(cid); 19212 if (pkgName == null) { 19213 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19214 continue; 19215 } 19216 if (DEBUG_SD_INSTALL) 19217 Log.i(TAG, "Looking for pkg : " + pkgName); 19218 19219 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19220 if (ps == null) { 19221 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19222 continue; 19223 } 19224 19225 /* 19226 * Skip packages that are not external if we're unmounting 19227 * external storage. 19228 */ 19229 if (externalStorage && !isMounted && !isExternal(ps)) { 19230 continue; 19231 } 19232 19233 final AsecInstallArgs args = new AsecInstallArgs(cid, 19234 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19235 // The package status is changed only if the code path 19236 // matches between settings and the container id. 19237 if (ps.codePathString != null 19238 && ps.codePathString.startsWith(args.getCodePath())) { 19239 if (DEBUG_SD_INSTALL) { 19240 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19241 + " at code path: " + ps.codePathString); 19242 } 19243 19244 // We do have a valid package installed on sdcard 19245 processCids.put(args, ps.codePathString); 19246 final int uid = ps.appId; 19247 if (uid != -1) { 19248 uidArr = ArrayUtils.appendInt(uidArr, uid); 19249 } 19250 } else { 19251 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19252 + ps.codePathString); 19253 } 19254 } 19255 } 19256 19257 Arrays.sort(uidArr); 19258 } 19259 19260 // Process packages with valid entries. 19261 if (isMounted) { 19262 if (DEBUG_SD_INSTALL) 19263 Log.i(TAG, "Loading packages"); 19264 loadMediaPackages(processCids, uidArr, externalStorage); 19265 startCleaningPackages(); 19266 mInstallerService.onSecureContainersAvailable(); 19267 } else { 19268 if (DEBUG_SD_INSTALL) 19269 Log.i(TAG, "Unloading packages"); 19270 unloadMediaPackages(processCids, uidArr, reportStatus); 19271 } 19272 } 19273 19274 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19275 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19276 final int size = infos.size(); 19277 final String[] packageNames = new String[size]; 19278 final int[] packageUids = new int[size]; 19279 for (int i = 0; i < size; i++) { 19280 final ApplicationInfo info = infos.get(i); 19281 packageNames[i] = info.packageName; 19282 packageUids[i] = info.uid; 19283 } 19284 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19285 finishedReceiver); 19286 } 19287 19288 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19289 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19290 sendResourcesChangedBroadcast(mediaStatus, replacing, 19291 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19292 } 19293 19294 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19295 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19296 int size = pkgList.length; 19297 if (size > 0) { 19298 // Send broadcasts here 19299 Bundle extras = new Bundle(); 19300 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19301 if (uidArr != null) { 19302 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19303 } 19304 if (replacing) { 19305 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19306 } 19307 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19308 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19309 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19310 } 19311 } 19312 19313 /* 19314 * Look at potentially valid container ids from processCids If package 19315 * information doesn't match the one on record or package scanning fails, 19316 * the cid is added to list of removeCids. We currently don't delete stale 19317 * containers. 19318 */ 19319 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19320 boolean externalStorage) { 19321 ArrayList<String> pkgList = new ArrayList<String>(); 19322 Set<AsecInstallArgs> keys = processCids.keySet(); 19323 19324 for (AsecInstallArgs args : keys) { 19325 String codePath = processCids.get(args); 19326 if (DEBUG_SD_INSTALL) 19327 Log.i(TAG, "Loading container : " + args.cid); 19328 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19329 try { 19330 // Make sure there are no container errors first. 19331 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19332 Slog.e(TAG, "Failed to mount cid : " + args.cid 19333 + " when installing from sdcard"); 19334 continue; 19335 } 19336 // Check code path here. 19337 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19338 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19339 + " does not match one in settings " + codePath); 19340 continue; 19341 } 19342 // Parse package 19343 int parseFlags = mDefParseFlags; 19344 if (args.isExternalAsec()) { 19345 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19346 } 19347 if (args.isFwdLocked()) { 19348 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19349 } 19350 19351 synchronized (mInstallLock) { 19352 PackageParser.Package pkg = null; 19353 try { 19354 // Sadly we don't know the package name yet to freeze it 19355 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19356 SCAN_IGNORE_FROZEN, 0, null); 19357 } catch (PackageManagerException e) { 19358 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19359 } 19360 // Scan the package 19361 if (pkg != null) { 19362 /* 19363 * TODO why is the lock being held? doPostInstall is 19364 * called in other places without the lock. This needs 19365 * to be straightened out. 19366 */ 19367 // writer 19368 synchronized (mPackages) { 19369 retCode = PackageManager.INSTALL_SUCCEEDED; 19370 pkgList.add(pkg.packageName); 19371 // Post process args 19372 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19373 pkg.applicationInfo.uid); 19374 } 19375 } else { 19376 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19377 } 19378 } 19379 19380 } finally { 19381 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19382 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19383 } 19384 } 19385 } 19386 // writer 19387 synchronized (mPackages) { 19388 // If the platform SDK has changed since the last time we booted, 19389 // we need to re-grant app permission to catch any new ones that 19390 // appear. This is really a hack, and means that apps can in some 19391 // cases get permissions that the user didn't initially explicitly 19392 // allow... it would be nice to have some better way to handle 19393 // this situation. 19394 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19395 : mSettings.getInternalVersion(); 19396 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19397 : StorageManager.UUID_PRIVATE_INTERNAL; 19398 19399 int updateFlags = UPDATE_PERMISSIONS_ALL; 19400 if (ver.sdkVersion != mSdkVersion) { 19401 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19402 + mSdkVersion + "; regranting permissions for external"); 19403 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19404 } 19405 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19406 19407 // Yay, everything is now upgraded 19408 ver.forceCurrent(); 19409 19410 // can downgrade to reader 19411 // Persist settings 19412 mSettings.writeLPr(); 19413 } 19414 // Send a broadcast to let everyone know we are done processing 19415 if (pkgList.size() > 0) { 19416 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19417 } 19418 } 19419 19420 /* 19421 * Utility method to unload a list of specified containers 19422 */ 19423 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19424 // Just unmount all valid containers. 19425 for (AsecInstallArgs arg : cidArgs) { 19426 synchronized (mInstallLock) { 19427 arg.doPostDeleteLI(false); 19428 } 19429 } 19430 } 19431 19432 /* 19433 * Unload packages mounted on external media. This involves deleting package 19434 * data from internal structures, sending broadcasts about disabled packages, 19435 * gc'ing to free up references, unmounting all secure containers 19436 * corresponding to packages on external media, and posting a 19437 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19438 * that we always have to post this message if status has been requested no 19439 * matter what. 19440 */ 19441 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19442 final boolean reportStatus) { 19443 if (DEBUG_SD_INSTALL) 19444 Log.i(TAG, "unloading media packages"); 19445 ArrayList<String> pkgList = new ArrayList<String>(); 19446 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19447 final Set<AsecInstallArgs> keys = processCids.keySet(); 19448 for (AsecInstallArgs args : keys) { 19449 String pkgName = args.getPackageName(); 19450 if (DEBUG_SD_INSTALL) 19451 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19452 // Delete package internally 19453 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19454 synchronized (mInstallLock) { 19455 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19456 final boolean res; 19457 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19458 "unloadMediaPackages")) { 19459 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19460 null); 19461 } 19462 if (res) { 19463 pkgList.add(pkgName); 19464 } else { 19465 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19466 failedList.add(args); 19467 } 19468 } 19469 } 19470 19471 // reader 19472 synchronized (mPackages) { 19473 // We didn't update the settings after removing each package; 19474 // write them now for all packages. 19475 mSettings.writeLPr(); 19476 } 19477 19478 // We have to absolutely send UPDATED_MEDIA_STATUS only 19479 // after confirming that all the receivers processed the ordered 19480 // broadcast when packages get disabled, force a gc to clean things up. 19481 // and unload all the containers. 19482 if (pkgList.size() > 0) { 19483 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19484 new IIntentReceiver.Stub() { 19485 public void performReceive(Intent intent, int resultCode, String data, 19486 Bundle extras, boolean ordered, boolean sticky, 19487 int sendingUser) throws RemoteException { 19488 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19489 reportStatus ? 1 : 0, 1, keys); 19490 mHandler.sendMessage(msg); 19491 } 19492 }); 19493 } else { 19494 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19495 keys); 19496 mHandler.sendMessage(msg); 19497 } 19498 } 19499 19500 private void loadPrivatePackages(final VolumeInfo vol) { 19501 mHandler.post(new Runnable() { 19502 @Override 19503 public void run() { 19504 loadPrivatePackagesInner(vol); 19505 } 19506 }); 19507 } 19508 19509 private void loadPrivatePackagesInner(VolumeInfo vol) { 19510 final String volumeUuid = vol.fsUuid; 19511 if (TextUtils.isEmpty(volumeUuid)) { 19512 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19513 return; 19514 } 19515 19516 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19517 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19518 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19519 19520 final VersionInfo ver; 19521 final List<PackageSetting> packages; 19522 synchronized (mPackages) { 19523 ver = mSettings.findOrCreateVersion(volumeUuid); 19524 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19525 } 19526 19527 for (PackageSetting ps : packages) { 19528 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19529 synchronized (mInstallLock) { 19530 final PackageParser.Package pkg; 19531 try { 19532 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19533 loaded.add(pkg.applicationInfo); 19534 19535 } catch (PackageManagerException e) { 19536 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19537 } 19538 19539 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19540 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19541 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19542 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19543 } 19544 } 19545 } 19546 19547 // Reconcile app data for all started/unlocked users 19548 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19549 final UserManager um = mContext.getSystemService(UserManager.class); 19550 UserManagerInternal umInternal = getUserManagerInternal(); 19551 for (UserInfo user : um.getUsers()) { 19552 final int flags; 19553 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19554 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19555 } else if (umInternal.isUserRunning(user.id)) { 19556 flags = StorageManager.FLAG_STORAGE_DE; 19557 } else { 19558 continue; 19559 } 19560 19561 try { 19562 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19563 synchronized (mInstallLock) { 19564 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 19565 } 19566 } catch (IllegalStateException e) { 19567 // Device was probably ejected, and we'll process that event momentarily 19568 Slog.w(TAG, "Failed to prepare storage: " + e); 19569 } 19570 } 19571 19572 synchronized (mPackages) { 19573 int updateFlags = UPDATE_PERMISSIONS_ALL; 19574 if (ver.sdkVersion != mSdkVersion) { 19575 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19576 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19577 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19578 } 19579 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19580 19581 // Yay, everything is now upgraded 19582 ver.forceCurrent(); 19583 19584 mSettings.writeLPr(); 19585 } 19586 19587 for (PackageFreezer freezer : freezers) { 19588 freezer.close(); 19589 } 19590 19591 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19592 sendResourcesChangedBroadcast(true, false, loaded, null); 19593 } 19594 19595 private void unloadPrivatePackages(final VolumeInfo vol) { 19596 mHandler.post(new Runnable() { 19597 @Override 19598 public void run() { 19599 unloadPrivatePackagesInner(vol); 19600 } 19601 }); 19602 } 19603 19604 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19605 final String volumeUuid = vol.fsUuid; 19606 if (TextUtils.isEmpty(volumeUuid)) { 19607 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19608 return; 19609 } 19610 19611 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19612 synchronized (mInstallLock) { 19613 synchronized (mPackages) { 19614 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19615 for (PackageSetting ps : packages) { 19616 if (ps.pkg == null) continue; 19617 19618 final ApplicationInfo info = ps.pkg.applicationInfo; 19619 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19620 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19621 19622 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19623 "unloadPrivatePackagesInner")) { 19624 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19625 false, null)) { 19626 unloaded.add(info); 19627 } else { 19628 Slog.w(TAG, "Failed to unload " + ps.codePath); 19629 } 19630 } 19631 19632 // Try very hard to release any references to this package 19633 // so we don't risk the system server being killed due to 19634 // open FDs 19635 AttributeCache.instance().removePackage(ps.name); 19636 } 19637 19638 mSettings.writeLPr(); 19639 } 19640 } 19641 19642 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19643 sendResourcesChangedBroadcast(false, false, unloaded, null); 19644 19645 // Try very hard to release any references to this path so we don't risk 19646 // the system server being killed due to open FDs 19647 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19648 19649 for (int i = 0; i < 3; i++) { 19650 System.gc(); 19651 System.runFinalization(); 19652 } 19653 } 19654 19655 /** 19656 * Prepare storage areas for given user on all mounted devices. 19657 */ 19658 void prepareUserData(int userId, int userSerial, int flags) { 19659 synchronized (mInstallLock) { 19660 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19661 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19662 final String volumeUuid = vol.getFsUuid(); 19663 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19664 } 19665 } 19666 } 19667 19668 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19669 boolean allowRecover) { 19670 // Prepare storage and verify that serial numbers are consistent; if 19671 // there's a mismatch we need to destroy to avoid leaking data 19672 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19673 try { 19674 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19675 19676 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19677 UserManagerService.enforceSerialNumber( 19678 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19679 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19680 UserManagerService.enforceSerialNumber( 19681 Environment.getDataSystemDeDirectory(userId), userSerial); 19682 } 19683 } 19684 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19685 UserManagerService.enforceSerialNumber( 19686 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19687 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19688 UserManagerService.enforceSerialNumber( 19689 Environment.getDataSystemCeDirectory(userId), userSerial); 19690 } 19691 } 19692 19693 synchronized (mInstallLock) { 19694 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19695 } 19696 } catch (Exception e) { 19697 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19698 + " because we failed to prepare: " + e); 19699 destroyUserDataLI(volumeUuid, userId, 19700 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19701 19702 if (allowRecover) { 19703 // Try one last time; if we fail again we're really in trouble 19704 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19705 } 19706 } 19707 } 19708 19709 /** 19710 * Destroy storage areas for given user on all mounted devices. 19711 */ 19712 void destroyUserData(int userId, int flags) { 19713 synchronized (mInstallLock) { 19714 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19715 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19716 final String volumeUuid = vol.getFsUuid(); 19717 destroyUserDataLI(volumeUuid, userId, flags); 19718 } 19719 } 19720 } 19721 19722 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19723 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19724 try { 19725 // Clean up app data, profile data, and media data 19726 mInstaller.destroyUserData(volumeUuid, userId, flags); 19727 19728 // Clean up system data 19729 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19730 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19731 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19732 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19733 } 19734 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19735 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19736 } 19737 } 19738 19739 // Data with special labels is now gone, so finish the job 19740 storage.destroyUserStorage(volumeUuid, userId, flags); 19741 19742 } catch (Exception e) { 19743 logCriticalInfo(Log.WARN, 19744 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19745 } 19746 } 19747 19748 /** 19749 * Examine all users present on given mounted volume, and destroy data 19750 * belonging to users that are no longer valid, or whose user ID has been 19751 * recycled. 19752 */ 19753 private void reconcileUsers(String volumeUuid) { 19754 final List<File> files = new ArrayList<>(); 19755 Collections.addAll(files, FileUtils 19756 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19757 Collections.addAll(files, FileUtils 19758 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19759 Collections.addAll(files, FileUtils 19760 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19761 Collections.addAll(files, FileUtils 19762 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19763 for (File file : files) { 19764 if (!file.isDirectory()) continue; 19765 19766 final int userId; 19767 final UserInfo info; 19768 try { 19769 userId = Integer.parseInt(file.getName()); 19770 info = sUserManager.getUserInfo(userId); 19771 } catch (NumberFormatException e) { 19772 Slog.w(TAG, "Invalid user directory " + file); 19773 continue; 19774 } 19775 19776 boolean destroyUser = false; 19777 if (info == null) { 19778 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19779 + " because no matching user was found"); 19780 destroyUser = true; 19781 } else if (!mOnlyCore) { 19782 try { 19783 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19784 } catch (IOException e) { 19785 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19786 + " because we failed to enforce serial number: " + e); 19787 destroyUser = true; 19788 } 19789 } 19790 19791 if (destroyUser) { 19792 synchronized (mInstallLock) { 19793 destroyUserDataLI(volumeUuid, userId, 19794 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19795 } 19796 } 19797 } 19798 } 19799 19800 private void assertPackageKnown(String volumeUuid, String packageName) 19801 throws PackageManagerException { 19802 synchronized (mPackages) { 19803 final PackageSetting ps = mSettings.mPackages.get(packageName); 19804 if (ps == null) { 19805 throw new PackageManagerException("Package " + packageName + " is unknown"); 19806 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19807 throw new PackageManagerException( 19808 "Package " + packageName + " found on unknown volume " + volumeUuid 19809 + "; expected volume " + ps.volumeUuid); 19810 } 19811 } 19812 } 19813 19814 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19815 throws PackageManagerException { 19816 synchronized (mPackages) { 19817 final PackageSetting ps = mSettings.mPackages.get(packageName); 19818 if (ps == null) { 19819 throw new PackageManagerException("Package " + packageName + " is unknown"); 19820 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19821 throw new PackageManagerException( 19822 "Package " + packageName + " found on unknown volume " + volumeUuid 19823 + "; expected volume " + ps.volumeUuid); 19824 } else if (!ps.getInstalled(userId)) { 19825 throw new PackageManagerException( 19826 "Package " + packageName + " not installed for user " + userId); 19827 } 19828 } 19829 } 19830 19831 /** 19832 * Examine all apps present on given mounted volume, and destroy apps that 19833 * aren't expected, either due to uninstallation or reinstallation on 19834 * another volume. 19835 */ 19836 private void reconcileApps(String volumeUuid) { 19837 final File[] files = FileUtils 19838 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19839 for (File file : files) { 19840 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19841 && !PackageInstallerService.isStageName(file.getName()); 19842 if (!isPackage) { 19843 // Ignore entries which are not packages 19844 continue; 19845 } 19846 19847 try { 19848 final PackageLite pkg = PackageParser.parsePackageLite(file, 19849 PackageParser.PARSE_MUST_BE_APK); 19850 assertPackageKnown(volumeUuid, pkg.packageName); 19851 19852 } catch (PackageParserException | PackageManagerException e) { 19853 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19854 synchronized (mInstallLock) { 19855 removeCodePathLI(file); 19856 } 19857 } 19858 } 19859 } 19860 19861 /** 19862 * Reconcile all app data for the given user. 19863 * <p> 19864 * Verifies that directories exist and that ownership and labeling is 19865 * correct for all installed apps on all mounted volumes. 19866 */ 19867 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 19868 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19869 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19870 final String volumeUuid = vol.getFsUuid(); 19871 synchronized (mInstallLock) { 19872 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 19873 } 19874 } 19875 } 19876 19877 /** 19878 * Reconcile all app data on given mounted volume. 19879 * <p> 19880 * Destroys app data that isn't expected, either due to uninstallation or 19881 * reinstallation on another volume. 19882 * <p> 19883 * Verifies that directories exist and that ownership and labeling is 19884 * correct for all installed apps. 19885 */ 19886 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 19887 boolean migrateAppData) { 19888 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19889 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 19890 19891 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19892 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19893 19894 // First look for stale data that doesn't belong, and check if things 19895 // have changed since we did our last restorecon 19896 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19897 if (StorageManager.isFileEncryptedNativeOrEmulated() 19898 && !StorageManager.isUserKeyUnlocked(userId)) { 19899 throw new RuntimeException( 19900 "Yikes, someone asked us to reconcile CE storage while " + userId 19901 + " was still locked; this would have caused massive data loss!"); 19902 } 19903 19904 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19905 for (File file : files) { 19906 final String packageName = file.getName(); 19907 try { 19908 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19909 } catch (PackageManagerException e) { 19910 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19911 try { 19912 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19913 StorageManager.FLAG_STORAGE_CE, 0); 19914 } catch (InstallerException e2) { 19915 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19916 } 19917 } 19918 } 19919 } 19920 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19921 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19922 for (File file : files) { 19923 final String packageName = file.getName(); 19924 try { 19925 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19926 } catch (PackageManagerException e) { 19927 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19928 try { 19929 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19930 StorageManager.FLAG_STORAGE_DE, 0); 19931 } catch (InstallerException e2) { 19932 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19933 } 19934 } 19935 } 19936 } 19937 19938 // Ensure that data directories are ready to roll for all packages 19939 // installed for this volume and user 19940 final List<PackageSetting> packages; 19941 synchronized (mPackages) { 19942 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19943 } 19944 int preparedCount = 0; 19945 for (PackageSetting ps : packages) { 19946 final String packageName = ps.name; 19947 if (ps.pkg == null) { 19948 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19949 // TODO: might be due to legacy ASEC apps; we should circle back 19950 // and reconcile again once they're scanned 19951 continue; 19952 } 19953 19954 if (ps.getInstalled(userId)) { 19955 prepareAppDataLIF(ps.pkg, userId, flags); 19956 19957 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 19958 // We may have just shuffled around app data directories, so 19959 // prepare them one more time 19960 prepareAppDataLIF(ps.pkg, userId, flags); 19961 } 19962 19963 preparedCount++; 19964 } 19965 } 19966 19967 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 19968 } 19969 19970 /** 19971 * Prepare app data for the given app just after it was installed or 19972 * upgraded. This method carefully only touches users that it's installed 19973 * for, and it forces a restorecon to handle any seinfo changes. 19974 * <p> 19975 * Verifies that directories exist and that ownership and labeling is 19976 * correct for all installed apps. If there is an ownership mismatch, it 19977 * will try recovering system apps by wiping data; third-party app data is 19978 * left intact. 19979 * <p> 19980 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19981 */ 19982 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19983 final PackageSetting ps; 19984 synchronized (mPackages) { 19985 ps = mSettings.mPackages.get(pkg.packageName); 19986 mSettings.writeKernelMappingLPr(ps); 19987 } 19988 19989 final UserManager um = mContext.getSystemService(UserManager.class); 19990 UserManagerInternal umInternal = getUserManagerInternal(); 19991 for (UserInfo user : um.getUsers()) { 19992 final int flags; 19993 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19994 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19995 } else if (umInternal.isUserRunning(user.id)) { 19996 flags = StorageManager.FLAG_STORAGE_DE; 19997 } else { 19998 continue; 19999 } 20000 20001 if (ps.getInstalled(user.id)) { 20002 // TODO: when user data is locked, mark that we're still dirty 20003 prepareAppDataLIF(pkg, user.id, flags); 20004 } 20005 } 20006 } 20007 20008 /** 20009 * Prepare app data for the given app. 20010 * <p> 20011 * Verifies that directories exist and that ownership and labeling is 20012 * correct for all installed apps. If there is an ownership mismatch, this 20013 * will try recovering system apps by wiping data; third-party app data is 20014 * left intact. 20015 */ 20016 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 20017 if (pkg == null) { 20018 Slog.wtf(TAG, "Package was null!", new Throwable()); 20019 return; 20020 } 20021 prepareAppDataLeafLIF(pkg, userId, flags); 20022 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20023 for (int i = 0; i < childCount; i++) { 20024 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 20025 } 20026 } 20027 20028 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20029 if (DEBUG_APP_DATA) { 20030 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 20031 + Integer.toHexString(flags)); 20032 } 20033 20034 final String volumeUuid = pkg.volumeUuid; 20035 final String packageName = pkg.packageName; 20036 final ApplicationInfo app = pkg.applicationInfo; 20037 final int appId = UserHandle.getAppId(app.uid); 20038 20039 Preconditions.checkNotNull(app.seinfo); 20040 20041 try { 20042 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20043 appId, app.seinfo, app.targetSdkVersion); 20044 } catch (InstallerException e) { 20045 if (app.isSystemApp()) { 20046 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 20047 + ", but trying to recover: " + e); 20048 destroyAppDataLeafLIF(pkg, userId, flags); 20049 try { 20050 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20051 appId, app.seinfo, app.targetSdkVersion); 20052 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 20053 } catch (InstallerException e2) { 20054 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 20055 } 20056 } else { 20057 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 20058 } 20059 } 20060 20061 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20062 try { 20063 // CE storage is unlocked right now, so read out the inode and 20064 // remember for use later when it's locked 20065 // TODO: mark this structure as dirty so we persist it! 20066 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 20067 StorageManager.FLAG_STORAGE_CE); 20068 synchronized (mPackages) { 20069 final PackageSetting ps = mSettings.mPackages.get(packageName); 20070 if (ps != null) { 20071 ps.setCeDataInode(ceDataInode, userId); 20072 } 20073 } 20074 } catch (InstallerException e) { 20075 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 20076 } 20077 } 20078 20079 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20080 } 20081 20082 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 20083 if (pkg == null) { 20084 Slog.wtf(TAG, "Package was null!", new Throwable()); 20085 return; 20086 } 20087 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20088 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20089 for (int i = 0; i < childCount; i++) { 20090 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 20091 } 20092 } 20093 20094 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20095 final String volumeUuid = pkg.volumeUuid; 20096 final String packageName = pkg.packageName; 20097 final ApplicationInfo app = pkg.applicationInfo; 20098 20099 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20100 // Create a native library symlink only if we have native libraries 20101 // and if the native libraries are 32 bit libraries. We do not provide 20102 // this symlink for 64 bit libraries. 20103 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20104 final String nativeLibPath = app.nativeLibraryDir; 20105 try { 20106 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20107 nativeLibPath, userId); 20108 } catch (InstallerException e) { 20109 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20110 } 20111 } 20112 } 20113 } 20114 20115 /** 20116 * For system apps on non-FBE devices, this method migrates any existing 20117 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20118 * requested by the app. 20119 */ 20120 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20121 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20122 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20123 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20124 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20125 try { 20126 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20127 storageTarget); 20128 } catch (InstallerException e) { 20129 logCriticalInfo(Log.WARN, 20130 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20131 } 20132 return true; 20133 } else { 20134 return false; 20135 } 20136 } 20137 20138 public PackageFreezer freezePackage(String packageName, String killReason) { 20139 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20140 } 20141 20142 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20143 return new PackageFreezer(packageName, userId, killReason); 20144 } 20145 20146 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20147 String killReason) { 20148 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20149 } 20150 20151 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20152 String killReason) { 20153 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20154 return new PackageFreezer(); 20155 } else { 20156 return freezePackage(packageName, userId, killReason); 20157 } 20158 } 20159 20160 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20161 String killReason) { 20162 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20163 } 20164 20165 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20166 String killReason) { 20167 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20168 return new PackageFreezer(); 20169 } else { 20170 return freezePackage(packageName, userId, killReason); 20171 } 20172 } 20173 20174 /** 20175 * Class that freezes and kills the given package upon creation, and 20176 * unfreezes it upon closing. This is typically used when doing surgery on 20177 * app code/data to prevent the app from running while you're working. 20178 */ 20179 private class PackageFreezer implements AutoCloseable { 20180 private final String mPackageName; 20181 private final PackageFreezer[] mChildren; 20182 20183 private final boolean mWeFroze; 20184 20185 private final AtomicBoolean mClosed = new AtomicBoolean(); 20186 private final CloseGuard mCloseGuard = CloseGuard.get(); 20187 20188 /** 20189 * Create and return a stub freezer that doesn't actually do anything, 20190 * typically used when someone requested 20191 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20192 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20193 */ 20194 public PackageFreezer() { 20195 mPackageName = null; 20196 mChildren = null; 20197 mWeFroze = false; 20198 mCloseGuard.open("close"); 20199 } 20200 20201 public PackageFreezer(String packageName, int userId, String killReason) { 20202 synchronized (mPackages) { 20203 mPackageName = packageName; 20204 mWeFroze = mFrozenPackages.add(mPackageName); 20205 20206 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20207 if (ps != null) { 20208 killApplication(ps.name, ps.appId, userId, killReason); 20209 } 20210 20211 final PackageParser.Package p = mPackages.get(packageName); 20212 if (p != null && p.childPackages != null) { 20213 final int N = p.childPackages.size(); 20214 mChildren = new PackageFreezer[N]; 20215 for (int i = 0; i < N; i++) { 20216 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20217 userId, killReason); 20218 } 20219 } else { 20220 mChildren = null; 20221 } 20222 } 20223 mCloseGuard.open("close"); 20224 } 20225 20226 @Override 20227 protected void finalize() throws Throwable { 20228 try { 20229 mCloseGuard.warnIfOpen(); 20230 close(); 20231 } finally { 20232 super.finalize(); 20233 } 20234 } 20235 20236 @Override 20237 public void close() { 20238 mCloseGuard.close(); 20239 if (mClosed.compareAndSet(false, true)) { 20240 synchronized (mPackages) { 20241 if (mWeFroze) { 20242 mFrozenPackages.remove(mPackageName); 20243 } 20244 20245 if (mChildren != null) { 20246 for (PackageFreezer freezer : mChildren) { 20247 freezer.close(); 20248 } 20249 } 20250 } 20251 } 20252 } 20253 } 20254 20255 /** 20256 * Verify that given package is currently frozen. 20257 */ 20258 private void checkPackageFrozen(String packageName) { 20259 synchronized (mPackages) { 20260 if (!mFrozenPackages.contains(packageName)) { 20261 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20262 } 20263 } 20264 } 20265 20266 @Override 20267 public int movePackage(final String packageName, final String volumeUuid) { 20268 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20269 20270 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20271 final int moveId = mNextMoveId.getAndIncrement(); 20272 mHandler.post(new Runnable() { 20273 @Override 20274 public void run() { 20275 try { 20276 movePackageInternal(packageName, volumeUuid, moveId, user); 20277 } catch (PackageManagerException e) { 20278 Slog.w(TAG, "Failed to move " + packageName, e); 20279 mMoveCallbacks.notifyStatusChanged(moveId, 20280 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20281 } 20282 } 20283 }); 20284 return moveId; 20285 } 20286 20287 private void movePackageInternal(final String packageName, final String volumeUuid, 20288 final int moveId, UserHandle user) throws PackageManagerException { 20289 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20290 final PackageManager pm = mContext.getPackageManager(); 20291 20292 final boolean currentAsec; 20293 final String currentVolumeUuid; 20294 final File codeFile; 20295 final String installerPackageName; 20296 final String packageAbiOverride; 20297 final int appId; 20298 final String seinfo; 20299 final String label; 20300 final int targetSdkVersion; 20301 final PackageFreezer freezer; 20302 final int[] installedUserIds; 20303 20304 // reader 20305 synchronized (mPackages) { 20306 final PackageParser.Package pkg = mPackages.get(packageName); 20307 final PackageSetting ps = mSettings.mPackages.get(packageName); 20308 if (pkg == null || ps == null) { 20309 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20310 } 20311 20312 if (pkg.applicationInfo.isSystemApp()) { 20313 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20314 "Cannot move system application"); 20315 } 20316 20317 if (pkg.applicationInfo.isExternalAsec()) { 20318 currentAsec = true; 20319 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20320 } else if (pkg.applicationInfo.isForwardLocked()) { 20321 currentAsec = true; 20322 currentVolumeUuid = "forward_locked"; 20323 } else { 20324 currentAsec = false; 20325 currentVolumeUuid = ps.volumeUuid; 20326 20327 final File probe = new File(pkg.codePath); 20328 final File probeOat = new File(probe, "oat"); 20329 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20330 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20331 "Move only supported for modern cluster style installs"); 20332 } 20333 } 20334 20335 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20336 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20337 "Package already moved to " + volumeUuid); 20338 } 20339 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20340 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20341 "Device admin cannot be moved"); 20342 } 20343 20344 if (mFrozenPackages.contains(packageName)) { 20345 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20346 "Failed to move already frozen package"); 20347 } 20348 20349 codeFile = new File(pkg.codePath); 20350 installerPackageName = ps.installerPackageName; 20351 packageAbiOverride = ps.cpuAbiOverrideString; 20352 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20353 seinfo = pkg.applicationInfo.seinfo; 20354 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20355 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20356 freezer = freezePackage(packageName, "movePackageInternal"); 20357 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20358 } 20359 20360 final Bundle extras = new Bundle(); 20361 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20362 extras.putString(Intent.EXTRA_TITLE, label); 20363 mMoveCallbacks.notifyCreated(moveId, extras); 20364 20365 int installFlags; 20366 final boolean moveCompleteApp; 20367 final File measurePath; 20368 20369 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20370 installFlags = INSTALL_INTERNAL; 20371 moveCompleteApp = !currentAsec; 20372 measurePath = Environment.getDataAppDirectory(volumeUuid); 20373 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20374 installFlags = INSTALL_EXTERNAL; 20375 moveCompleteApp = false; 20376 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20377 } else { 20378 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20379 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20380 || !volume.isMountedWritable()) { 20381 freezer.close(); 20382 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20383 "Move location not mounted private volume"); 20384 } 20385 20386 Preconditions.checkState(!currentAsec); 20387 20388 installFlags = INSTALL_INTERNAL; 20389 moveCompleteApp = true; 20390 measurePath = Environment.getDataAppDirectory(volumeUuid); 20391 } 20392 20393 final PackageStats stats = new PackageStats(null, -1); 20394 synchronized (mInstaller) { 20395 for (int userId : installedUserIds) { 20396 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20397 freezer.close(); 20398 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20399 "Failed to measure package size"); 20400 } 20401 } 20402 } 20403 20404 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20405 + stats.dataSize); 20406 20407 final long startFreeBytes = measurePath.getFreeSpace(); 20408 final long sizeBytes; 20409 if (moveCompleteApp) { 20410 sizeBytes = stats.codeSize + stats.dataSize; 20411 } else { 20412 sizeBytes = stats.codeSize; 20413 } 20414 20415 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20416 freezer.close(); 20417 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20418 "Not enough free space to move"); 20419 } 20420 20421 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20422 20423 final CountDownLatch installedLatch = new CountDownLatch(1); 20424 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20425 @Override 20426 public void onUserActionRequired(Intent intent) throws RemoteException { 20427 throw new IllegalStateException(); 20428 } 20429 20430 @Override 20431 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20432 Bundle extras) throws RemoteException { 20433 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20434 + PackageManager.installStatusToString(returnCode, msg)); 20435 20436 installedLatch.countDown(); 20437 freezer.close(); 20438 20439 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20440 switch (status) { 20441 case PackageInstaller.STATUS_SUCCESS: 20442 mMoveCallbacks.notifyStatusChanged(moveId, 20443 PackageManager.MOVE_SUCCEEDED); 20444 break; 20445 case PackageInstaller.STATUS_FAILURE_STORAGE: 20446 mMoveCallbacks.notifyStatusChanged(moveId, 20447 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20448 break; 20449 default: 20450 mMoveCallbacks.notifyStatusChanged(moveId, 20451 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20452 break; 20453 } 20454 } 20455 }; 20456 20457 final MoveInfo move; 20458 if (moveCompleteApp) { 20459 // Kick off a thread to report progress estimates 20460 new Thread() { 20461 @Override 20462 public void run() { 20463 while (true) { 20464 try { 20465 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20466 break; 20467 } 20468 } catch (InterruptedException ignored) { 20469 } 20470 20471 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20472 final int progress = 10 + (int) MathUtils.constrain( 20473 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20474 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20475 } 20476 } 20477 }.start(); 20478 20479 final String dataAppName = codeFile.getName(); 20480 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20481 dataAppName, appId, seinfo, targetSdkVersion); 20482 } else { 20483 move = null; 20484 } 20485 20486 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20487 20488 final Message msg = mHandler.obtainMessage(INIT_COPY); 20489 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20490 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20491 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20492 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20493 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20494 msg.obj = params; 20495 20496 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20497 System.identityHashCode(msg.obj)); 20498 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20499 System.identityHashCode(msg.obj)); 20500 20501 mHandler.sendMessage(msg); 20502 } 20503 20504 @Override 20505 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20506 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20507 20508 final int realMoveId = mNextMoveId.getAndIncrement(); 20509 final Bundle extras = new Bundle(); 20510 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20511 mMoveCallbacks.notifyCreated(realMoveId, extras); 20512 20513 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20514 @Override 20515 public void onCreated(int moveId, Bundle extras) { 20516 // Ignored 20517 } 20518 20519 @Override 20520 public void onStatusChanged(int moveId, int status, long estMillis) { 20521 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20522 } 20523 }; 20524 20525 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20526 storage.setPrimaryStorageUuid(volumeUuid, callback); 20527 return realMoveId; 20528 } 20529 20530 @Override 20531 public int getMoveStatus(int moveId) { 20532 mContext.enforceCallingOrSelfPermission( 20533 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20534 return mMoveCallbacks.mLastStatus.get(moveId); 20535 } 20536 20537 @Override 20538 public void registerMoveCallback(IPackageMoveObserver callback) { 20539 mContext.enforceCallingOrSelfPermission( 20540 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20541 mMoveCallbacks.register(callback); 20542 } 20543 20544 @Override 20545 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20546 mContext.enforceCallingOrSelfPermission( 20547 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20548 mMoveCallbacks.unregister(callback); 20549 } 20550 20551 @Override 20552 public boolean setInstallLocation(int loc) { 20553 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20554 null); 20555 if (getInstallLocation() == loc) { 20556 return true; 20557 } 20558 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20559 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20560 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20561 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20562 return true; 20563 } 20564 return false; 20565 } 20566 20567 @Override 20568 public int getInstallLocation() { 20569 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20570 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20571 PackageHelper.APP_INSTALL_AUTO); 20572 } 20573 20574 /** Called by UserManagerService */ 20575 void cleanUpUser(UserManagerService userManager, int userHandle) { 20576 synchronized (mPackages) { 20577 mDirtyUsers.remove(userHandle); 20578 mUserNeedsBadging.delete(userHandle); 20579 mSettings.removeUserLPw(userHandle); 20580 mPendingBroadcasts.remove(userHandle); 20581 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20582 removeUnusedPackagesLPw(userManager, userHandle); 20583 } 20584 } 20585 20586 /** 20587 * We're removing userHandle and would like to remove any downloaded packages 20588 * that are no longer in use by any other user. 20589 * @param userHandle the user being removed 20590 */ 20591 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20592 final boolean DEBUG_CLEAN_APKS = false; 20593 int [] users = userManager.getUserIds(); 20594 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20595 while (psit.hasNext()) { 20596 PackageSetting ps = psit.next(); 20597 if (ps.pkg == null) { 20598 continue; 20599 } 20600 final String packageName = ps.pkg.packageName; 20601 // Skip over if system app 20602 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20603 continue; 20604 } 20605 if (DEBUG_CLEAN_APKS) { 20606 Slog.i(TAG, "Checking package " + packageName); 20607 } 20608 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20609 if (keep) { 20610 if (DEBUG_CLEAN_APKS) { 20611 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20612 } 20613 } else { 20614 for (int i = 0; i < users.length; i++) { 20615 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20616 keep = true; 20617 if (DEBUG_CLEAN_APKS) { 20618 Slog.i(TAG, " Keeping package " + packageName + " for user " 20619 + users[i]); 20620 } 20621 break; 20622 } 20623 } 20624 } 20625 if (!keep) { 20626 if (DEBUG_CLEAN_APKS) { 20627 Slog.i(TAG, " Removing package " + packageName); 20628 } 20629 mHandler.post(new Runnable() { 20630 public void run() { 20631 deletePackageX(packageName, userHandle, 0); 20632 } //end run 20633 }); 20634 } 20635 } 20636 } 20637 20638 /** Called by UserManagerService */ 20639 void createNewUser(int userId) { 20640 synchronized (mInstallLock) { 20641 mSettings.createNewUserLI(this, mInstaller, userId); 20642 } 20643 synchronized (mPackages) { 20644 scheduleWritePackageRestrictionsLocked(userId); 20645 scheduleWritePackageListLocked(userId); 20646 applyFactoryDefaultBrowserLPw(userId); 20647 primeDomainVerificationsLPw(userId); 20648 } 20649 } 20650 20651 void onNewUserCreated(final int userId) { 20652 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20653 // If permission review for legacy apps is required, we represent 20654 // dagerous permissions for such apps as always granted runtime 20655 // permissions to keep per user flag state whether review is needed. 20656 // Hence, if a new user is added we have to propagate dangerous 20657 // permission grants for these legacy apps. 20658 if (mPermissionReviewRequired) { 20659 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20660 | UPDATE_PERMISSIONS_REPLACE_ALL); 20661 } 20662 } 20663 20664 @Override 20665 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20666 mContext.enforceCallingOrSelfPermission( 20667 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20668 "Only package verification agents can read the verifier device identity"); 20669 20670 synchronized (mPackages) { 20671 return mSettings.getVerifierDeviceIdentityLPw(); 20672 } 20673 } 20674 20675 @Override 20676 public void setPermissionEnforced(String permission, boolean enforced) { 20677 // TODO: Now that we no longer change GID for storage, this should to away. 20678 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20679 "setPermissionEnforced"); 20680 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20681 synchronized (mPackages) { 20682 if (mSettings.mReadExternalStorageEnforced == null 20683 || mSettings.mReadExternalStorageEnforced != enforced) { 20684 mSettings.mReadExternalStorageEnforced = enforced; 20685 mSettings.writeLPr(); 20686 } 20687 } 20688 // kill any non-foreground processes so we restart them and 20689 // grant/revoke the GID. 20690 final IActivityManager am = ActivityManagerNative.getDefault(); 20691 if (am != null) { 20692 final long token = Binder.clearCallingIdentity(); 20693 try { 20694 am.killProcessesBelowForeground("setPermissionEnforcement"); 20695 } catch (RemoteException e) { 20696 } finally { 20697 Binder.restoreCallingIdentity(token); 20698 } 20699 } 20700 } else { 20701 throw new IllegalArgumentException("No selective enforcement for " + permission); 20702 } 20703 } 20704 20705 @Override 20706 @Deprecated 20707 public boolean isPermissionEnforced(String permission) { 20708 return true; 20709 } 20710 20711 @Override 20712 public boolean isStorageLow() { 20713 final long token = Binder.clearCallingIdentity(); 20714 try { 20715 final DeviceStorageMonitorInternal 20716 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20717 if (dsm != null) { 20718 return dsm.isMemoryLow(); 20719 } else { 20720 return false; 20721 } 20722 } finally { 20723 Binder.restoreCallingIdentity(token); 20724 } 20725 } 20726 20727 @Override 20728 public IPackageInstaller getPackageInstaller() { 20729 return mInstallerService; 20730 } 20731 20732 private boolean userNeedsBadging(int userId) { 20733 int index = mUserNeedsBadging.indexOfKey(userId); 20734 if (index < 0) { 20735 final UserInfo userInfo; 20736 final long token = Binder.clearCallingIdentity(); 20737 try { 20738 userInfo = sUserManager.getUserInfo(userId); 20739 } finally { 20740 Binder.restoreCallingIdentity(token); 20741 } 20742 final boolean b; 20743 if (userInfo != null && userInfo.isManagedProfile()) { 20744 b = true; 20745 } else { 20746 b = false; 20747 } 20748 mUserNeedsBadging.put(userId, b); 20749 return b; 20750 } 20751 return mUserNeedsBadging.valueAt(index); 20752 } 20753 20754 @Override 20755 public KeySet getKeySetByAlias(String packageName, String alias) { 20756 if (packageName == null || alias == null) { 20757 return null; 20758 } 20759 synchronized(mPackages) { 20760 final PackageParser.Package pkg = mPackages.get(packageName); 20761 if (pkg == null) { 20762 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20763 throw new IllegalArgumentException("Unknown package: " + packageName); 20764 } 20765 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20766 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20767 } 20768 } 20769 20770 @Override 20771 public KeySet getSigningKeySet(String packageName) { 20772 if (packageName == null) { 20773 return null; 20774 } 20775 synchronized(mPackages) { 20776 final PackageParser.Package pkg = mPackages.get(packageName); 20777 if (pkg == null) { 20778 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20779 throw new IllegalArgumentException("Unknown package: " + packageName); 20780 } 20781 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20782 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20783 throw new SecurityException("May not access signing KeySet of other apps."); 20784 } 20785 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20786 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20787 } 20788 } 20789 20790 @Override 20791 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20792 if (packageName == null || ks == null) { 20793 return false; 20794 } 20795 synchronized(mPackages) { 20796 final PackageParser.Package pkg = mPackages.get(packageName); 20797 if (pkg == null) { 20798 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20799 throw new IllegalArgumentException("Unknown package: " + packageName); 20800 } 20801 IBinder ksh = ks.getToken(); 20802 if (ksh instanceof KeySetHandle) { 20803 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20804 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20805 } 20806 return false; 20807 } 20808 } 20809 20810 @Override 20811 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20812 if (packageName == null || ks == null) { 20813 return false; 20814 } 20815 synchronized(mPackages) { 20816 final PackageParser.Package pkg = mPackages.get(packageName); 20817 if (pkg == null) { 20818 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20819 throw new IllegalArgumentException("Unknown package: " + packageName); 20820 } 20821 IBinder ksh = ks.getToken(); 20822 if (ksh instanceof KeySetHandle) { 20823 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20824 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20825 } 20826 return false; 20827 } 20828 } 20829 20830 private void deletePackageIfUnusedLPr(final String packageName) { 20831 PackageSetting ps = mSettings.mPackages.get(packageName); 20832 if (ps == null) { 20833 return; 20834 } 20835 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20836 // TODO Implement atomic delete if package is unused 20837 // It is currently possible that the package will be deleted even if it is installed 20838 // after this method returns. 20839 mHandler.post(new Runnable() { 20840 public void run() { 20841 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20842 } 20843 }); 20844 } 20845 } 20846 20847 /** 20848 * Check and throw if the given before/after packages would be considered a 20849 * downgrade. 20850 */ 20851 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20852 throws PackageManagerException { 20853 if (after.versionCode < before.mVersionCode) { 20854 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20855 "Update version code " + after.versionCode + " is older than current " 20856 + before.mVersionCode); 20857 } else if (after.versionCode == before.mVersionCode) { 20858 if (after.baseRevisionCode < before.baseRevisionCode) { 20859 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20860 "Update base revision code " + after.baseRevisionCode 20861 + " is older than current " + before.baseRevisionCode); 20862 } 20863 20864 if (!ArrayUtils.isEmpty(after.splitNames)) { 20865 for (int i = 0; i < after.splitNames.length; i++) { 20866 final String splitName = after.splitNames[i]; 20867 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20868 if (j != -1) { 20869 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20870 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20871 "Update split " + splitName + " revision code " 20872 + after.splitRevisionCodes[i] + " is older than current " 20873 + before.splitRevisionCodes[j]); 20874 } 20875 } 20876 } 20877 } 20878 } 20879 } 20880 20881 private static class MoveCallbacks extends Handler { 20882 private static final int MSG_CREATED = 1; 20883 private static final int MSG_STATUS_CHANGED = 2; 20884 20885 private final RemoteCallbackList<IPackageMoveObserver> 20886 mCallbacks = new RemoteCallbackList<>(); 20887 20888 private final SparseIntArray mLastStatus = new SparseIntArray(); 20889 20890 public MoveCallbacks(Looper looper) { 20891 super(looper); 20892 } 20893 20894 public void register(IPackageMoveObserver callback) { 20895 mCallbacks.register(callback); 20896 } 20897 20898 public void unregister(IPackageMoveObserver callback) { 20899 mCallbacks.unregister(callback); 20900 } 20901 20902 @Override 20903 public void handleMessage(Message msg) { 20904 final SomeArgs args = (SomeArgs) msg.obj; 20905 final int n = mCallbacks.beginBroadcast(); 20906 for (int i = 0; i < n; i++) { 20907 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20908 try { 20909 invokeCallback(callback, msg.what, args); 20910 } catch (RemoteException ignored) { 20911 } 20912 } 20913 mCallbacks.finishBroadcast(); 20914 args.recycle(); 20915 } 20916 20917 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20918 throws RemoteException { 20919 switch (what) { 20920 case MSG_CREATED: { 20921 callback.onCreated(args.argi1, (Bundle) args.arg2); 20922 break; 20923 } 20924 case MSG_STATUS_CHANGED: { 20925 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20926 break; 20927 } 20928 } 20929 } 20930 20931 private void notifyCreated(int moveId, Bundle extras) { 20932 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20933 20934 final SomeArgs args = SomeArgs.obtain(); 20935 args.argi1 = moveId; 20936 args.arg2 = extras; 20937 obtainMessage(MSG_CREATED, args).sendToTarget(); 20938 } 20939 20940 private void notifyStatusChanged(int moveId, int status) { 20941 notifyStatusChanged(moveId, status, -1); 20942 } 20943 20944 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20945 Slog.v(TAG, "Move " + moveId + " status " + status); 20946 20947 final SomeArgs args = SomeArgs.obtain(); 20948 args.argi1 = moveId; 20949 args.argi2 = status; 20950 args.arg3 = estMillis; 20951 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20952 20953 synchronized (mLastStatus) { 20954 mLastStatus.put(moveId, status); 20955 } 20956 } 20957 } 20958 20959 private final static class OnPermissionChangeListeners extends Handler { 20960 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20961 20962 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20963 new RemoteCallbackList<>(); 20964 20965 public OnPermissionChangeListeners(Looper looper) { 20966 super(looper); 20967 } 20968 20969 @Override 20970 public void handleMessage(Message msg) { 20971 switch (msg.what) { 20972 case MSG_ON_PERMISSIONS_CHANGED: { 20973 final int uid = msg.arg1; 20974 handleOnPermissionsChanged(uid); 20975 } break; 20976 } 20977 } 20978 20979 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20980 mPermissionListeners.register(listener); 20981 20982 } 20983 20984 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20985 mPermissionListeners.unregister(listener); 20986 } 20987 20988 public void onPermissionsChanged(int uid) { 20989 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20990 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20991 } 20992 } 20993 20994 private void handleOnPermissionsChanged(int uid) { 20995 final int count = mPermissionListeners.beginBroadcast(); 20996 try { 20997 for (int i = 0; i < count; i++) { 20998 IOnPermissionsChangeListener callback = mPermissionListeners 20999 .getBroadcastItem(i); 21000 try { 21001 callback.onPermissionsChanged(uid); 21002 } catch (RemoteException e) { 21003 Log.e(TAG, "Permission listener is dead", e); 21004 } 21005 } 21006 } finally { 21007 mPermissionListeners.finishBroadcast(); 21008 } 21009 } 21010 } 21011 21012 private class PackageManagerInternalImpl extends PackageManagerInternal { 21013 @Override 21014 public void setLocationPackagesProvider(PackagesProvider provider) { 21015 synchronized (mPackages) { 21016 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 21017 } 21018 } 21019 21020 @Override 21021 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 21022 synchronized (mPackages) { 21023 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 21024 } 21025 } 21026 21027 @Override 21028 public void setSmsAppPackagesProvider(PackagesProvider provider) { 21029 synchronized (mPackages) { 21030 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 21031 } 21032 } 21033 21034 @Override 21035 public void setDialerAppPackagesProvider(PackagesProvider provider) { 21036 synchronized (mPackages) { 21037 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 21038 } 21039 } 21040 21041 @Override 21042 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 21043 synchronized (mPackages) { 21044 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 21045 } 21046 } 21047 21048 @Override 21049 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 21050 synchronized (mPackages) { 21051 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 21052 } 21053 } 21054 21055 @Override 21056 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 21057 synchronized (mPackages) { 21058 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 21059 packageName, userId); 21060 } 21061 } 21062 21063 @Override 21064 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 21065 synchronized (mPackages) { 21066 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 21067 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 21068 packageName, userId); 21069 } 21070 } 21071 21072 @Override 21073 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 21074 synchronized (mPackages) { 21075 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 21076 packageName, userId); 21077 } 21078 } 21079 21080 @Override 21081 public void setKeepUninstalledPackages(final List<String> packageList) { 21082 Preconditions.checkNotNull(packageList); 21083 List<String> removedFromList = null; 21084 synchronized (mPackages) { 21085 if (mKeepUninstalledPackages != null) { 21086 final int packagesCount = mKeepUninstalledPackages.size(); 21087 for (int i = 0; i < packagesCount; i++) { 21088 String oldPackage = mKeepUninstalledPackages.get(i); 21089 if (packageList != null && packageList.contains(oldPackage)) { 21090 continue; 21091 } 21092 if (removedFromList == null) { 21093 removedFromList = new ArrayList<>(); 21094 } 21095 removedFromList.add(oldPackage); 21096 } 21097 } 21098 mKeepUninstalledPackages = new ArrayList<>(packageList); 21099 if (removedFromList != null) { 21100 final int removedCount = removedFromList.size(); 21101 for (int i = 0; i < removedCount; i++) { 21102 deletePackageIfUnusedLPr(removedFromList.get(i)); 21103 } 21104 } 21105 } 21106 } 21107 21108 @Override 21109 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21110 synchronized (mPackages) { 21111 // If we do not support permission review, done. 21112 if (!mPermissionReviewRequired) { 21113 return false; 21114 } 21115 21116 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21117 if (packageSetting == null) { 21118 return false; 21119 } 21120 21121 // Permission review applies only to apps not supporting the new permission model. 21122 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21123 return false; 21124 } 21125 21126 // Legacy apps have the permission and get user consent on launch. 21127 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21128 return permissionsState.isPermissionReviewRequired(userId); 21129 } 21130 } 21131 21132 @Override 21133 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21134 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21135 } 21136 21137 @Override 21138 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21139 int userId) { 21140 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21141 } 21142 21143 @Override 21144 public void setDeviceAndProfileOwnerPackages( 21145 int deviceOwnerUserId, String deviceOwnerPackage, 21146 SparseArray<String> profileOwnerPackages) { 21147 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21148 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21149 } 21150 21151 @Override 21152 public boolean isPackageDataProtected(int userId, String packageName) { 21153 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21154 } 21155 21156 @Override 21157 public boolean wasPackageEverLaunched(String packageName, int userId) { 21158 synchronized (mPackages) { 21159 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21160 } 21161 } 21162 21163 @Override 21164 public void grantRuntimePermission(String packageName, String name, int userId, 21165 boolean overridePolicy) { 21166 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 21167 overridePolicy); 21168 } 21169 21170 @Override 21171 public void revokeRuntimePermission(String packageName, String name, int userId, 21172 boolean overridePolicy) { 21173 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 21174 overridePolicy); 21175 } 21176 } 21177 21178 @Override 21179 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21180 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21181 synchronized (mPackages) { 21182 final long identity = Binder.clearCallingIdentity(); 21183 try { 21184 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21185 packageNames, userId); 21186 } finally { 21187 Binder.restoreCallingIdentity(identity); 21188 } 21189 } 21190 } 21191 21192 private static void enforceSystemOrPhoneCaller(String tag) { 21193 int callingUid = Binder.getCallingUid(); 21194 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21195 throw new SecurityException( 21196 "Cannot call " + tag + " from UID " + callingUid); 21197 } 21198 } 21199 21200 boolean isHistoricalPackageUsageAvailable() { 21201 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21202 } 21203 21204 /** 21205 * Return a <b>copy</b> of the collection of packages known to the package manager. 21206 * @return A copy of the values of mPackages. 21207 */ 21208 Collection<PackageParser.Package> getPackages() { 21209 synchronized (mPackages) { 21210 return new ArrayList<>(mPackages.values()); 21211 } 21212 } 21213 21214 /** 21215 * Logs process start information (including base APK hash) to the security log. 21216 * @hide 21217 */ 21218 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21219 String apkFile, int pid) { 21220 if (!SecurityLog.isLoggingEnabled()) { 21221 return; 21222 } 21223 Bundle data = new Bundle(); 21224 data.putLong("startTimestamp", System.currentTimeMillis()); 21225 data.putString("processName", processName); 21226 data.putInt("uid", uid); 21227 data.putString("seinfo", seinfo); 21228 data.putString("apkFile", apkFile); 21229 data.putInt("pid", pid); 21230 Message msg = mProcessLoggingHandler.obtainMessage( 21231 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21232 msg.setData(data); 21233 mProcessLoggingHandler.sendMessage(msg); 21234 } 21235 21236 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21237 return mCompilerStats.getPackageStats(pkgName); 21238 } 21239 21240 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21241 return getOrCreateCompilerPackageStats(pkg.packageName); 21242 } 21243 21244 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21245 return mCompilerStats.getOrCreatePackageStats(pkgName); 21246 } 21247 21248 public void deleteCompilerPackageStats(String pkgName) { 21249 mCompilerStats.deletePackageStats(pkgName); 21250 } 21251} 21252