PackageManagerService.java revision c480bdafdb984f024bb13a8f0de9b6e1efd34bcd
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.SystemClock; 189import android.os.SystemProperties; 190import android.os.Trace; 191import android.os.UserHandle; 192import android.os.UserManager; 193import android.os.UserManagerInternal; 194import android.os.storage.IMountService; 195import android.os.storage.MountServiceInternal; 196import android.os.storage.StorageEventListener; 197import android.os.storage.StorageManager; 198import android.os.storage.VolumeInfo; 199import android.os.storage.VolumeRecord; 200import android.provider.Settings.Global; 201import android.provider.Settings.Secure; 202import android.security.KeyStore; 203import android.security.SystemKeyStore; 204import android.system.ErrnoException; 205import android.system.Os; 206import android.text.TextUtils; 207import android.text.format.DateUtils; 208import android.util.ArrayMap; 209import android.util.ArraySet; 210import android.util.DisplayMetrics; 211import android.util.EventLog; 212import android.util.ExceptionUtils; 213import android.util.Log; 214import android.util.LogPrinter; 215import android.util.MathUtils; 216import android.util.Pair; 217import android.util.PrintStreamPrinter; 218import android.util.Slog; 219import android.util.SparseArray; 220import android.util.SparseBooleanArray; 221import android.util.SparseIntArray; 222import android.util.Xml; 223import android.util.jar.StrictJarFile; 224import android.view.Display; 225 226import com.android.internal.R; 227import com.android.internal.annotations.GuardedBy; 228import com.android.internal.app.IMediaContainerService; 229import com.android.internal.app.ResolverActivity; 230import com.android.internal.content.NativeLibraryHelper; 231import com.android.internal.content.PackageHelper; 232import com.android.internal.logging.MetricsLogger; 233import com.android.internal.os.IParcelFileDescriptorFactory; 234import com.android.internal.os.SomeArgs; 235import com.android.internal.os.Zygote; 236import com.android.internal.telephony.CarrierAppUtils; 237import com.android.internal.util.ArrayUtils; 238import com.android.internal.util.FastPrintWriter; 239import com.android.internal.util.FastXmlSerializer; 240import com.android.internal.util.IndentingPrintWriter; 241import com.android.internal.util.Preconditions; 242import com.android.internal.util.XmlUtils; 243import com.android.server.AttributeCache; 244import com.android.server.EventLogTags; 245import com.android.server.FgThread; 246import com.android.server.IntentResolver; 247import com.android.server.LocalServices; 248import com.android.server.ServiceThread; 249import com.android.server.SystemConfig; 250import com.android.server.Watchdog; 251import com.android.server.net.NetworkPolicyManagerInternal; 252import com.android.server.pm.Installer.InstallerException; 253import com.android.server.pm.PermissionsState.PermissionState; 254import com.android.server.pm.Settings.DatabaseVersion; 255import com.android.server.pm.Settings.VersionInfo; 256import com.android.server.pm.dex.DexManager; 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.HashMap; 300import java.util.Iterator; 301import java.util.List; 302import java.util.Map; 303import java.util.Objects; 304import java.util.Set; 305import java.util.concurrent.CountDownLatch; 306import java.util.concurrent.TimeUnit; 307import java.util.concurrent.atomic.AtomicBoolean; 308import java.util.concurrent.atomic.AtomicInteger; 309 310/** 311 * Keep track of all those APKs everywhere. 312 * <p> 313 * Internally there are two important locks: 314 * <ul> 315 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 316 * and other related state. It is a fine-grained lock that should only be held 317 * momentarily, as it's one of the most contended locks in the system. 318 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 319 * operations typically involve heavy lifting of application data on disk. Since 320 * {@code installd} is single-threaded, and it's operations can often be slow, 321 * this lock should never be acquired while already holding {@link #mPackages}. 322 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 323 * holding {@link #mInstallLock}. 324 * </ul> 325 * Many internal methods rely on the caller to hold the appropriate locks, and 326 * this contract is expressed through method name suffixes: 327 * <ul> 328 * <li>fooLI(): the caller must hold {@link #mInstallLock} 329 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 330 * being modified must be frozen 331 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 332 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 333 * </ul> 334 * <p> 335 * Because this class is very central to the platform's security; please run all 336 * CTS and unit tests whenever making modifications: 337 * 338 * <pre> 339 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 340 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 341 * </pre> 342 */ 343public class PackageManagerService extends IPackageManager.Stub { 344 static final String TAG = "PackageManager"; 345 static final boolean DEBUG_SETTINGS = false; 346 static final boolean DEBUG_PREFERRED = false; 347 static final boolean DEBUG_UPGRADE = false; 348 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 349 private static final boolean DEBUG_BACKUP = false; 350 private static final boolean DEBUG_INSTALL = false; 351 private static final boolean DEBUG_REMOVE = false; 352 private static final boolean DEBUG_BROADCASTS = false; 353 private static final boolean DEBUG_SHOW_INFO = false; 354 private static final boolean DEBUG_PACKAGE_INFO = false; 355 private static final boolean DEBUG_INTENT_MATCHING = false; 356 private static final boolean DEBUG_PACKAGE_SCANNING = false; 357 private static final boolean DEBUG_VERIFY = false; 358 private static final boolean DEBUG_FILTERS = false; 359 360 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 361 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 362 // user, but by default initialize to this. 363 static final boolean DEBUG_DEXOPT = false; 364 365 private static final boolean DEBUG_ABI_SELECTION = false; 366 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 367 private static final boolean DEBUG_TRIAGED_MISSING = false; 368 private static final boolean DEBUG_APP_DATA = false; 369 370 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 boolean ENABLE_QUOTA = 376 SystemProperties.getBoolean("persist.fw.quota", false); 377 378 private static final int RADIO_UID = Process.PHONE_UID; 379 private static final int LOG_UID = Process.LOG_UID; 380 private static final int NFC_UID = Process.NFC_UID; 381 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 382 private static final int SHELL_UID = Process.SHELL_UID; 383 384 // Cap the size of permission trees that 3rd party apps can define 385 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 386 387 // Suffix used during package installation when copying/moving 388 // package apks to install directory. 389 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 390 391 static final int SCAN_NO_DEX = 1<<1; 392 static final int SCAN_FORCE_DEX = 1<<2; 393 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 394 static final int SCAN_NEW_INSTALL = 1<<4; 395 static final int SCAN_NO_PATHS = 1<<5; 396 static final int SCAN_UPDATE_TIME = 1<<6; 397 static final int SCAN_DEFER_DEX = 1<<7; 398 static final int SCAN_BOOTING = 1<<8; 399 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 400 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 401 static final int SCAN_REPLACING = 1<<11; 402 static final int SCAN_REQUIRE_KNOWN = 1<<12; 403 static final int SCAN_MOVE = 1<<13; 404 static final int SCAN_INITIAL = 1<<14; 405 static final int SCAN_CHECK_ONLY = 1<<15; 406 static final int SCAN_DONT_KILL_APP = 1<<17; 407 static final int SCAN_IGNORE_FROZEN = 1<<18; 408 409 static final int REMOVE_CHATTY = 1<<16; 410 411 private static final int[] EMPTY_INT_ARRAY = new int[0]; 412 413 /** 414 * Timeout (in milliseconds) after which the watchdog should declare that 415 * our handler thread is wedged. The usual default for such things is one 416 * minute but we sometimes do very lengthy I/O operations on this thread, 417 * such as installing multi-gigabyte applications, so ours needs to be longer. 418 */ 419 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 420 421 /** 422 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 423 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 424 * settings entry if available, otherwise we use the hardcoded default. If it's been 425 * more than this long since the last fstrim, we force one during the boot sequence. 426 * 427 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 428 * one gets run at the next available charging+idle time. This final mandatory 429 * no-fstrim check kicks in only of the other scheduling criteria is never met. 430 */ 431 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 432 433 /** 434 * Whether verification is enabled by default. 435 */ 436 private static final boolean DEFAULT_VERIFY_ENABLE = true; 437 438 /** 439 * The default maximum time to wait for the verification agent to return in 440 * milliseconds. 441 */ 442 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 443 444 /** 445 * The default response for package verification timeout. 446 * 447 * This can be either PackageManager.VERIFICATION_ALLOW or 448 * PackageManager.VERIFICATION_REJECT. 449 */ 450 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 451 452 static final String PLATFORM_PACKAGE_NAME = "android"; 453 454 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 455 456 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 457 DEFAULT_CONTAINER_PACKAGE, 458 "com.android.defcontainer.DefaultContainerService"); 459 460 private static final String KILL_APP_REASON_GIDS_CHANGED = 461 "permission grant or revoke changed gids"; 462 463 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 464 "permissions revoked"; 465 466 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 467 468 private static final String PACKAGE_SCHEME = "package"; 469 470 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 471 /** 472 * If VENDOR_OVERLAY_SKU_PROPERTY is set, search for runtime resource overlay APKs in 473 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_SKU_PROPERTY> rather than in 474 * VENDOR_OVERLAY_DIR. 475 */ 476 private static final String VENDOR_OVERLAY_SKU_PROPERTY = "ro.boot.vendor.overlay.sku"; 477 478 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000; 479 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5; 480 481 /** Permission grant: not grant the permission. */ 482 private static final int GRANT_DENIED = 1; 483 484 /** Permission grant: grant the permission as an install permission. */ 485 private static final int GRANT_INSTALL = 2; 486 487 /** Permission grant: grant the permission as a runtime one. */ 488 private static final int GRANT_RUNTIME = 3; 489 490 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 491 private static final int GRANT_UPGRADE = 4; 492 493 /** Canonical intent used to identify what counts as a "web browser" app */ 494 private static final Intent sBrowserIntent; 495 static { 496 sBrowserIntent = new Intent(); 497 sBrowserIntent.setAction(Intent.ACTION_VIEW); 498 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 499 sBrowserIntent.setData(Uri.parse("http:")); 500 } 501 502 /** 503 * The set of all protected actions [i.e. those actions for which a high priority 504 * intent filter is disallowed]. 505 */ 506 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 507 static { 508 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 509 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 510 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 511 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 512 } 513 514 // Compilation reasons. 515 public static final int REASON_FIRST_BOOT = 0; 516 public static final int REASON_BOOT = 1; 517 public static final int REASON_INSTALL = 2; 518 public static final int REASON_BACKGROUND_DEXOPT = 3; 519 public static final int REASON_AB_OTA = 4; 520 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 521 public static final int REASON_SHARED_APK = 6; 522 public static final int REASON_FORCED_DEXOPT = 7; 523 public static final int REASON_CORE_APP = 8; 524 525 public static final int REASON_LAST = REASON_CORE_APP; 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 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 715 // is used by other apps). 716 private final DexManager mDexManager; 717 718 private AtomicInteger mNextMoveId = new AtomicInteger(); 719 private final MoveCallbacks mMoveCallbacks; 720 721 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 722 723 // Cache of users who need badging. 724 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 725 726 /** Token for keys in mPendingVerification. */ 727 private int mPendingVerificationToken = 0; 728 729 volatile boolean mSystemReady; 730 volatile boolean mSafeMode; 731 volatile boolean mHasSystemUidErrors; 732 733 ApplicationInfo mAndroidApplication; 734 final ActivityInfo mResolveActivity = new ActivityInfo(); 735 final ResolveInfo mResolveInfo = new ResolveInfo(); 736 ComponentName mResolveComponentName; 737 PackageParser.Package mPlatformPackage; 738 ComponentName mCustomResolverComponentName; 739 740 boolean mResolverReplaced = false; 741 742 private final @Nullable ComponentName mIntentFilterVerifierComponent; 743 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 744 745 private int mIntentFilterVerificationToken = 0; 746 747 /** Component that knows whether or not an ephemeral application exists */ 748 final ComponentName mEphemeralResolverComponent; 749 /** The service connection to the ephemeral resolver */ 750 final EphemeralResolverConnection mEphemeralResolverConnection; 751 752 /** Component used to install ephemeral applications */ 753 final ComponentName mEphemeralInstallerComponent; 754 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 755 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 756 757 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 758 = new SparseArray<IntentFilterVerificationState>(); 759 760 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 761 762 // List of packages names to keep cached, even if they are uninstalled for all users 763 private List<String> mKeepUninstalledPackages; 764 765 private UserManagerInternal mUserManagerInternal; 766 767 private static class IFVerificationParams { 768 PackageParser.Package pkg; 769 boolean replacing; 770 int userId; 771 int verifierUid; 772 773 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 774 int _userId, int _verifierUid) { 775 pkg = _pkg; 776 replacing = _replacing; 777 userId = _userId; 778 replacing = _replacing; 779 verifierUid = _verifierUid; 780 } 781 } 782 783 private interface IntentFilterVerifier<T extends IntentFilter> { 784 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 785 T filter, String packageName); 786 void startVerifications(int userId); 787 void receiveVerificationResponse(int verificationId); 788 } 789 790 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 791 private Context mContext; 792 private ComponentName mIntentFilterVerifierComponent; 793 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 794 795 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 796 mContext = context; 797 mIntentFilterVerifierComponent = verifierComponent; 798 } 799 800 private String getDefaultScheme() { 801 return IntentFilter.SCHEME_HTTPS; 802 } 803 804 @Override 805 public void startVerifications(int userId) { 806 // Launch verifications requests 807 int count = mCurrentIntentFilterVerifications.size(); 808 for (int n=0; n<count; n++) { 809 int verificationId = mCurrentIntentFilterVerifications.get(n); 810 final IntentFilterVerificationState ivs = 811 mIntentFilterVerificationStates.get(verificationId); 812 813 String packageName = ivs.getPackageName(); 814 815 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 816 final int filterCount = filters.size(); 817 ArraySet<String> domainsSet = new ArraySet<>(); 818 for (int m=0; m<filterCount; m++) { 819 PackageParser.ActivityIntentInfo filter = filters.get(m); 820 domainsSet.addAll(filter.getHostsList()); 821 } 822 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 823 synchronized (mPackages) { 824 if (mSettings.createIntentFilterVerificationIfNeededLPw( 825 packageName, domainsList) != null) { 826 scheduleWriteSettingsLocked(); 827 } 828 } 829 sendVerificationRequest(userId, verificationId, ivs); 830 } 831 mCurrentIntentFilterVerifications.clear(); 832 } 833 834 private void sendVerificationRequest(int userId, int verificationId, 835 IntentFilterVerificationState ivs) { 836 837 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 838 verificationIntent.putExtra( 839 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 840 verificationId); 841 verificationIntent.putExtra( 842 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 843 getDefaultScheme()); 844 verificationIntent.putExtra( 845 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 846 ivs.getHostsString()); 847 verificationIntent.putExtra( 848 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 849 ivs.getPackageName()); 850 verificationIntent.setComponent(mIntentFilterVerifierComponent); 851 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 852 853 UserHandle user = new UserHandle(userId); 854 mContext.sendBroadcastAsUser(verificationIntent, user); 855 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 856 "Sending IntentFilter verification broadcast"); 857 } 858 859 public void receiveVerificationResponse(int verificationId) { 860 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 861 862 final boolean verified = ivs.isVerified(); 863 864 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 865 final int count = filters.size(); 866 if (DEBUG_DOMAIN_VERIFICATION) { 867 Slog.i(TAG, "Received verification response " + verificationId 868 + " for " + count + " filters, verified=" + verified); 869 } 870 for (int n=0; n<count; n++) { 871 PackageParser.ActivityIntentInfo filter = filters.get(n); 872 filter.setVerified(verified); 873 874 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 875 + " verified with result:" + verified + " and hosts:" 876 + ivs.getHostsString()); 877 } 878 879 mIntentFilterVerificationStates.remove(verificationId); 880 881 final String packageName = ivs.getPackageName(); 882 IntentFilterVerificationInfo ivi = null; 883 884 synchronized (mPackages) { 885 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 886 } 887 if (ivi == null) { 888 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 889 + verificationId + " packageName:" + packageName); 890 return; 891 } 892 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 893 "Updating IntentFilterVerificationInfo for package " + packageName 894 +" verificationId:" + verificationId); 895 896 synchronized (mPackages) { 897 if (verified) { 898 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 899 } else { 900 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 901 } 902 scheduleWriteSettingsLocked(); 903 904 final int userId = ivs.getUserId(); 905 if (userId != UserHandle.USER_ALL) { 906 final int userStatus = 907 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 908 909 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 910 boolean needUpdate = false; 911 912 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 913 // already been set by the User thru the Disambiguation dialog 914 switch (userStatus) { 915 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 916 if (verified) { 917 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 918 } else { 919 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 920 } 921 needUpdate = true; 922 break; 923 924 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 925 if (verified) { 926 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 927 needUpdate = true; 928 } 929 break; 930 931 default: 932 // Nothing to do 933 } 934 935 if (needUpdate) { 936 mSettings.updateIntentFilterVerificationStatusLPw( 937 packageName, updatedStatus, userId); 938 scheduleWritePackageRestrictionsLocked(userId); 939 } 940 } 941 } 942 } 943 944 @Override 945 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 946 ActivityIntentInfo filter, String packageName) { 947 if (!hasValidDomains(filter)) { 948 return false; 949 } 950 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 951 if (ivs == null) { 952 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 953 packageName); 954 } 955 if (DEBUG_DOMAIN_VERIFICATION) { 956 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 957 } 958 ivs.addFilter(filter); 959 return true; 960 } 961 962 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 963 int userId, int verificationId, String packageName) { 964 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 965 verifierUid, userId, packageName); 966 ivs.setPendingState(); 967 synchronized (mPackages) { 968 mIntentFilterVerificationStates.append(verificationId, ivs); 969 mCurrentIntentFilterVerifications.add(verificationId); 970 } 971 return ivs; 972 } 973 } 974 975 private static boolean hasValidDomains(ActivityIntentInfo filter) { 976 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 977 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 978 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 979 } 980 981 // Set of pending broadcasts for aggregating enable/disable of components. 982 static class PendingPackageBroadcasts { 983 // for each user id, a map of <package name -> components within that package> 984 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 985 986 public PendingPackageBroadcasts() { 987 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 988 } 989 990 public ArrayList<String> get(int userId, String packageName) { 991 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 992 return packages.get(packageName); 993 } 994 995 public void put(int userId, String packageName, ArrayList<String> components) { 996 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 997 packages.put(packageName, components); 998 } 999 1000 public void remove(int userId, String packageName) { 1001 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1002 if (packages != null) { 1003 packages.remove(packageName); 1004 } 1005 } 1006 1007 public void remove(int userId) { 1008 mUidMap.remove(userId); 1009 } 1010 1011 public int userIdCount() { 1012 return mUidMap.size(); 1013 } 1014 1015 public int userIdAt(int n) { 1016 return mUidMap.keyAt(n); 1017 } 1018 1019 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1020 return mUidMap.get(userId); 1021 } 1022 1023 public int size() { 1024 // total number of pending broadcast entries across all userIds 1025 int num = 0; 1026 for (int i = 0; i< mUidMap.size(); i++) { 1027 num += mUidMap.valueAt(i).size(); 1028 } 1029 return num; 1030 } 1031 1032 public void clear() { 1033 mUidMap.clear(); 1034 } 1035 1036 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1037 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1038 if (map == null) { 1039 map = new ArrayMap<String, ArrayList<String>>(); 1040 mUidMap.put(userId, map); 1041 } 1042 return map; 1043 } 1044 } 1045 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1046 1047 // Service Connection to remote media container service to copy 1048 // package uri's from external media onto secure containers 1049 // or internal storage. 1050 private IMediaContainerService mContainerService = null; 1051 1052 static final int SEND_PENDING_BROADCAST = 1; 1053 static final int MCS_BOUND = 3; 1054 static final int END_COPY = 4; 1055 static final int INIT_COPY = 5; 1056 static final int MCS_UNBIND = 6; 1057 static final int START_CLEANING_PACKAGE = 7; 1058 static final int FIND_INSTALL_LOC = 8; 1059 static final int POST_INSTALL = 9; 1060 static final int MCS_RECONNECT = 10; 1061 static final int MCS_GIVE_UP = 11; 1062 static final int UPDATED_MEDIA_STATUS = 12; 1063 static final int WRITE_SETTINGS = 13; 1064 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1065 static final int PACKAGE_VERIFIED = 15; 1066 static final int CHECK_PENDING_VERIFICATION = 16; 1067 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1068 static final int INTENT_FILTER_VERIFIED = 18; 1069 static final int WRITE_PACKAGE_LIST = 19; 1070 1071 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1072 1073 // Delay time in millisecs 1074 static final int BROADCAST_DELAY = 10 * 1000; 1075 1076 static UserManagerService sUserManager; 1077 1078 // Stores a list of users whose package restrictions file needs to be updated 1079 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1080 1081 final private DefaultContainerConnection mDefContainerConn = 1082 new DefaultContainerConnection(); 1083 class DefaultContainerConnection implements ServiceConnection { 1084 public void onServiceConnected(ComponentName name, IBinder service) { 1085 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1086 IMediaContainerService imcs = 1087 IMediaContainerService.Stub.asInterface(service); 1088 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1089 } 1090 1091 public void onServiceDisconnected(ComponentName name) { 1092 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1093 } 1094 } 1095 1096 // Recordkeeping of restore-after-install operations that are currently in flight 1097 // between the Package Manager and the Backup Manager 1098 static class PostInstallData { 1099 public InstallArgs args; 1100 public PackageInstalledInfo res; 1101 1102 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1103 args = _a; 1104 res = _r; 1105 } 1106 } 1107 1108 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1109 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1110 1111 // XML tags for backup/restore of various bits of state 1112 private static final String TAG_PREFERRED_BACKUP = "pa"; 1113 private static final String TAG_DEFAULT_APPS = "da"; 1114 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1115 1116 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1117 private static final String TAG_ALL_GRANTS = "rt-grants"; 1118 private static final String TAG_GRANT = "grant"; 1119 private static final String ATTR_PACKAGE_NAME = "pkg"; 1120 1121 private static final String TAG_PERMISSION = "perm"; 1122 private static final String ATTR_PERMISSION_NAME = "name"; 1123 private static final String ATTR_IS_GRANTED = "g"; 1124 private static final String ATTR_USER_SET = "set"; 1125 private static final String ATTR_USER_FIXED = "fixed"; 1126 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1127 1128 // System/policy permission grants are not backed up 1129 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1130 FLAG_PERMISSION_POLICY_FIXED 1131 | FLAG_PERMISSION_SYSTEM_FIXED 1132 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1133 1134 // And we back up these user-adjusted states 1135 private static final int USER_RUNTIME_GRANT_MASK = 1136 FLAG_PERMISSION_USER_SET 1137 | FLAG_PERMISSION_USER_FIXED 1138 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1139 1140 final @Nullable String mRequiredVerifierPackage; 1141 final @NonNull String mRequiredInstallerPackage; 1142 final @NonNull String mRequiredUninstallerPackage; 1143 final @Nullable String mSetupWizardPackage; 1144 final @Nullable String mStorageManagerPackage; 1145 final @NonNull String mServicesSystemSharedLibraryPackageName; 1146 final @NonNull String mSharedSystemSharedLibraryPackageName; 1147 1148 final boolean mPermissionReviewRequired; 1149 1150 private final PackageUsage mPackageUsage = new PackageUsage(); 1151 private final CompilerStats mCompilerStats = new CompilerStats(); 1152 1153 class PackageHandler extends Handler { 1154 private boolean mBound = false; 1155 final ArrayList<HandlerParams> mPendingInstalls = 1156 new ArrayList<HandlerParams>(); 1157 1158 private boolean connectToService() { 1159 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1160 " DefaultContainerService"); 1161 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1162 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1163 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1164 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1165 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1166 mBound = true; 1167 return true; 1168 } 1169 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1170 return false; 1171 } 1172 1173 private void disconnectService() { 1174 mContainerService = null; 1175 mBound = false; 1176 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1177 mContext.unbindService(mDefContainerConn); 1178 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1179 } 1180 1181 PackageHandler(Looper looper) { 1182 super(looper); 1183 } 1184 1185 public void handleMessage(Message msg) { 1186 try { 1187 doHandleMessage(msg); 1188 } finally { 1189 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1190 } 1191 } 1192 1193 void doHandleMessage(Message msg) { 1194 switch (msg.what) { 1195 case INIT_COPY: { 1196 HandlerParams params = (HandlerParams) msg.obj; 1197 int idx = mPendingInstalls.size(); 1198 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1199 // If a bind was already initiated we dont really 1200 // need to do anything. The pending install 1201 // will be processed later on. 1202 if (!mBound) { 1203 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1204 System.identityHashCode(mHandler)); 1205 // If this is the only one pending we might 1206 // have to bind to the service again. 1207 if (!connectToService()) { 1208 Slog.e(TAG, "Failed to bind to media container service"); 1209 params.serviceError(); 1210 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1211 System.identityHashCode(mHandler)); 1212 if (params.traceMethod != null) { 1213 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1214 params.traceCookie); 1215 } 1216 return; 1217 } else { 1218 // Once we bind to the service, the first 1219 // pending request will be processed. 1220 mPendingInstalls.add(idx, params); 1221 } 1222 } else { 1223 mPendingInstalls.add(idx, params); 1224 // Already bound to the service. Just make 1225 // sure we trigger off processing the first request. 1226 if (idx == 0) { 1227 mHandler.sendEmptyMessage(MCS_BOUND); 1228 } 1229 } 1230 break; 1231 } 1232 case MCS_BOUND: { 1233 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1234 if (msg.obj != null) { 1235 mContainerService = (IMediaContainerService) msg.obj; 1236 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1237 System.identityHashCode(mHandler)); 1238 } 1239 if (mContainerService == null) { 1240 if (!mBound) { 1241 // Something seriously wrong since we are not bound and we are not 1242 // waiting for connection. Bail out. 1243 Slog.e(TAG, "Cannot bind to media container service"); 1244 for (HandlerParams params : mPendingInstalls) { 1245 // Indicate service bind error 1246 params.serviceError(); 1247 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1248 System.identityHashCode(params)); 1249 if (params.traceMethod != null) { 1250 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1251 params.traceMethod, params.traceCookie); 1252 } 1253 return; 1254 } 1255 mPendingInstalls.clear(); 1256 } else { 1257 Slog.w(TAG, "Waiting to connect to media container service"); 1258 } 1259 } else if (mPendingInstalls.size() > 0) { 1260 HandlerParams params = mPendingInstalls.get(0); 1261 if (params != null) { 1262 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1263 System.identityHashCode(params)); 1264 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1265 if (params.startCopy()) { 1266 // We are done... look for more work or to 1267 // go idle. 1268 if (DEBUG_SD_INSTALL) Log.i(TAG, 1269 "Checking for more work or unbind..."); 1270 // Delete pending install 1271 if (mPendingInstalls.size() > 0) { 1272 mPendingInstalls.remove(0); 1273 } 1274 if (mPendingInstalls.size() == 0) { 1275 if (mBound) { 1276 if (DEBUG_SD_INSTALL) Log.i(TAG, 1277 "Posting delayed MCS_UNBIND"); 1278 removeMessages(MCS_UNBIND); 1279 Message ubmsg = obtainMessage(MCS_UNBIND); 1280 // Unbind after a little delay, to avoid 1281 // continual thrashing. 1282 sendMessageDelayed(ubmsg, 10000); 1283 } 1284 } else { 1285 // There are more pending requests in queue. 1286 // Just post MCS_BOUND message to trigger processing 1287 // of next pending install. 1288 if (DEBUG_SD_INSTALL) Log.i(TAG, 1289 "Posting MCS_BOUND for next work"); 1290 mHandler.sendEmptyMessage(MCS_BOUND); 1291 } 1292 } 1293 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1294 } 1295 } else { 1296 // Should never happen ideally. 1297 Slog.w(TAG, "Empty queue"); 1298 } 1299 break; 1300 } 1301 case MCS_RECONNECT: { 1302 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1303 if (mPendingInstalls.size() > 0) { 1304 if (mBound) { 1305 disconnectService(); 1306 } 1307 if (!connectToService()) { 1308 Slog.e(TAG, "Failed to bind to media container service"); 1309 for (HandlerParams params : mPendingInstalls) { 1310 // Indicate service bind error 1311 params.serviceError(); 1312 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1313 System.identityHashCode(params)); 1314 } 1315 mPendingInstalls.clear(); 1316 } 1317 } 1318 break; 1319 } 1320 case MCS_UNBIND: { 1321 // If there is no actual work left, then time to unbind. 1322 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1323 1324 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1325 if (mBound) { 1326 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1327 1328 disconnectService(); 1329 } 1330 } else if (mPendingInstalls.size() > 0) { 1331 // There are more pending requests in queue. 1332 // Just post MCS_BOUND message to trigger processing 1333 // of next pending install. 1334 mHandler.sendEmptyMessage(MCS_BOUND); 1335 } 1336 1337 break; 1338 } 1339 case MCS_GIVE_UP: { 1340 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1341 HandlerParams params = mPendingInstalls.remove(0); 1342 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1343 System.identityHashCode(params)); 1344 break; 1345 } 1346 case SEND_PENDING_BROADCAST: { 1347 String packages[]; 1348 ArrayList<String> components[]; 1349 int size = 0; 1350 int uids[]; 1351 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1352 synchronized (mPackages) { 1353 if (mPendingBroadcasts == null) { 1354 return; 1355 } 1356 size = mPendingBroadcasts.size(); 1357 if (size <= 0) { 1358 // Nothing to be done. Just return 1359 return; 1360 } 1361 packages = new String[size]; 1362 components = new ArrayList[size]; 1363 uids = new int[size]; 1364 int i = 0; // filling out the above arrays 1365 1366 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1367 int packageUserId = mPendingBroadcasts.userIdAt(n); 1368 Iterator<Map.Entry<String, ArrayList<String>>> it 1369 = mPendingBroadcasts.packagesForUserId(packageUserId) 1370 .entrySet().iterator(); 1371 while (it.hasNext() && i < size) { 1372 Map.Entry<String, ArrayList<String>> ent = it.next(); 1373 packages[i] = ent.getKey(); 1374 components[i] = ent.getValue(); 1375 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1376 uids[i] = (ps != null) 1377 ? UserHandle.getUid(packageUserId, ps.appId) 1378 : -1; 1379 i++; 1380 } 1381 } 1382 size = i; 1383 mPendingBroadcasts.clear(); 1384 } 1385 // Send broadcasts 1386 for (int i = 0; i < size; i++) { 1387 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1388 } 1389 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1390 break; 1391 } 1392 case START_CLEANING_PACKAGE: { 1393 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1394 final String packageName = (String)msg.obj; 1395 final int userId = msg.arg1; 1396 final boolean andCode = msg.arg2 != 0; 1397 synchronized (mPackages) { 1398 if (userId == UserHandle.USER_ALL) { 1399 int[] users = sUserManager.getUserIds(); 1400 for (int user : users) { 1401 mSettings.addPackageToCleanLPw( 1402 new PackageCleanItem(user, packageName, andCode)); 1403 } 1404 } else { 1405 mSettings.addPackageToCleanLPw( 1406 new PackageCleanItem(userId, packageName, andCode)); 1407 } 1408 } 1409 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1410 startCleaningPackages(); 1411 } break; 1412 case POST_INSTALL: { 1413 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1414 1415 PostInstallData data = mRunningInstalls.get(msg.arg1); 1416 final boolean didRestore = (msg.arg2 != 0); 1417 mRunningInstalls.delete(msg.arg1); 1418 1419 if (data != null) { 1420 InstallArgs args = data.args; 1421 PackageInstalledInfo parentRes = data.res; 1422 1423 final boolean grantPermissions = (args.installFlags 1424 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1425 final boolean killApp = (args.installFlags 1426 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1427 final String[] grantedPermissions = args.installGrantPermissions; 1428 1429 // Handle the parent package 1430 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1431 grantedPermissions, didRestore, args.installerPackageName, 1432 args.observer); 1433 1434 // Handle the child packages 1435 final int childCount = (parentRes.addedChildPackages != null) 1436 ? parentRes.addedChildPackages.size() : 0; 1437 for (int i = 0; i < childCount; i++) { 1438 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1439 handlePackagePostInstall(childRes, grantPermissions, killApp, 1440 grantedPermissions, false, args.installerPackageName, 1441 args.observer); 1442 } 1443 1444 // Log tracing if needed 1445 if (args.traceMethod != null) { 1446 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1447 args.traceCookie); 1448 } 1449 } else { 1450 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1451 } 1452 1453 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1454 } break; 1455 case UPDATED_MEDIA_STATUS: { 1456 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1457 boolean reportStatus = msg.arg1 == 1; 1458 boolean doGc = msg.arg2 == 1; 1459 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1460 if (doGc) { 1461 // Force a gc to clear up stale containers. 1462 Runtime.getRuntime().gc(); 1463 } 1464 if (msg.obj != null) { 1465 @SuppressWarnings("unchecked") 1466 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1467 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1468 // Unload containers 1469 unloadAllContainers(args); 1470 } 1471 if (reportStatus) { 1472 try { 1473 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1474 PackageHelper.getMountService().finishMediaUpdate(); 1475 } catch (RemoteException e) { 1476 Log.e(TAG, "MountService not running?"); 1477 } 1478 } 1479 } break; 1480 case WRITE_SETTINGS: { 1481 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1482 synchronized (mPackages) { 1483 removeMessages(WRITE_SETTINGS); 1484 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1485 mSettings.writeLPr(); 1486 mDirtyUsers.clear(); 1487 } 1488 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1489 } break; 1490 case WRITE_PACKAGE_RESTRICTIONS: { 1491 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1492 synchronized (mPackages) { 1493 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1494 for (int userId : mDirtyUsers) { 1495 mSettings.writePackageRestrictionsLPr(userId); 1496 } 1497 mDirtyUsers.clear(); 1498 } 1499 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1500 } break; 1501 case WRITE_PACKAGE_LIST: { 1502 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1503 synchronized (mPackages) { 1504 removeMessages(WRITE_PACKAGE_LIST); 1505 mSettings.writePackageListLPr(msg.arg1); 1506 } 1507 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1508 } break; 1509 case CHECK_PENDING_VERIFICATION: { 1510 final int verificationId = msg.arg1; 1511 final PackageVerificationState state = mPendingVerification.get(verificationId); 1512 1513 if ((state != null) && !state.timeoutExtended()) { 1514 final InstallArgs args = state.getInstallArgs(); 1515 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1516 1517 Slog.i(TAG, "Verification timed out for " + originUri); 1518 mPendingVerification.remove(verificationId); 1519 1520 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1521 1522 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1523 Slog.i(TAG, "Continuing with installation of " + originUri); 1524 state.setVerifierResponse(Binder.getCallingUid(), 1525 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1526 broadcastPackageVerified(verificationId, originUri, 1527 PackageManager.VERIFICATION_ALLOW, 1528 state.getInstallArgs().getUser()); 1529 try { 1530 ret = args.copyApk(mContainerService, true); 1531 } catch (RemoteException e) { 1532 Slog.e(TAG, "Could not contact the ContainerService"); 1533 } 1534 } else { 1535 broadcastPackageVerified(verificationId, originUri, 1536 PackageManager.VERIFICATION_REJECT, 1537 state.getInstallArgs().getUser()); 1538 } 1539 1540 Trace.asyncTraceEnd( 1541 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1542 1543 processPendingInstall(args, ret); 1544 mHandler.sendEmptyMessage(MCS_UNBIND); 1545 } 1546 break; 1547 } 1548 case PACKAGE_VERIFIED: { 1549 final int verificationId = msg.arg1; 1550 1551 final PackageVerificationState state = mPendingVerification.get(verificationId); 1552 if (state == null) { 1553 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1554 break; 1555 } 1556 1557 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1558 1559 state.setVerifierResponse(response.callerUid, response.code); 1560 1561 if (state.isVerificationComplete()) { 1562 mPendingVerification.remove(verificationId); 1563 1564 final InstallArgs args = state.getInstallArgs(); 1565 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1566 1567 int ret; 1568 if (state.isInstallAllowed()) { 1569 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1570 broadcastPackageVerified(verificationId, originUri, 1571 response.code, state.getInstallArgs().getUser()); 1572 try { 1573 ret = args.copyApk(mContainerService, true); 1574 } catch (RemoteException e) { 1575 Slog.e(TAG, "Could not contact the ContainerService"); 1576 } 1577 } else { 1578 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1579 } 1580 1581 Trace.asyncTraceEnd( 1582 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1583 1584 processPendingInstall(args, ret); 1585 mHandler.sendEmptyMessage(MCS_UNBIND); 1586 } 1587 1588 break; 1589 } 1590 case START_INTENT_FILTER_VERIFICATIONS: { 1591 IFVerificationParams params = (IFVerificationParams) msg.obj; 1592 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1593 params.replacing, params.pkg); 1594 break; 1595 } 1596 case INTENT_FILTER_VERIFIED: { 1597 final int verificationId = msg.arg1; 1598 1599 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1600 verificationId); 1601 if (state == null) { 1602 Slog.w(TAG, "Invalid IntentFilter verification token " 1603 + verificationId + " received"); 1604 break; 1605 } 1606 1607 final int userId = state.getUserId(); 1608 1609 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1610 "Processing IntentFilter verification with token:" 1611 + verificationId + " and userId:" + userId); 1612 1613 final IntentFilterVerificationResponse response = 1614 (IntentFilterVerificationResponse) msg.obj; 1615 1616 state.setVerifierResponse(response.callerUid, response.code); 1617 1618 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1619 "IntentFilter verification with token:" + verificationId 1620 + " and userId:" + userId 1621 + " is settings verifier response with response code:" 1622 + response.code); 1623 1624 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1625 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1626 + response.getFailedDomainsString()); 1627 } 1628 1629 if (state.isVerificationComplete()) { 1630 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1631 } else { 1632 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1633 "IntentFilter verification with token:" + verificationId 1634 + " was not said to be complete"); 1635 } 1636 1637 break; 1638 } 1639 } 1640 } 1641 } 1642 1643 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1644 boolean killApp, String[] grantedPermissions, 1645 boolean launchedForRestore, String installerPackage, 1646 IPackageInstallObserver2 installObserver) { 1647 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1648 // Send the removed broadcasts 1649 if (res.removedInfo != null) { 1650 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1651 } 1652 1653 // Now that we successfully installed the package, grant runtime 1654 // permissions if requested before broadcasting the install. 1655 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1656 >= Build.VERSION_CODES.M) { 1657 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1658 } 1659 1660 final boolean update = res.removedInfo != null 1661 && res.removedInfo.removedPackage != null; 1662 1663 // If this is the first time we have child packages for a disabled privileged 1664 // app that had no children, we grant requested runtime permissions to the new 1665 // children if the parent on the system image had them already granted. 1666 if (res.pkg.parentPackage != null) { 1667 synchronized (mPackages) { 1668 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1669 } 1670 } 1671 1672 synchronized (mPackages) { 1673 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1674 } 1675 1676 final String packageName = res.pkg.applicationInfo.packageName; 1677 Bundle extras = new Bundle(1); 1678 extras.putInt(Intent.EXTRA_UID, res.uid); 1679 1680 // Determine the set of users who are adding this package for 1681 // the first time vs. those who are seeing an update. 1682 int[] firstUsers = EMPTY_INT_ARRAY; 1683 int[] updateUsers = EMPTY_INT_ARRAY; 1684 if (res.origUsers == null || res.origUsers.length == 0) { 1685 firstUsers = res.newUsers; 1686 } else { 1687 for (int newUser : res.newUsers) { 1688 boolean isNew = true; 1689 for (int origUser : res.origUsers) { 1690 if (origUser == newUser) { 1691 isNew = false; 1692 break; 1693 } 1694 } 1695 if (isNew) { 1696 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1697 } else { 1698 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1699 } 1700 } 1701 } 1702 1703 // Send installed broadcasts if the install/update is not ephemeral 1704 if (!isEphemeral(res.pkg)) { 1705 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1706 1707 // Send added for users that see the package for the first time 1708 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1709 extras, 0 /*flags*/, null /*targetPackage*/, 1710 null /*finishedReceiver*/, firstUsers); 1711 1712 // Send added for users that don't see the package for the first time 1713 if (update) { 1714 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1715 } 1716 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1717 extras, 0 /*flags*/, null /*targetPackage*/, 1718 null /*finishedReceiver*/, updateUsers); 1719 1720 // Send replaced for users that don't see the package for the first time 1721 if (update) { 1722 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1723 packageName, extras, 0 /*flags*/, 1724 null /*targetPackage*/, null /*finishedReceiver*/, 1725 updateUsers); 1726 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1727 null /*package*/, null /*extras*/, 0 /*flags*/, 1728 packageName /*targetPackage*/, 1729 null /*finishedReceiver*/, updateUsers); 1730 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1731 // First-install and we did a restore, so we're responsible for the 1732 // first-launch broadcast. 1733 if (DEBUG_BACKUP) { 1734 Slog.i(TAG, "Post-restore of " + packageName 1735 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1736 } 1737 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1738 } 1739 1740 // Send broadcast package appeared if forward locked/external for all users 1741 // treat asec-hosted packages like removable media on upgrade 1742 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1743 if (DEBUG_INSTALL) { 1744 Slog.i(TAG, "upgrading pkg " + res.pkg 1745 + " is ASEC-hosted -> AVAILABLE"); 1746 } 1747 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1748 ArrayList<String> pkgList = new ArrayList<>(1); 1749 pkgList.add(packageName); 1750 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1751 } 1752 } 1753 1754 // Work that needs to happen on first install within each user 1755 if (firstUsers != null && firstUsers.length > 0) { 1756 synchronized (mPackages) { 1757 for (int userId : firstUsers) { 1758 // If this app is a browser and it's newly-installed for some 1759 // users, clear any default-browser state in those users. The 1760 // app's nature doesn't depend on the user, so we can just check 1761 // its browser nature in any user and generalize. 1762 if (packageIsBrowser(packageName, userId)) { 1763 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1764 } 1765 1766 // We may also need to apply pending (restored) runtime 1767 // permission grants within these users. 1768 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1769 } 1770 } 1771 } 1772 1773 // Log current value of "unknown sources" setting 1774 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1775 getUnknownSourcesSettings()); 1776 1777 // Force a gc to clear up things 1778 Runtime.getRuntime().gc(); 1779 1780 // Remove the replaced package's older resources safely now 1781 // We delete after a gc for applications on sdcard. 1782 if (res.removedInfo != null && res.removedInfo.args != null) { 1783 synchronized (mInstallLock) { 1784 res.removedInfo.args.doPostDeleteLI(true); 1785 } 1786 } 1787 1788 if (!isEphemeral(res.pkg)) { 1789 // Notify DexManager that the package was installed for new users. 1790 // The updated users should already be indexed and the package code paths 1791 // should not change. 1792 // Don't notify the manager for ephemeral apps as they are not expected to 1793 // survive long enough to benefit of background optimizations. 1794 for (int userId : firstUsers) { 1795 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1796 mDexManager.notifyPackageInstalled(info, userId); 1797 } 1798 } 1799 } 1800 1801 // If someone is watching installs - notify them 1802 if (installObserver != null) { 1803 try { 1804 Bundle extras = extrasForInstallResult(res); 1805 installObserver.onPackageInstalled(res.name, res.returnCode, 1806 res.returnMsg, extras); 1807 } catch (RemoteException e) { 1808 Slog.i(TAG, "Observer no longer exists."); 1809 } 1810 } 1811 } 1812 1813 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1814 PackageParser.Package pkg) { 1815 if (pkg.parentPackage == null) { 1816 return; 1817 } 1818 if (pkg.requestedPermissions == null) { 1819 return; 1820 } 1821 final PackageSetting disabledSysParentPs = mSettings 1822 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1823 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1824 || !disabledSysParentPs.isPrivileged() 1825 || (disabledSysParentPs.childPackageNames != null 1826 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1827 return; 1828 } 1829 final int[] allUserIds = sUserManager.getUserIds(); 1830 final int permCount = pkg.requestedPermissions.size(); 1831 for (int i = 0; i < permCount; i++) { 1832 String permission = pkg.requestedPermissions.get(i); 1833 BasePermission bp = mSettings.mPermissions.get(permission); 1834 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1835 continue; 1836 } 1837 for (int userId : allUserIds) { 1838 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1839 permission, userId)) { 1840 grantRuntimePermission(pkg.packageName, permission, userId); 1841 } 1842 } 1843 } 1844 } 1845 1846 private StorageEventListener mStorageListener = new StorageEventListener() { 1847 @Override 1848 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1849 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1850 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1851 final String volumeUuid = vol.getFsUuid(); 1852 1853 // Clean up any users or apps that were removed or recreated 1854 // while this volume was missing 1855 reconcileUsers(volumeUuid); 1856 reconcileApps(volumeUuid); 1857 1858 // Clean up any install sessions that expired or were 1859 // cancelled while this volume was missing 1860 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1861 1862 loadPrivatePackages(vol); 1863 1864 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1865 unloadPrivatePackages(vol); 1866 } 1867 } 1868 1869 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1870 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1871 updateExternalMediaStatus(true, false); 1872 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1873 updateExternalMediaStatus(false, false); 1874 } 1875 } 1876 } 1877 1878 @Override 1879 public void onVolumeForgotten(String fsUuid) { 1880 if (TextUtils.isEmpty(fsUuid)) { 1881 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1882 return; 1883 } 1884 1885 // Remove any apps installed on the forgotten volume 1886 synchronized (mPackages) { 1887 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1888 for (PackageSetting ps : packages) { 1889 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1890 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1891 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1892 } 1893 1894 mSettings.onVolumeForgotten(fsUuid); 1895 mSettings.writeLPr(); 1896 } 1897 } 1898 }; 1899 1900 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1901 String[] grantedPermissions) { 1902 for (int userId : userIds) { 1903 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1904 } 1905 1906 // We could have touched GID membership, so flush out packages.list 1907 synchronized (mPackages) { 1908 mSettings.writePackageListLPr(); 1909 } 1910 } 1911 1912 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1913 String[] grantedPermissions) { 1914 SettingBase sb = (SettingBase) pkg.mExtras; 1915 if (sb == null) { 1916 return; 1917 } 1918 1919 PermissionsState permissionsState = sb.getPermissionsState(); 1920 1921 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1922 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1923 1924 for (String permission : pkg.requestedPermissions) { 1925 final BasePermission bp; 1926 synchronized (mPackages) { 1927 bp = mSettings.mPermissions.get(permission); 1928 } 1929 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1930 && (grantedPermissions == null 1931 || ArrayUtils.contains(grantedPermissions, permission))) { 1932 final int flags = permissionsState.getPermissionFlags(permission, userId); 1933 // Installer cannot change immutable permissions. 1934 if ((flags & immutableFlags) == 0) { 1935 grantRuntimePermission(pkg.packageName, permission, userId); 1936 } 1937 } 1938 } 1939 } 1940 1941 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1942 Bundle extras = null; 1943 switch (res.returnCode) { 1944 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1945 extras = new Bundle(); 1946 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1947 res.origPermission); 1948 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1949 res.origPackage); 1950 break; 1951 } 1952 case PackageManager.INSTALL_SUCCEEDED: { 1953 extras = new Bundle(); 1954 extras.putBoolean(Intent.EXTRA_REPLACING, 1955 res.removedInfo != null && res.removedInfo.removedPackage != null); 1956 break; 1957 } 1958 } 1959 return extras; 1960 } 1961 1962 void scheduleWriteSettingsLocked() { 1963 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1964 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1965 } 1966 } 1967 1968 void scheduleWritePackageListLocked(int userId) { 1969 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 1970 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 1971 msg.arg1 = userId; 1972 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 1973 } 1974 } 1975 1976 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1977 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1978 scheduleWritePackageRestrictionsLocked(userId); 1979 } 1980 1981 void scheduleWritePackageRestrictionsLocked(int userId) { 1982 final int[] userIds = (userId == UserHandle.USER_ALL) 1983 ? sUserManager.getUserIds() : new int[]{userId}; 1984 for (int nextUserId : userIds) { 1985 if (!sUserManager.exists(nextUserId)) return; 1986 mDirtyUsers.add(nextUserId); 1987 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1988 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1989 } 1990 } 1991 } 1992 1993 public static PackageManagerService main(Context context, Installer installer, 1994 boolean factoryTest, boolean onlyCore) { 1995 // Self-check for initial settings. 1996 PackageManagerServiceCompilerMapping.checkProperties(); 1997 1998 PackageManagerService m = new PackageManagerService(context, installer, 1999 factoryTest, onlyCore); 2000 m.enableSystemUserPackages(); 2001 ServiceManager.addService("package", m); 2002 return m; 2003 } 2004 2005 private void enableSystemUserPackages() { 2006 if (!UserManager.isSplitSystemUser()) { 2007 return; 2008 } 2009 // For system user, enable apps based on the following conditions: 2010 // - app is whitelisted or belong to one of these groups: 2011 // -- system app which has no launcher icons 2012 // -- system app which has INTERACT_ACROSS_USERS permission 2013 // -- system IME app 2014 // - app is not in the blacklist 2015 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2016 Set<String> enableApps = new ArraySet<>(); 2017 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2018 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2019 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2020 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2021 enableApps.addAll(wlApps); 2022 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2023 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2024 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2025 enableApps.removeAll(blApps); 2026 Log.i(TAG, "Applications installed for system user: " + enableApps); 2027 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2028 UserHandle.SYSTEM); 2029 final int allAppsSize = allAps.size(); 2030 synchronized (mPackages) { 2031 for (int i = 0; i < allAppsSize; i++) { 2032 String pName = allAps.get(i); 2033 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2034 // Should not happen, but we shouldn't be failing if it does 2035 if (pkgSetting == null) { 2036 continue; 2037 } 2038 boolean install = enableApps.contains(pName); 2039 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2040 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2041 + " for system user"); 2042 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2043 } 2044 } 2045 } 2046 } 2047 2048 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2049 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2050 Context.DISPLAY_SERVICE); 2051 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2052 } 2053 2054 /** 2055 * Requests that files preopted on a secondary system partition be copied to the data partition 2056 * if possible. Note that the actual copying of the files is accomplished by init for security 2057 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2058 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2059 */ 2060 private static void requestCopyPreoptedFiles() { 2061 final int WAIT_TIME_MS = 100; 2062 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2063 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2064 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2065 // We will wait for up to 100 seconds. 2066 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2067 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2068 try { 2069 Thread.sleep(WAIT_TIME_MS); 2070 } catch (InterruptedException e) { 2071 // Do nothing 2072 } 2073 if (SystemClock.uptimeMillis() > timeEnd) { 2074 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2075 Slog.wtf(TAG, "cppreopt did not finish!"); 2076 break; 2077 } 2078 } 2079 } 2080 } 2081 2082 public PackageManagerService(Context context, Installer installer, 2083 boolean factoryTest, boolean onlyCore) { 2084 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2085 SystemClock.uptimeMillis()); 2086 2087 if (mSdkVersion <= 0) { 2088 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2089 } 2090 2091 mContext = context; 2092 2093 mPermissionReviewRequired = context.getResources().getBoolean( 2094 R.bool.config_permissionReviewRequired); 2095 2096 mFactoryTest = factoryTest; 2097 mOnlyCore = onlyCore; 2098 mMetrics = new DisplayMetrics(); 2099 mSettings = new Settings(mPackages); 2100 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2101 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2102 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2103 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2104 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2105 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2106 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2107 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2108 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2109 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2110 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2111 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2112 2113 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2114 if (separateProcesses != null && separateProcesses.length() > 0) { 2115 if ("*".equals(separateProcesses)) { 2116 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2117 mSeparateProcesses = null; 2118 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2119 } else { 2120 mDefParseFlags = 0; 2121 mSeparateProcesses = separateProcesses.split(","); 2122 Slog.w(TAG, "Running with debug.separate_processes: " 2123 + separateProcesses); 2124 } 2125 } else { 2126 mDefParseFlags = 0; 2127 mSeparateProcesses = null; 2128 } 2129 2130 mInstaller = installer; 2131 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2132 "*dexopt*"); 2133 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2134 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2135 2136 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2137 FgThread.get().getLooper()); 2138 2139 getDefaultDisplayMetrics(context, mMetrics); 2140 2141 SystemConfig systemConfig = SystemConfig.getInstance(); 2142 mGlobalGids = systemConfig.getGlobalGids(); 2143 mSystemPermissions = systemConfig.getSystemPermissions(); 2144 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2145 2146 mProtectedPackages = new ProtectedPackages(mContext); 2147 2148 synchronized (mInstallLock) { 2149 // writer 2150 synchronized (mPackages) { 2151 mHandlerThread = new ServiceThread(TAG, 2152 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2153 mHandlerThread.start(); 2154 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2155 mProcessLoggingHandler = new ProcessLoggingHandler(); 2156 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2157 2158 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2159 2160 File dataDir = Environment.getDataDirectory(); 2161 mAppInstallDir = new File(dataDir, "app"); 2162 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2163 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2164 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2165 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2166 2167 sUserManager = new UserManagerService(context, this, mPackages); 2168 2169 // Propagate permission configuration in to package manager. 2170 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2171 = systemConfig.getPermissions(); 2172 for (int i=0; i<permConfig.size(); i++) { 2173 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2174 BasePermission bp = mSettings.mPermissions.get(perm.name); 2175 if (bp == null) { 2176 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2177 mSettings.mPermissions.put(perm.name, bp); 2178 } 2179 if (perm.gids != null) { 2180 bp.setGids(perm.gids, perm.perUser); 2181 } 2182 } 2183 2184 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2185 for (int i=0; i<libConfig.size(); i++) { 2186 mSharedLibraries.put(libConfig.keyAt(i), 2187 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2188 } 2189 2190 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2191 2192 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2193 2194 if (mFirstBoot) { 2195 requestCopyPreoptedFiles(); 2196 } 2197 2198 String customResolverActivity = Resources.getSystem().getString( 2199 R.string.config_customResolverActivity); 2200 if (TextUtils.isEmpty(customResolverActivity)) { 2201 customResolverActivity = null; 2202 } else { 2203 mCustomResolverComponentName = ComponentName.unflattenFromString( 2204 customResolverActivity); 2205 } 2206 2207 long startTime = SystemClock.uptimeMillis(); 2208 2209 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2210 startTime); 2211 2212 // Set flag to monitor and not change apk file paths when 2213 // scanning install directories. 2214 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2215 2216 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2217 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2218 2219 if (bootClassPath == null) { 2220 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2221 } 2222 2223 if (systemServerClassPath == null) { 2224 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2225 } 2226 2227 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2228 final String[] dexCodeInstructionSets = 2229 getDexCodeInstructionSets( 2230 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2231 2232 /** 2233 * Ensure all external libraries have had dexopt run on them. 2234 */ 2235 if (mSharedLibraries.size() > 0) { 2236 // NOTE: For now, we're compiling these system "shared libraries" 2237 // (and framework jars) into all available architectures. It's possible 2238 // to compile them only when we come across an app that uses them (there's 2239 // already logic for that in scanPackageLI) but that adds some complexity. 2240 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2241 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2242 final String lib = libEntry.path; 2243 if (lib == null) { 2244 continue; 2245 } 2246 2247 try { 2248 // Shared libraries do not have profiles so we perform a full 2249 // AOT compilation (if needed). 2250 int dexoptNeeded = DexFile.getDexOptNeeded( 2251 lib, dexCodeInstructionSet, 2252 getCompilerFilterForReason(REASON_SHARED_APK), 2253 false /* newProfile */); 2254 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2255 mInstaller.dexopt(lib, Process.SYSTEM_UID, "*", 2256 dexCodeInstructionSet, dexoptNeeded, null, 2257 DEXOPT_PUBLIC, 2258 getCompilerFilterForReason(REASON_SHARED_APK), 2259 StorageManager.UUID_PRIVATE_INTERNAL, 2260 PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK); 2261 } 2262 } catch (FileNotFoundException e) { 2263 Slog.w(TAG, "Library not found: " + lib); 2264 } catch (IOException | InstallerException e) { 2265 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2266 + e.getMessage()); 2267 } 2268 } 2269 } 2270 } 2271 2272 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2273 2274 final VersionInfo ver = mSettings.getInternalVersion(); 2275 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2276 2277 // when upgrading from pre-M, promote system app permissions from install to runtime 2278 mPromoteSystemApps = 2279 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2280 2281 // When upgrading from pre-N, we need to handle package extraction like first boot, 2282 // as there is no profiling data available. 2283 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2284 2285 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2286 2287 // save off the names of pre-existing system packages prior to scanning; we don't 2288 // want to automatically grant runtime permissions for new system apps 2289 if (mPromoteSystemApps) { 2290 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2291 while (pkgSettingIter.hasNext()) { 2292 PackageSetting ps = pkgSettingIter.next(); 2293 if (isSystemApp(ps)) { 2294 mExistingSystemPackages.add(ps.name); 2295 } 2296 } 2297 } 2298 2299 // Collect vendor overlay packages. 2300 // (Do this before scanning any apps.) 2301 // For security and version matching reason, only consider 2302 // overlay packages if they reside in the right directory. 2303 File vendorOverlayDir; 2304 String overlaySkuDir = SystemProperties.get(VENDOR_OVERLAY_SKU_PROPERTY); 2305 if (!overlaySkuDir.isEmpty()) { 2306 vendorOverlayDir = new File(VENDOR_OVERLAY_DIR, overlaySkuDir); 2307 } else { 2308 vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2309 } 2310 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2311 | PackageParser.PARSE_IS_SYSTEM 2312 | PackageParser.PARSE_IS_SYSTEM_DIR 2313 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2314 2315 // Find base frameworks (resource packages without code). 2316 scanDirTracedLI(frameworkDir, mDefParseFlags 2317 | PackageParser.PARSE_IS_SYSTEM 2318 | PackageParser.PARSE_IS_SYSTEM_DIR 2319 | PackageParser.PARSE_IS_PRIVILEGED, 2320 scanFlags | SCAN_NO_DEX, 0); 2321 2322 // Collected privileged system packages. 2323 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2324 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2325 | PackageParser.PARSE_IS_SYSTEM 2326 | PackageParser.PARSE_IS_SYSTEM_DIR 2327 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2328 2329 // Collect ordinary system packages. 2330 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2331 scanDirTracedLI(systemAppDir, mDefParseFlags 2332 | PackageParser.PARSE_IS_SYSTEM 2333 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2334 2335 // Collect all vendor packages. 2336 File vendorAppDir = new File("/vendor/app"); 2337 try { 2338 vendorAppDir = vendorAppDir.getCanonicalFile(); 2339 } catch (IOException e) { 2340 // failed to look up canonical path, continue with original one 2341 } 2342 scanDirTracedLI(vendorAppDir, mDefParseFlags 2343 | PackageParser.PARSE_IS_SYSTEM 2344 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2345 2346 // Collect all OEM packages. 2347 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2348 scanDirTracedLI(oemAppDir, mDefParseFlags 2349 | PackageParser.PARSE_IS_SYSTEM 2350 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2351 2352 // Prune any system packages that no longer exist. 2353 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2354 if (!mOnlyCore) { 2355 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2356 while (psit.hasNext()) { 2357 PackageSetting ps = psit.next(); 2358 2359 /* 2360 * If this is not a system app, it can't be a 2361 * disable system app. 2362 */ 2363 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2364 continue; 2365 } 2366 2367 /* 2368 * If the package is scanned, it's not erased. 2369 */ 2370 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2371 if (scannedPkg != null) { 2372 /* 2373 * If the system app is both scanned and in the 2374 * disabled packages list, then it must have been 2375 * added via OTA. Remove it from the currently 2376 * scanned package so the previously user-installed 2377 * application can be scanned. 2378 */ 2379 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2380 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2381 + ps.name + "; removing system app. Last known codePath=" 2382 + ps.codePathString + ", installStatus=" + ps.installStatus 2383 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2384 + scannedPkg.mVersionCode); 2385 removePackageLI(scannedPkg, true); 2386 mExpectingBetter.put(ps.name, ps.codePath); 2387 } 2388 2389 continue; 2390 } 2391 2392 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2393 psit.remove(); 2394 logCriticalInfo(Log.WARN, "System package " + ps.name 2395 + " no longer exists; it's data will be wiped"); 2396 // Actual deletion of code and data will be handled by later 2397 // reconciliation step 2398 } else { 2399 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2400 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2401 possiblyDeletedUpdatedSystemApps.add(ps.name); 2402 } 2403 } 2404 } 2405 } 2406 2407 //look for any incomplete package installations 2408 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2409 for (int i = 0; i < deletePkgsList.size(); i++) { 2410 // Actual deletion of code and data will be handled by later 2411 // reconciliation step 2412 final String packageName = deletePkgsList.get(i).name; 2413 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2414 synchronized (mPackages) { 2415 mSettings.removePackageLPw(packageName); 2416 } 2417 } 2418 2419 //delete tmp files 2420 deleteTempPackageFiles(); 2421 2422 // Remove any shared userIDs that have no associated packages 2423 mSettings.pruneSharedUsersLPw(); 2424 2425 if (!mOnlyCore) { 2426 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2427 SystemClock.uptimeMillis()); 2428 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2429 2430 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2431 | PackageParser.PARSE_FORWARD_LOCK, 2432 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2433 2434 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2435 | PackageParser.PARSE_IS_EPHEMERAL, 2436 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2437 2438 /** 2439 * Remove disable package settings for any updated system 2440 * apps that were removed via an OTA. If they're not a 2441 * previously-updated app, remove them completely. 2442 * Otherwise, just revoke their system-level permissions. 2443 */ 2444 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2445 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2446 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2447 2448 String msg; 2449 if (deletedPkg == null) { 2450 msg = "Updated system package " + deletedAppName 2451 + " no longer exists; it's data will be wiped"; 2452 // Actual deletion of code and data will be handled by later 2453 // reconciliation step 2454 } else { 2455 msg = "Updated system app + " + deletedAppName 2456 + " no longer present; removing system privileges for " 2457 + deletedAppName; 2458 2459 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2460 2461 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2462 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2463 } 2464 logCriticalInfo(Log.WARN, msg); 2465 } 2466 2467 /** 2468 * Make sure all system apps that we expected to appear on 2469 * the userdata partition actually showed up. If they never 2470 * appeared, crawl back and revive the system version. 2471 */ 2472 for (int i = 0; i < mExpectingBetter.size(); i++) { 2473 final String packageName = mExpectingBetter.keyAt(i); 2474 if (!mPackages.containsKey(packageName)) { 2475 final File scanFile = mExpectingBetter.valueAt(i); 2476 2477 logCriticalInfo(Log.WARN, "Expected better " + packageName 2478 + " but never showed up; reverting to system"); 2479 2480 int reparseFlags = mDefParseFlags; 2481 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2482 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2483 | PackageParser.PARSE_IS_SYSTEM_DIR 2484 | PackageParser.PARSE_IS_PRIVILEGED; 2485 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2486 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2487 | PackageParser.PARSE_IS_SYSTEM_DIR; 2488 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2489 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2490 | PackageParser.PARSE_IS_SYSTEM_DIR; 2491 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2492 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2493 | PackageParser.PARSE_IS_SYSTEM_DIR; 2494 } else { 2495 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2496 continue; 2497 } 2498 2499 mSettings.enableSystemPackageLPw(packageName); 2500 2501 try { 2502 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2503 } catch (PackageManagerException e) { 2504 Slog.e(TAG, "Failed to parse original system package: " 2505 + e.getMessage()); 2506 } 2507 } 2508 } 2509 } 2510 mExpectingBetter.clear(); 2511 2512 // Resolve the storage manager. 2513 mStorageManagerPackage = getStorageManagerPackageName(); 2514 2515 // Resolve protected action filters. Only the setup wizard is allowed to 2516 // have a high priority filter for these actions. 2517 mSetupWizardPackage = getSetupWizardPackageName(); 2518 if (mProtectedFilters.size() > 0) { 2519 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2520 Slog.i(TAG, "No setup wizard;" 2521 + " All protected intents capped to priority 0"); 2522 } 2523 for (ActivityIntentInfo filter : mProtectedFilters) { 2524 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2525 if (DEBUG_FILTERS) { 2526 Slog.i(TAG, "Found setup wizard;" 2527 + " allow priority " + filter.getPriority() + ";" 2528 + " package: " + filter.activity.info.packageName 2529 + " activity: " + filter.activity.className 2530 + " priority: " + filter.getPriority()); 2531 } 2532 // skip setup wizard; allow it to keep the high priority filter 2533 continue; 2534 } 2535 Slog.w(TAG, "Protected action; cap priority to 0;" 2536 + " package: " + filter.activity.info.packageName 2537 + " activity: " + filter.activity.className 2538 + " origPrio: " + filter.getPriority()); 2539 filter.setPriority(0); 2540 } 2541 } 2542 mDeferProtectedFilters = false; 2543 mProtectedFilters.clear(); 2544 2545 // Now that we know all of the shared libraries, update all clients to have 2546 // the correct library paths. 2547 updateAllSharedLibrariesLPw(); 2548 2549 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2550 // NOTE: We ignore potential failures here during a system scan (like 2551 // the rest of the commands above) because there's precious little we 2552 // can do about it. A settings error is reported, though. 2553 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2554 false /* boot complete */); 2555 } 2556 2557 // Now that we know all the packages we are keeping, 2558 // read and update their last usage times. 2559 mPackageUsage.read(mPackages); 2560 mCompilerStats.read(); 2561 2562 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2563 SystemClock.uptimeMillis()); 2564 Slog.i(TAG, "Time to scan packages: " 2565 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2566 + " seconds"); 2567 2568 // If the platform SDK has changed since the last time we booted, 2569 // we need to re-grant app permission to catch any new ones that 2570 // appear. This is really a hack, and means that apps can in some 2571 // cases get permissions that the user didn't initially explicitly 2572 // allow... it would be nice to have some better way to handle 2573 // this situation. 2574 int updateFlags = UPDATE_PERMISSIONS_ALL; 2575 if (ver.sdkVersion != mSdkVersion) { 2576 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2577 + mSdkVersion + "; regranting permissions for internal storage"); 2578 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2579 } 2580 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2581 ver.sdkVersion = mSdkVersion; 2582 2583 // If this is the first boot or an update from pre-M, and it is a normal 2584 // boot, then we need to initialize the default preferred apps across 2585 // all defined users. 2586 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2587 for (UserInfo user : sUserManager.getUsers(true)) { 2588 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2589 applyFactoryDefaultBrowserLPw(user.id); 2590 primeDomainVerificationsLPw(user.id); 2591 } 2592 } 2593 2594 // Prepare storage for system user really early during boot, 2595 // since core system apps like SettingsProvider and SystemUI 2596 // can't wait for user to start 2597 final int storageFlags; 2598 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2599 storageFlags = StorageManager.FLAG_STORAGE_DE; 2600 } else { 2601 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2602 } 2603 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2604 storageFlags); 2605 2606 // If this is first boot after an OTA, and a normal boot, then 2607 // we need to clear code cache directories. 2608 // Note that we do *not* clear the application profiles. These remain valid 2609 // across OTAs and are used to drive profile verification (post OTA) and 2610 // profile compilation (without waiting to collect a fresh set of profiles). 2611 if (mIsUpgrade && !onlyCore) { 2612 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2613 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2614 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2615 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2616 // No apps are running this early, so no need to freeze 2617 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2618 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2619 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2620 } 2621 } 2622 ver.fingerprint = Build.FINGERPRINT; 2623 } 2624 2625 checkDefaultBrowser(); 2626 2627 // clear only after permissions and other defaults have been updated 2628 mExistingSystemPackages.clear(); 2629 mPromoteSystemApps = false; 2630 2631 // All the changes are done during package scanning. 2632 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2633 2634 // can downgrade to reader 2635 mSettings.writeLPr(); 2636 2637 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2638 // early on (before the package manager declares itself as early) because other 2639 // components in the system server might ask for package contexts for these apps. 2640 // 2641 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2642 // (i.e, that the data partition is unavailable). 2643 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2644 long start = System.nanoTime(); 2645 List<PackageParser.Package> coreApps = new ArrayList<>(); 2646 for (PackageParser.Package pkg : mPackages.values()) { 2647 if (pkg.coreApp) { 2648 coreApps.add(pkg); 2649 } 2650 } 2651 2652 int[] stats = performDexOptUpgrade(coreApps, false, 2653 getCompilerFilterForReason(REASON_CORE_APP)); 2654 2655 final int elapsedTimeSeconds = 2656 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2657 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2658 2659 if (DEBUG_DEXOPT) { 2660 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2661 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2662 } 2663 2664 2665 // TODO: Should we log these stats to tron too ? 2666 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2667 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2668 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2669 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2670 } 2671 2672 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2673 SystemClock.uptimeMillis()); 2674 2675 if (!mOnlyCore) { 2676 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2677 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2678 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2679 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2680 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2681 mIntentFilterVerifierComponent); 2682 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2683 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2684 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2685 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2686 } else { 2687 mRequiredVerifierPackage = null; 2688 mRequiredInstallerPackage = null; 2689 mRequiredUninstallerPackage = null; 2690 mIntentFilterVerifierComponent = null; 2691 mIntentFilterVerifier = null; 2692 mServicesSystemSharedLibraryPackageName = null; 2693 mSharedSystemSharedLibraryPackageName = null; 2694 } 2695 2696 mInstallerService = new PackageInstallerService(context, this); 2697 2698 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2699 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2700 // both the installer and resolver must be present to enable ephemeral 2701 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2702 if (DEBUG_EPHEMERAL) { 2703 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2704 + " installer:" + ephemeralInstallerComponent); 2705 } 2706 mEphemeralResolverComponent = ephemeralResolverComponent; 2707 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2708 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2709 mEphemeralResolverConnection = 2710 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2711 } else { 2712 if (DEBUG_EPHEMERAL) { 2713 final String missingComponent = 2714 (ephemeralResolverComponent == null) 2715 ? (ephemeralInstallerComponent == null) 2716 ? "resolver and installer" 2717 : "resolver" 2718 : "installer"; 2719 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2720 } 2721 mEphemeralResolverComponent = null; 2722 mEphemeralInstallerComponent = null; 2723 mEphemeralResolverConnection = null; 2724 } 2725 2726 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2727 2728 // Read and update the usage of dex files. 2729 // Do this at the end of PM init so that all the packages have their 2730 // data directory reconciled. 2731 // At this point we know the code paths of the packages, so we can validate 2732 // the disk file and build the internal cache. 2733 // The usage file is expected to be small so loading and verifying it 2734 // should take a fairly small time compare to the other activities (e.g. package 2735 // scanning). 2736 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2737 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2738 for (int userId : currentUserIds) { 2739 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2740 } 2741 mDexManager.load(userPackages); 2742 } // synchronized (mPackages) 2743 } // synchronized (mInstallLock) 2744 2745 // Now after opening every single application zip, make sure they 2746 // are all flushed. Not really needed, but keeps things nice and 2747 // tidy. 2748 Runtime.getRuntime().gc(); 2749 2750 // The initial scanning above does many calls into installd while 2751 // holding the mPackages lock, but we're mostly interested in yelling 2752 // once we have a booted system. 2753 mInstaller.setWarnIfHeld(mPackages); 2754 2755 // Expose private service for system components to use. 2756 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2757 } 2758 2759 @Override 2760 public boolean isFirstBoot() { 2761 return mFirstBoot; 2762 } 2763 2764 @Override 2765 public boolean isOnlyCoreApps() { 2766 return mOnlyCore; 2767 } 2768 2769 @Override 2770 public boolean isUpgrade() { 2771 return mIsUpgrade; 2772 } 2773 2774 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2775 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2776 2777 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2778 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2779 UserHandle.USER_SYSTEM); 2780 if (matches.size() == 1) { 2781 return matches.get(0).getComponentInfo().packageName; 2782 } else if (matches.size() == 0) { 2783 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2784 return null; 2785 } 2786 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2787 } 2788 2789 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2790 synchronized (mPackages) { 2791 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2792 if (libraryEntry == null) { 2793 throw new IllegalStateException("Missing required shared library:" + libraryName); 2794 } 2795 return libraryEntry.apk; 2796 } 2797 } 2798 2799 private @NonNull String getRequiredInstallerLPr() { 2800 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2801 intent.addCategory(Intent.CATEGORY_DEFAULT); 2802 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2803 2804 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2805 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2806 UserHandle.USER_SYSTEM); 2807 if (matches.size() == 1) { 2808 ResolveInfo resolveInfo = matches.get(0); 2809 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2810 throw new RuntimeException("The installer must be a privileged app"); 2811 } 2812 return matches.get(0).getComponentInfo().packageName; 2813 } else { 2814 throw new RuntimeException("There must be exactly one installer; found " + matches); 2815 } 2816 } 2817 2818 private @NonNull String getRequiredUninstallerLPr() { 2819 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2820 intent.addCategory(Intent.CATEGORY_DEFAULT); 2821 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2822 2823 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2824 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2825 UserHandle.USER_SYSTEM); 2826 if (resolveInfo == null || 2827 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2828 throw new RuntimeException("There must be exactly one uninstaller; found " 2829 + resolveInfo); 2830 } 2831 return resolveInfo.getComponentInfo().packageName; 2832 } 2833 2834 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2835 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2836 2837 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2838 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2839 UserHandle.USER_SYSTEM); 2840 ResolveInfo best = null; 2841 final int N = matches.size(); 2842 for (int i = 0; i < N; i++) { 2843 final ResolveInfo cur = matches.get(i); 2844 final String packageName = cur.getComponentInfo().packageName; 2845 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2846 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2847 continue; 2848 } 2849 2850 if (best == null || cur.priority > best.priority) { 2851 best = cur; 2852 } 2853 } 2854 2855 if (best != null) { 2856 return best.getComponentInfo().getComponentName(); 2857 } else { 2858 throw new RuntimeException("There must be at least one intent filter verifier"); 2859 } 2860 } 2861 2862 private @Nullable ComponentName getEphemeralResolverLPr() { 2863 final String[] packageArray = 2864 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2865 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2866 if (DEBUG_EPHEMERAL) { 2867 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2868 } 2869 return null; 2870 } 2871 2872 final int resolveFlags = 2873 MATCH_DIRECT_BOOT_AWARE 2874 | MATCH_DIRECT_BOOT_UNAWARE 2875 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2876 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2877 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2878 resolveFlags, UserHandle.USER_SYSTEM); 2879 2880 final int N = resolvers.size(); 2881 if (N == 0) { 2882 if (DEBUG_EPHEMERAL) { 2883 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2884 } 2885 return null; 2886 } 2887 2888 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2889 for (int i = 0; i < N; i++) { 2890 final ResolveInfo info = resolvers.get(i); 2891 2892 if (info.serviceInfo == null) { 2893 continue; 2894 } 2895 2896 final String packageName = info.serviceInfo.packageName; 2897 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2898 if (DEBUG_EPHEMERAL) { 2899 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2900 + " pkg: " + packageName + ", info:" + info); 2901 } 2902 continue; 2903 } 2904 2905 if (DEBUG_EPHEMERAL) { 2906 Slog.v(TAG, "Ephemeral resolver found;" 2907 + " pkg: " + packageName + ", info:" + info); 2908 } 2909 return new ComponentName(packageName, info.serviceInfo.name); 2910 } 2911 if (DEBUG_EPHEMERAL) { 2912 Slog.v(TAG, "Ephemeral resolver NOT found"); 2913 } 2914 return null; 2915 } 2916 2917 private @Nullable ComponentName getEphemeralInstallerLPr() { 2918 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2919 intent.addCategory(Intent.CATEGORY_DEFAULT); 2920 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2921 2922 final int resolveFlags = 2923 MATCH_DIRECT_BOOT_AWARE 2924 | MATCH_DIRECT_BOOT_UNAWARE 2925 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2926 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2927 resolveFlags, UserHandle.USER_SYSTEM); 2928 if (matches.size() == 0) { 2929 return null; 2930 } else if (matches.size() == 1) { 2931 return matches.get(0).getComponentInfo().getComponentName(); 2932 } else { 2933 throw new RuntimeException( 2934 "There must be at most one ephemeral installer; found " + matches); 2935 } 2936 } 2937 2938 private void primeDomainVerificationsLPw(int userId) { 2939 if (DEBUG_DOMAIN_VERIFICATION) { 2940 Slog.d(TAG, "Priming domain verifications in user " + userId); 2941 } 2942 2943 SystemConfig systemConfig = SystemConfig.getInstance(); 2944 ArraySet<String> packages = systemConfig.getLinkedApps(); 2945 ArraySet<String> domains = new ArraySet<String>(); 2946 2947 for (String packageName : packages) { 2948 PackageParser.Package pkg = mPackages.get(packageName); 2949 if (pkg != null) { 2950 if (!pkg.isSystemApp()) { 2951 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2952 continue; 2953 } 2954 2955 domains.clear(); 2956 for (PackageParser.Activity a : pkg.activities) { 2957 for (ActivityIntentInfo filter : a.intents) { 2958 if (hasValidDomains(filter)) { 2959 domains.addAll(filter.getHostsList()); 2960 } 2961 } 2962 } 2963 2964 if (domains.size() > 0) { 2965 if (DEBUG_DOMAIN_VERIFICATION) { 2966 Slog.v(TAG, " + " + packageName); 2967 } 2968 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2969 // state w.r.t. the formal app-linkage "no verification attempted" state; 2970 // and then 'always' in the per-user state actually used for intent resolution. 2971 final IntentFilterVerificationInfo ivi; 2972 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2973 new ArrayList<String>(domains)); 2974 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2975 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2976 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2977 } else { 2978 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2979 + "' does not handle web links"); 2980 } 2981 } else { 2982 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2983 } 2984 } 2985 2986 scheduleWritePackageRestrictionsLocked(userId); 2987 scheduleWriteSettingsLocked(); 2988 } 2989 2990 private void applyFactoryDefaultBrowserLPw(int userId) { 2991 // The default browser app's package name is stored in a string resource, 2992 // with a product-specific overlay used for vendor customization. 2993 String browserPkg = mContext.getResources().getString( 2994 com.android.internal.R.string.default_browser); 2995 if (!TextUtils.isEmpty(browserPkg)) { 2996 // non-empty string => required to be a known package 2997 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2998 if (ps == null) { 2999 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3000 browserPkg = null; 3001 } else { 3002 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3003 } 3004 } 3005 3006 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3007 // default. If there's more than one, just leave everything alone. 3008 if (browserPkg == null) { 3009 calculateDefaultBrowserLPw(userId); 3010 } 3011 } 3012 3013 private void calculateDefaultBrowserLPw(int userId) { 3014 List<String> allBrowsers = resolveAllBrowserApps(userId); 3015 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3016 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3017 } 3018 3019 private List<String> resolveAllBrowserApps(int userId) { 3020 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3021 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3022 PackageManager.MATCH_ALL, userId); 3023 3024 final int count = list.size(); 3025 List<String> result = new ArrayList<String>(count); 3026 for (int i=0; i<count; i++) { 3027 ResolveInfo info = list.get(i); 3028 if (info.activityInfo == null 3029 || !info.handleAllWebDataURI 3030 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3031 || result.contains(info.activityInfo.packageName)) { 3032 continue; 3033 } 3034 result.add(info.activityInfo.packageName); 3035 } 3036 3037 return result; 3038 } 3039 3040 private boolean packageIsBrowser(String packageName, int userId) { 3041 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3042 PackageManager.MATCH_ALL, userId); 3043 final int N = list.size(); 3044 for (int i = 0; i < N; i++) { 3045 ResolveInfo info = list.get(i); 3046 if (packageName.equals(info.activityInfo.packageName)) { 3047 return true; 3048 } 3049 } 3050 return false; 3051 } 3052 3053 private void checkDefaultBrowser() { 3054 final int myUserId = UserHandle.myUserId(); 3055 final String packageName = getDefaultBrowserPackageName(myUserId); 3056 if (packageName != null) { 3057 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3058 if (info == null) { 3059 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3060 synchronized (mPackages) { 3061 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3062 } 3063 } 3064 } 3065 } 3066 3067 @Override 3068 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3069 throws RemoteException { 3070 try { 3071 return super.onTransact(code, data, reply, flags); 3072 } catch (RuntimeException e) { 3073 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3074 Slog.wtf(TAG, "Package Manager Crash", e); 3075 } 3076 throw e; 3077 } 3078 } 3079 3080 static int[] appendInts(int[] cur, int[] add) { 3081 if (add == null) return cur; 3082 if (cur == null) return add; 3083 final int N = add.length; 3084 for (int i=0; i<N; i++) { 3085 cur = appendInt(cur, add[i]); 3086 } 3087 return cur; 3088 } 3089 3090 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3091 if (!sUserManager.exists(userId)) return null; 3092 if (ps == null) { 3093 return null; 3094 } 3095 final PackageParser.Package p = ps.pkg; 3096 if (p == null) { 3097 return null; 3098 } 3099 3100 final PermissionsState permissionsState = ps.getPermissionsState(); 3101 3102 // Compute GIDs only if requested 3103 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3104 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3105 // Compute granted permissions only if package has requested permissions 3106 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3107 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3108 final PackageUserState state = ps.readUserState(userId); 3109 3110 return PackageParser.generatePackageInfo(p, gids, flags, 3111 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3112 } 3113 3114 @Override 3115 public void checkPackageStartable(String packageName, int userId) { 3116 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3117 3118 synchronized (mPackages) { 3119 final PackageSetting ps = mSettings.mPackages.get(packageName); 3120 if (ps == null) { 3121 throw new SecurityException("Package " + packageName + " was not found!"); 3122 } 3123 3124 if (!ps.getInstalled(userId)) { 3125 throw new SecurityException( 3126 "Package " + packageName + " was not installed for user " + userId + "!"); 3127 } 3128 3129 if (mSafeMode && !ps.isSystem()) { 3130 throw new SecurityException("Package " + packageName + " not a system app!"); 3131 } 3132 3133 if (mFrozenPackages.contains(packageName)) { 3134 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3135 } 3136 3137 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3138 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3139 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3140 } 3141 } 3142 } 3143 3144 @Override 3145 public boolean isPackageAvailable(String packageName, int userId) { 3146 if (!sUserManager.exists(userId)) return false; 3147 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3148 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3149 synchronized (mPackages) { 3150 PackageParser.Package p = mPackages.get(packageName); 3151 if (p != null) { 3152 final PackageSetting ps = (PackageSetting) p.mExtras; 3153 if (ps != null) { 3154 final PackageUserState state = ps.readUserState(userId); 3155 if (state != null) { 3156 return PackageParser.isAvailable(state); 3157 } 3158 } 3159 } 3160 } 3161 return false; 3162 } 3163 3164 @Override 3165 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3166 if (!sUserManager.exists(userId)) return null; 3167 flags = updateFlagsForPackage(flags, userId, packageName); 3168 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3169 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3170 // reader 3171 synchronized (mPackages) { 3172 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3173 PackageParser.Package p = null; 3174 if (matchFactoryOnly) { 3175 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3176 if (ps != null) { 3177 return generatePackageInfo(ps, flags, userId); 3178 } 3179 } 3180 if (p == null) { 3181 p = mPackages.get(packageName); 3182 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3183 return null; 3184 } 3185 } 3186 if (DEBUG_PACKAGE_INFO) 3187 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3188 if (p != null) { 3189 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3190 } 3191 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3192 final PackageSetting ps = mSettings.mPackages.get(packageName); 3193 return generatePackageInfo(ps, flags, userId); 3194 } 3195 } 3196 return null; 3197 } 3198 3199 @Override 3200 public String[] currentToCanonicalPackageNames(String[] names) { 3201 String[] out = new String[names.length]; 3202 // reader 3203 synchronized (mPackages) { 3204 for (int i=names.length-1; i>=0; i--) { 3205 PackageSetting ps = mSettings.mPackages.get(names[i]); 3206 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3207 } 3208 } 3209 return out; 3210 } 3211 3212 @Override 3213 public String[] canonicalToCurrentPackageNames(String[] names) { 3214 String[] out = new String[names.length]; 3215 // reader 3216 synchronized (mPackages) { 3217 for (int i=names.length-1; i>=0; i--) { 3218 String cur = mSettings.mRenamedPackages.get(names[i]); 3219 out[i] = cur != null ? cur : names[i]; 3220 } 3221 } 3222 return out; 3223 } 3224 3225 @Override 3226 public int getPackageUid(String packageName, int flags, int userId) { 3227 if (!sUserManager.exists(userId)) return -1; 3228 flags = updateFlagsForPackage(flags, userId, packageName); 3229 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3230 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3231 3232 // reader 3233 synchronized (mPackages) { 3234 final PackageParser.Package p = mPackages.get(packageName); 3235 if (p != null && p.isMatch(flags)) { 3236 return UserHandle.getUid(userId, p.applicationInfo.uid); 3237 } 3238 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3239 final PackageSetting ps = mSettings.mPackages.get(packageName); 3240 if (ps != null && ps.isMatch(flags)) { 3241 return UserHandle.getUid(userId, ps.appId); 3242 } 3243 } 3244 } 3245 3246 return -1; 3247 } 3248 3249 @Override 3250 public int[] getPackageGids(String packageName, int flags, int userId) { 3251 if (!sUserManager.exists(userId)) return null; 3252 flags = updateFlagsForPackage(flags, userId, packageName); 3253 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3254 false /* requireFullPermission */, false /* checkShell */, 3255 "getPackageGids"); 3256 3257 // reader 3258 synchronized (mPackages) { 3259 final PackageParser.Package p = mPackages.get(packageName); 3260 if (p != null && p.isMatch(flags)) { 3261 PackageSetting ps = (PackageSetting) p.mExtras; 3262 return ps.getPermissionsState().computeGids(userId); 3263 } 3264 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3265 final PackageSetting ps = mSettings.mPackages.get(packageName); 3266 if (ps != null && ps.isMatch(flags)) { 3267 return ps.getPermissionsState().computeGids(userId); 3268 } 3269 } 3270 } 3271 3272 return null; 3273 } 3274 3275 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3276 if (bp.perm != null) { 3277 return PackageParser.generatePermissionInfo(bp.perm, flags); 3278 } 3279 PermissionInfo pi = new PermissionInfo(); 3280 pi.name = bp.name; 3281 pi.packageName = bp.sourcePackage; 3282 pi.nonLocalizedLabel = bp.name; 3283 pi.protectionLevel = bp.protectionLevel; 3284 return pi; 3285 } 3286 3287 @Override 3288 public PermissionInfo getPermissionInfo(String name, int flags) { 3289 // reader 3290 synchronized (mPackages) { 3291 final BasePermission p = mSettings.mPermissions.get(name); 3292 if (p != null) { 3293 return generatePermissionInfo(p, flags); 3294 } 3295 return null; 3296 } 3297 } 3298 3299 @Override 3300 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3301 int flags) { 3302 // reader 3303 synchronized (mPackages) { 3304 if (group != null && !mPermissionGroups.containsKey(group)) { 3305 // This is thrown as NameNotFoundException 3306 return null; 3307 } 3308 3309 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3310 for (BasePermission p : mSettings.mPermissions.values()) { 3311 if (group == null) { 3312 if (p.perm == null || p.perm.info.group == null) { 3313 out.add(generatePermissionInfo(p, flags)); 3314 } 3315 } else { 3316 if (p.perm != null && group.equals(p.perm.info.group)) { 3317 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3318 } 3319 } 3320 } 3321 return new ParceledListSlice<>(out); 3322 } 3323 } 3324 3325 @Override 3326 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3327 // reader 3328 synchronized (mPackages) { 3329 return PackageParser.generatePermissionGroupInfo( 3330 mPermissionGroups.get(name), flags); 3331 } 3332 } 3333 3334 @Override 3335 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3336 // reader 3337 synchronized (mPackages) { 3338 final int N = mPermissionGroups.size(); 3339 ArrayList<PermissionGroupInfo> out 3340 = new ArrayList<PermissionGroupInfo>(N); 3341 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3342 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3343 } 3344 return new ParceledListSlice<>(out); 3345 } 3346 } 3347 3348 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3349 int userId) { 3350 if (!sUserManager.exists(userId)) return null; 3351 PackageSetting ps = mSettings.mPackages.get(packageName); 3352 if (ps != null) { 3353 if (ps.pkg == null) { 3354 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3355 if (pInfo != null) { 3356 return pInfo.applicationInfo; 3357 } 3358 return null; 3359 } 3360 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3361 ps.readUserState(userId), userId); 3362 } 3363 return null; 3364 } 3365 3366 @Override 3367 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3368 if (!sUserManager.exists(userId)) return null; 3369 flags = updateFlagsForApplication(flags, userId, packageName); 3370 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3371 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3372 // writer 3373 synchronized (mPackages) { 3374 PackageParser.Package p = mPackages.get(packageName); 3375 if (DEBUG_PACKAGE_INFO) Log.v( 3376 TAG, "getApplicationInfo " + packageName 3377 + ": " + p); 3378 if (p != null) { 3379 PackageSetting ps = mSettings.mPackages.get(packageName); 3380 if (ps == null) return null; 3381 // Note: isEnabledLP() does not apply here - always return info 3382 return PackageParser.generateApplicationInfo( 3383 p, flags, ps.readUserState(userId), userId); 3384 } 3385 if ("android".equals(packageName)||"system".equals(packageName)) { 3386 return mAndroidApplication; 3387 } 3388 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3389 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3390 } 3391 } 3392 return null; 3393 } 3394 3395 @Override 3396 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3397 final IPackageDataObserver observer) { 3398 mContext.enforceCallingOrSelfPermission( 3399 android.Manifest.permission.CLEAR_APP_CACHE, null); 3400 // Queue up an async operation since clearing cache may take a little while. 3401 mHandler.post(new Runnable() { 3402 public void run() { 3403 mHandler.removeCallbacks(this); 3404 boolean success = true; 3405 synchronized (mInstallLock) { 3406 try { 3407 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3408 } catch (InstallerException e) { 3409 Slog.w(TAG, "Couldn't clear application caches: " + e); 3410 success = false; 3411 } 3412 } 3413 if (observer != null) { 3414 try { 3415 observer.onRemoveCompleted(null, success); 3416 } catch (RemoteException e) { 3417 Slog.w(TAG, "RemoveException when invoking call back"); 3418 } 3419 } 3420 } 3421 }); 3422 } 3423 3424 @Override 3425 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3426 final IntentSender pi) { 3427 mContext.enforceCallingOrSelfPermission( 3428 android.Manifest.permission.CLEAR_APP_CACHE, null); 3429 // Queue up an async operation since clearing cache may take a little while. 3430 mHandler.post(new Runnable() { 3431 public void run() { 3432 mHandler.removeCallbacks(this); 3433 boolean success = true; 3434 synchronized (mInstallLock) { 3435 try { 3436 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3437 } catch (InstallerException e) { 3438 Slog.w(TAG, "Couldn't clear application caches: " + e); 3439 success = false; 3440 } 3441 } 3442 if(pi != null) { 3443 try { 3444 // Callback via pending intent 3445 int code = success ? 1 : 0; 3446 pi.sendIntent(null, code, null, 3447 null, null); 3448 } catch (SendIntentException e1) { 3449 Slog.i(TAG, "Failed to send pending intent"); 3450 } 3451 } 3452 } 3453 }); 3454 } 3455 3456 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3457 synchronized (mInstallLock) { 3458 try { 3459 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3460 } catch (InstallerException e) { 3461 throw new IOException("Failed to free enough space", e); 3462 } 3463 } 3464 } 3465 3466 /** 3467 * Update given flags based on encryption status of current user. 3468 */ 3469 private int updateFlags(int flags, int userId) { 3470 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3471 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3472 // Caller expressed an explicit opinion about what encryption 3473 // aware/unaware components they want to see, so fall through and 3474 // give them what they want 3475 } else { 3476 // Caller expressed no opinion, so match based on user state 3477 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3478 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3479 } else { 3480 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3481 } 3482 } 3483 return flags; 3484 } 3485 3486 private UserManagerInternal getUserManagerInternal() { 3487 if (mUserManagerInternal == null) { 3488 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3489 } 3490 return mUserManagerInternal; 3491 } 3492 3493 /** 3494 * Update given flags when being used to request {@link PackageInfo}. 3495 */ 3496 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3497 boolean triaged = true; 3498 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3499 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3500 // Caller is asking for component details, so they'd better be 3501 // asking for specific encryption matching behavior, or be triaged 3502 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3503 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3504 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3505 triaged = false; 3506 } 3507 } 3508 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3509 | PackageManager.MATCH_SYSTEM_ONLY 3510 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3511 triaged = false; 3512 } 3513 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3514 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3515 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3516 } 3517 return updateFlags(flags, userId); 3518 } 3519 3520 /** 3521 * Update given flags when being used to request {@link ApplicationInfo}. 3522 */ 3523 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3524 return updateFlagsForPackage(flags, userId, cookie); 3525 } 3526 3527 /** 3528 * Update given flags when being used to request {@link ComponentInfo}. 3529 */ 3530 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3531 if (cookie instanceof Intent) { 3532 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3533 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3534 } 3535 } 3536 3537 boolean triaged = true; 3538 // Caller is asking for component details, so they'd better be 3539 // asking for specific encryption matching behavior, or be triaged 3540 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3541 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3542 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3543 triaged = false; 3544 } 3545 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3546 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3547 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3548 } 3549 3550 return updateFlags(flags, userId); 3551 } 3552 3553 /** 3554 * Update given flags when being used to request {@link ResolveInfo}. 3555 */ 3556 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3557 // Safe mode means we shouldn't match any third-party components 3558 if (mSafeMode) { 3559 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3560 } 3561 3562 return updateFlagsForComponent(flags, userId, cookie); 3563 } 3564 3565 @Override 3566 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3567 if (!sUserManager.exists(userId)) return null; 3568 flags = updateFlagsForComponent(flags, userId, component); 3569 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3570 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3571 synchronized (mPackages) { 3572 PackageParser.Activity a = mActivities.mActivities.get(component); 3573 3574 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3575 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3576 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3577 if (ps == null) return null; 3578 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3579 userId); 3580 } 3581 if (mResolveComponentName.equals(component)) { 3582 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3583 new PackageUserState(), userId); 3584 } 3585 } 3586 return null; 3587 } 3588 3589 @Override 3590 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3591 String resolvedType) { 3592 synchronized (mPackages) { 3593 if (component.equals(mResolveComponentName)) { 3594 // The resolver supports EVERYTHING! 3595 return true; 3596 } 3597 PackageParser.Activity a = mActivities.mActivities.get(component); 3598 if (a == null) { 3599 return false; 3600 } 3601 for (int i=0; i<a.intents.size(); i++) { 3602 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3603 intent.getData(), intent.getCategories(), TAG) >= 0) { 3604 return true; 3605 } 3606 } 3607 return false; 3608 } 3609 } 3610 3611 @Override 3612 public ActivityInfo getReceiverInfo(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 receiver info"); 3617 synchronized (mPackages) { 3618 PackageParser.Activity a = mReceivers.mActivities.get(component); 3619 if (DEBUG_PACKAGE_INFO) Log.v( 3620 TAG, "getReceiverInfo " + component + ": " + a); 3621 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3622 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3623 if (ps == null) return null; 3624 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3625 userId); 3626 } 3627 } 3628 return null; 3629 } 3630 3631 @Override 3632 public ServiceInfo getServiceInfo(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 service info"); 3637 synchronized (mPackages) { 3638 PackageParser.Service s = mServices.mServices.get(component); 3639 if (DEBUG_PACKAGE_INFO) Log.v( 3640 TAG, "getServiceInfo " + component + ": " + s); 3641 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3642 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3643 if (ps == null) return null; 3644 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3645 userId); 3646 } 3647 } 3648 return null; 3649 } 3650 3651 @Override 3652 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3653 if (!sUserManager.exists(userId)) return null; 3654 flags = updateFlagsForComponent(flags, userId, component); 3655 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3656 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3657 synchronized (mPackages) { 3658 PackageParser.Provider p = mProviders.mProviders.get(component); 3659 if (DEBUG_PACKAGE_INFO) Log.v( 3660 TAG, "getProviderInfo " + component + ": " + p); 3661 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3662 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3663 if (ps == null) return null; 3664 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3665 userId); 3666 } 3667 } 3668 return null; 3669 } 3670 3671 @Override 3672 public String[] getSystemSharedLibraryNames() { 3673 Set<String> libSet; 3674 synchronized (mPackages) { 3675 libSet = mSharedLibraries.keySet(); 3676 int size = libSet.size(); 3677 if (size > 0) { 3678 String[] libs = new String[size]; 3679 libSet.toArray(libs); 3680 return libs; 3681 } 3682 } 3683 return null; 3684 } 3685 3686 @Override 3687 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3688 synchronized (mPackages) { 3689 return mServicesSystemSharedLibraryPackageName; 3690 } 3691 } 3692 3693 @Override 3694 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3695 synchronized (mPackages) { 3696 return mSharedSystemSharedLibraryPackageName; 3697 } 3698 } 3699 3700 @Override 3701 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3702 synchronized (mPackages) { 3703 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3704 3705 final FeatureInfo fi = new FeatureInfo(); 3706 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3707 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3708 res.add(fi); 3709 3710 return new ParceledListSlice<>(res); 3711 } 3712 } 3713 3714 @Override 3715 public boolean hasSystemFeature(String name, int version) { 3716 synchronized (mPackages) { 3717 final FeatureInfo feat = mAvailableFeatures.get(name); 3718 if (feat == null) { 3719 return false; 3720 } else { 3721 return feat.version >= version; 3722 } 3723 } 3724 } 3725 3726 @Override 3727 public int checkPermission(String permName, String pkgName, int userId) { 3728 if (!sUserManager.exists(userId)) { 3729 return PackageManager.PERMISSION_DENIED; 3730 } 3731 3732 synchronized (mPackages) { 3733 final PackageParser.Package p = mPackages.get(pkgName); 3734 if (p != null && p.mExtras != null) { 3735 final PackageSetting ps = (PackageSetting) p.mExtras; 3736 final PermissionsState permissionsState = ps.getPermissionsState(); 3737 if (permissionsState.hasPermission(permName, userId)) { 3738 return PackageManager.PERMISSION_GRANTED; 3739 } 3740 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3741 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3742 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3743 return PackageManager.PERMISSION_GRANTED; 3744 } 3745 } 3746 } 3747 3748 return PackageManager.PERMISSION_DENIED; 3749 } 3750 3751 @Override 3752 public int checkUidPermission(String permName, int uid) { 3753 final int userId = UserHandle.getUserId(uid); 3754 3755 if (!sUserManager.exists(userId)) { 3756 return PackageManager.PERMISSION_DENIED; 3757 } 3758 3759 synchronized (mPackages) { 3760 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3761 if (obj != null) { 3762 final SettingBase ps = (SettingBase) obj; 3763 final PermissionsState permissionsState = ps.getPermissionsState(); 3764 if (permissionsState.hasPermission(permName, userId)) { 3765 return PackageManager.PERMISSION_GRANTED; 3766 } 3767 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3768 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3769 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3770 return PackageManager.PERMISSION_GRANTED; 3771 } 3772 } else { 3773 ArraySet<String> perms = mSystemPermissions.get(uid); 3774 if (perms != null) { 3775 if (perms.contains(permName)) { 3776 return PackageManager.PERMISSION_GRANTED; 3777 } 3778 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3779 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3780 return PackageManager.PERMISSION_GRANTED; 3781 } 3782 } 3783 } 3784 } 3785 3786 return PackageManager.PERMISSION_DENIED; 3787 } 3788 3789 @Override 3790 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3791 if (UserHandle.getCallingUserId() != userId) { 3792 mContext.enforceCallingPermission( 3793 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3794 "isPermissionRevokedByPolicy for user " + userId); 3795 } 3796 3797 if (checkPermission(permission, packageName, userId) 3798 == PackageManager.PERMISSION_GRANTED) { 3799 return false; 3800 } 3801 3802 final long identity = Binder.clearCallingIdentity(); 3803 try { 3804 final int flags = getPermissionFlags(permission, packageName, userId); 3805 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3806 } finally { 3807 Binder.restoreCallingIdentity(identity); 3808 } 3809 } 3810 3811 @Override 3812 public String getPermissionControllerPackageName() { 3813 synchronized (mPackages) { 3814 return mRequiredInstallerPackage; 3815 } 3816 } 3817 3818 /** 3819 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3820 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3821 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3822 * @param message the message to log on security exception 3823 */ 3824 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3825 boolean checkShell, String message) { 3826 if (userId < 0) { 3827 throw new IllegalArgumentException("Invalid userId " + userId); 3828 } 3829 if (checkShell) { 3830 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3831 } 3832 if (userId == UserHandle.getUserId(callingUid)) return; 3833 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3834 if (requireFullPermission) { 3835 mContext.enforceCallingOrSelfPermission( 3836 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3837 } else { 3838 try { 3839 mContext.enforceCallingOrSelfPermission( 3840 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3841 } catch (SecurityException se) { 3842 mContext.enforceCallingOrSelfPermission( 3843 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3844 } 3845 } 3846 } 3847 } 3848 3849 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3850 if (callingUid == Process.SHELL_UID) { 3851 if (userHandle >= 0 3852 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3853 throw new SecurityException("Shell does not have permission to access user " 3854 + userHandle); 3855 } else if (userHandle < 0) { 3856 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3857 + Debug.getCallers(3)); 3858 } 3859 } 3860 } 3861 3862 private BasePermission findPermissionTreeLP(String permName) { 3863 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3864 if (permName.startsWith(bp.name) && 3865 permName.length() > bp.name.length() && 3866 permName.charAt(bp.name.length()) == '.') { 3867 return bp; 3868 } 3869 } 3870 return null; 3871 } 3872 3873 private BasePermission checkPermissionTreeLP(String permName) { 3874 if (permName != null) { 3875 BasePermission bp = findPermissionTreeLP(permName); 3876 if (bp != null) { 3877 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3878 return bp; 3879 } 3880 throw new SecurityException("Calling uid " 3881 + Binder.getCallingUid() 3882 + " is not allowed to add to permission tree " 3883 + bp.name + " owned by uid " + bp.uid); 3884 } 3885 } 3886 throw new SecurityException("No permission tree found for " + permName); 3887 } 3888 3889 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3890 if (s1 == null) { 3891 return s2 == null; 3892 } 3893 if (s2 == null) { 3894 return false; 3895 } 3896 if (s1.getClass() != s2.getClass()) { 3897 return false; 3898 } 3899 return s1.equals(s2); 3900 } 3901 3902 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3903 if (pi1.icon != pi2.icon) return false; 3904 if (pi1.logo != pi2.logo) return false; 3905 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3906 if (!compareStrings(pi1.name, pi2.name)) return false; 3907 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3908 // We'll take care of setting this one. 3909 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3910 // These are not currently stored in settings. 3911 //if (!compareStrings(pi1.group, pi2.group)) return false; 3912 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3913 //if (pi1.labelRes != pi2.labelRes) return false; 3914 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3915 return true; 3916 } 3917 3918 int permissionInfoFootprint(PermissionInfo info) { 3919 int size = info.name.length(); 3920 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3921 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3922 return size; 3923 } 3924 3925 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3926 int size = 0; 3927 for (BasePermission perm : mSettings.mPermissions.values()) { 3928 if (perm.uid == tree.uid) { 3929 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3930 } 3931 } 3932 return size; 3933 } 3934 3935 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3936 // We calculate the max size of permissions defined by this uid and throw 3937 // if that plus the size of 'info' would exceed our stated maximum. 3938 if (tree.uid != Process.SYSTEM_UID) { 3939 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3940 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3941 throw new SecurityException("Permission tree size cap exceeded"); 3942 } 3943 } 3944 } 3945 3946 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3947 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3948 throw new SecurityException("Label must be specified in permission"); 3949 } 3950 BasePermission tree = checkPermissionTreeLP(info.name); 3951 BasePermission bp = mSettings.mPermissions.get(info.name); 3952 boolean added = bp == null; 3953 boolean changed = true; 3954 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3955 if (added) { 3956 enforcePermissionCapLocked(info, tree); 3957 bp = new BasePermission(info.name, tree.sourcePackage, 3958 BasePermission.TYPE_DYNAMIC); 3959 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3960 throw new SecurityException( 3961 "Not allowed to modify non-dynamic permission " 3962 + info.name); 3963 } else { 3964 if (bp.protectionLevel == fixedLevel 3965 && bp.perm.owner.equals(tree.perm.owner) 3966 && bp.uid == tree.uid 3967 && comparePermissionInfos(bp.perm.info, info)) { 3968 changed = false; 3969 } 3970 } 3971 bp.protectionLevel = fixedLevel; 3972 info = new PermissionInfo(info); 3973 info.protectionLevel = fixedLevel; 3974 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3975 bp.perm.info.packageName = tree.perm.info.packageName; 3976 bp.uid = tree.uid; 3977 if (added) { 3978 mSettings.mPermissions.put(info.name, bp); 3979 } 3980 if (changed) { 3981 if (!async) { 3982 mSettings.writeLPr(); 3983 } else { 3984 scheduleWriteSettingsLocked(); 3985 } 3986 } 3987 return added; 3988 } 3989 3990 @Override 3991 public boolean addPermission(PermissionInfo info) { 3992 synchronized (mPackages) { 3993 return addPermissionLocked(info, false); 3994 } 3995 } 3996 3997 @Override 3998 public boolean addPermissionAsync(PermissionInfo info) { 3999 synchronized (mPackages) { 4000 return addPermissionLocked(info, true); 4001 } 4002 } 4003 4004 @Override 4005 public void removePermission(String name) { 4006 synchronized (mPackages) { 4007 checkPermissionTreeLP(name); 4008 BasePermission bp = mSettings.mPermissions.get(name); 4009 if (bp != null) { 4010 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4011 throw new SecurityException( 4012 "Not allowed to modify non-dynamic permission " 4013 + name); 4014 } 4015 mSettings.mPermissions.remove(name); 4016 mSettings.writeLPr(); 4017 } 4018 } 4019 } 4020 4021 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4022 BasePermission bp) { 4023 int index = pkg.requestedPermissions.indexOf(bp.name); 4024 if (index == -1) { 4025 throw new SecurityException("Package " + pkg.packageName 4026 + " has not requested permission " + bp.name); 4027 } 4028 if (!bp.isRuntime() && !bp.isDevelopment()) { 4029 throw new SecurityException("Permission " + bp.name 4030 + " is not a changeable permission type"); 4031 } 4032 } 4033 4034 @Override 4035 public void grantRuntimePermission(String packageName, String name, final int userId) { 4036 if (!sUserManager.exists(userId)) { 4037 Log.e(TAG, "No such user:" + userId); 4038 return; 4039 } 4040 4041 mContext.enforceCallingOrSelfPermission( 4042 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4043 "grantRuntimePermission"); 4044 4045 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4046 true /* requireFullPermission */, true /* checkShell */, 4047 "grantRuntimePermission"); 4048 4049 final int uid; 4050 final SettingBase sb; 4051 4052 synchronized (mPackages) { 4053 final PackageParser.Package pkg = mPackages.get(packageName); 4054 if (pkg == null) { 4055 throw new IllegalArgumentException("Unknown package: " + packageName); 4056 } 4057 4058 final BasePermission bp = mSettings.mPermissions.get(name); 4059 if (bp == null) { 4060 throw new IllegalArgumentException("Unknown permission: " + name); 4061 } 4062 4063 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4064 4065 // If a permission review is required for legacy apps we represent 4066 // their permissions as always granted runtime ones since we need 4067 // to keep the review required permission flag per user while an 4068 // install permission's state is shared across all users. 4069 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) 4070 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4071 && bp.isRuntime()) { 4072 return; 4073 } 4074 4075 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4076 sb = (SettingBase) pkg.mExtras; 4077 if (sb == null) { 4078 throw new IllegalArgumentException("Unknown package: " + packageName); 4079 } 4080 4081 final PermissionsState permissionsState = sb.getPermissionsState(); 4082 4083 final int flags = permissionsState.getPermissionFlags(name, userId); 4084 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4085 throw new SecurityException("Cannot grant system fixed permission " 4086 + name + " for package " + packageName); 4087 } 4088 4089 if (bp.isDevelopment()) { 4090 // Development permissions must be handled specially, since they are not 4091 // normal runtime permissions. For now they apply to all users. 4092 if (permissionsState.grantInstallPermission(bp) != 4093 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4094 scheduleWriteSettingsLocked(); 4095 } 4096 return; 4097 } 4098 4099 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4100 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4101 return; 4102 } 4103 4104 final int result = permissionsState.grantRuntimePermission(bp, userId); 4105 switch (result) { 4106 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4107 return; 4108 } 4109 4110 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4111 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4112 mHandler.post(new Runnable() { 4113 @Override 4114 public void run() { 4115 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4116 } 4117 }); 4118 } 4119 break; 4120 } 4121 4122 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4123 4124 // Not critical if that is lost - app has to request again. 4125 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4126 } 4127 4128 // Only need to do this if user is initialized. Otherwise it's a new user 4129 // and there are no processes running as the user yet and there's no need 4130 // to make an expensive call to remount processes for the changed permissions. 4131 if (READ_EXTERNAL_STORAGE.equals(name) 4132 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4133 final long token = Binder.clearCallingIdentity(); 4134 try { 4135 if (sUserManager.isInitialized(userId)) { 4136 MountServiceInternal mountServiceInternal = LocalServices.getService( 4137 MountServiceInternal.class); 4138 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4139 } 4140 } finally { 4141 Binder.restoreCallingIdentity(token); 4142 } 4143 } 4144 } 4145 4146 @Override 4147 public void revokeRuntimePermission(String packageName, String name, int userId) { 4148 if (!sUserManager.exists(userId)) { 4149 Log.e(TAG, "No such user:" + userId); 4150 return; 4151 } 4152 4153 mContext.enforceCallingOrSelfPermission( 4154 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4155 "revokeRuntimePermission"); 4156 4157 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4158 true /* requireFullPermission */, true /* checkShell */, 4159 "revokeRuntimePermission"); 4160 4161 final int appId; 4162 4163 synchronized (mPackages) { 4164 final PackageParser.Package pkg = mPackages.get(packageName); 4165 if (pkg == null) { 4166 throw new IllegalArgumentException("Unknown package: " + packageName); 4167 } 4168 4169 final BasePermission bp = mSettings.mPermissions.get(name); 4170 if (bp == null) { 4171 throw new IllegalArgumentException("Unknown permission: " + name); 4172 } 4173 4174 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4175 4176 // If a permission review is required for legacy apps we represent 4177 // their permissions as always granted runtime ones since we need 4178 // to keep the review required permission flag per user while an 4179 // install permission's state is shared across all users. 4180 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) 4181 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4182 && bp.isRuntime()) { 4183 return; 4184 } 4185 4186 SettingBase sb = (SettingBase) pkg.mExtras; 4187 if (sb == null) { 4188 throw new IllegalArgumentException("Unknown package: " + packageName); 4189 } 4190 4191 final PermissionsState permissionsState = sb.getPermissionsState(); 4192 4193 final int flags = permissionsState.getPermissionFlags(name, userId); 4194 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4195 throw new SecurityException("Cannot revoke system fixed permission " 4196 + name + " for package " + packageName); 4197 } 4198 4199 if (bp.isDevelopment()) { 4200 // Development permissions must be handled specially, since they are not 4201 // normal runtime permissions. For now they apply to all users. 4202 if (permissionsState.revokeInstallPermission(bp) != 4203 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4204 scheduleWriteSettingsLocked(); 4205 } 4206 return; 4207 } 4208 4209 if (permissionsState.revokeRuntimePermission(bp, userId) == 4210 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4211 return; 4212 } 4213 4214 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4215 4216 // Critical, after this call app should never have the permission. 4217 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4218 4219 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4220 } 4221 4222 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4223 } 4224 4225 @Override 4226 public void resetRuntimePermissions() { 4227 mContext.enforceCallingOrSelfPermission( 4228 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4229 "revokeRuntimePermission"); 4230 4231 int callingUid = Binder.getCallingUid(); 4232 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4233 mContext.enforceCallingOrSelfPermission( 4234 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4235 "resetRuntimePermissions"); 4236 } 4237 4238 synchronized (mPackages) { 4239 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4240 for (int userId : UserManagerService.getInstance().getUserIds()) { 4241 final int packageCount = mPackages.size(); 4242 for (int i = 0; i < packageCount; i++) { 4243 PackageParser.Package pkg = mPackages.valueAt(i); 4244 if (!(pkg.mExtras instanceof PackageSetting)) { 4245 continue; 4246 } 4247 PackageSetting ps = (PackageSetting) pkg.mExtras; 4248 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4249 } 4250 } 4251 } 4252 } 4253 4254 @Override 4255 public int getPermissionFlags(String name, String packageName, int userId) { 4256 if (!sUserManager.exists(userId)) { 4257 return 0; 4258 } 4259 4260 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4261 4262 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4263 true /* requireFullPermission */, false /* checkShell */, 4264 "getPermissionFlags"); 4265 4266 synchronized (mPackages) { 4267 final PackageParser.Package pkg = mPackages.get(packageName); 4268 if (pkg == null) { 4269 return 0; 4270 } 4271 4272 final BasePermission bp = mSettings.mPermissions.get(name); 4273 if (bp == null) { 4274 return 0; 4275 } 4276 4277 SettingBase sb = (SettingBase) pkg.mExtras; 4278 if (sb == null) { 4279 return 0; 4280 } 4281 4282 PermissionsState permissionsState = sb.getPermissionsState(); 4283 return permissionsState.getPermissionFlags(name, userId); 4284 } 4285 } 4286 4287 @Override 4288 public void updatePermissionFlags(String name, String packageName, int flagMask, 4289 int flagValues, int userId) { 4290 if (!sUserManager.exists(userId)) { 4291 return; 4292 } 4293 4294 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4295 4296 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4297 true /* requireFullPermission */, true /* checkShell */, 4298 "updatePermissionFlags"); 4299 4300 // Only the system can change these flags and nothing else. 4301 if (getCallingUid() != Process.SYSTEM_UID) { 4302 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4303 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4304 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4305 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4306 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4307 } 4308 4309 synchronized (mPackages) { 4310 final PackageParser.Package pkg = mPackages.get(packageName); 4311 if (pkg == null) { 4312 throw new IllegalArgumentException("Unknown package: " + packageName); 4313 } 4314 4315 final BasePermission bp = mSettings.mPermissions.get(name); 4316 if (bp == null) { 4317 throw new IllegalArgumentException("Unknown permission: " + name); 4318 } 4319 4320 SettingBase sb = (SettingBase) pkg.mExtras; 4321 if (sb == null) { 4322 throw new IllegalArgumentException("Unknown package: " + packageName); 4323 } 4324 4325 PermissionsState permissionsState = sb.getPermissionsState(); 4326 4327 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4328 4329 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4330 // Install and runtime permissions are stored in different places, 4331 // so figure out what permission changed and persist the change. 4332 if (permissionsState.getInstallPermissionState(name) != null) { 4333 scheduleWriteSettingsLocked(); 4334 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4335 || hadState) { 4336 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4337 } 4338 } 4339 } 4340 } 4341 4342 /** 4343 * Update the permission flags for all packages and runtime permissions of a user in order 4344 * to allow device or profile owner to remove POLICY_FIXED. 4345 */ 4346 @Override 4347 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4348 if (!sUserManager.exists(userId)) { 4349 return; 4350 } 4351 4352 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4353 4354 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4355 true /* requireFullPermission */, true /* checkShell */, 4356 "updatePermissionFlagsForAllApps"); 4357 4358 // Only the system can change system fixed flags. 4359 if (getCallingUid() != Process.SYSTEM_UID) { 4360 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4361 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4362 } 4363 4364 synchronized (mPackages) { 4365 boolean changed = false; 4366 final int packageCount = mPackages.size(); 4367 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4368 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4369 SettingBase sb = (SettingBase) pkg.mExtras; 4370 if (sb == null) { 4371 continue; 4372 } 4373 PermissionsState permissionsState = sb.getPermissionsState(); 4374 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4375 userId, flagMask, flagValues); 4376 } 4377 if (changed) { 4378 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4379 } 4380 } 4381 } 4382 4383 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4384 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4385 != PackageManager.PERMISSION_GRANTED 4386 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4387 != PackageManager.PERMISSION_GRANTED) { 4388 throw new SecurityException(message + " requires " 4389 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4390 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4391 } 4392 } 4393 4394 @Override 4395 public boolean shouldShowRequestPermissionRationale(String permissionName, 4396 String packageName, int userId) { 4397 if (UserHandle.getCallingUserId() != userId) { 4398 mContext.enforceCallingPermission( 4399 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4400 "canShowRequestPermissionRationale for user " + userId); 4401 } 4402 4403 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4404 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4405 return false; 4406 } 4407 4408 if (checkPermission(permissionName, packageName, userId) 4409 == PackageManager.PERMISSION_GRANTED) { 4410 return false; 4411 } 4412 4413 final int flags; 4414 4415 final long identity = Binder.clearCallingIdentity(); 4416 try { 4417 flags = getPermissionFlags(permissionName, 4418 packageName, userId); 4419 } finally { 4420 Binder.restoreCallingIdentity(identity); 4421 } 4422 4423 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4424 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4425 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4426 4427 if ((flags & fixedFlags) != 0) { 4428 return false; 4429 } 4430 4431 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4432 } 4433 4434 @Override 4435 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4436 mContext.enforceCallingOrSelfPermission( 4437 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4438 "addOnPermissionsChangeListener"); 4439 4440 synchronized (mPackages) { 4441 mOnPermissionChangeListeners.addListenerLocked(listener); 4442 } 4443 } 4444 4445 @Override 4446 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4447 synchronized (mPackages) { 4448 mOnPermissionChangeListeners.removeListenerLocked(listener); 4449 } 4450 } 4451 4452 @Override 4453 public boolean isProtectedBroadcast(String actionName) { 4454 synchronized (mPackages) { 4455 if (mProtectedBroadcasts.contains(actionName)) { 4456 return true; 4457 } else if (actionName != null) { 4458 // TODO: remove these terrible hacks 4459 if (actionName.startsWith("android.net.netmon.lingerExpired") 4460 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4461 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4462 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4463 return true; 4464 } 4465 } 4466 } 4467 return false; 4468 } 4469 4470 @Override 4471 public int checkSignatures(String pkg1, String pkg2) { 4472 synchronized (mPackages) { 4473 final PackageParser.Package p1 = mPackages.get(pkg1); 4474 final PackageParser.Package p2 = mPackages.get(pkg2); 4475 if (p1 == null || p1.mExtras == null 4476 || p2 == null || p2.mExtras == null) { 4477 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4478 } 4479 return compareSignatures(p1.mSignatures, p2.mSignatures); 4480 } 4481 } 4482 4483 @Override 4484 public int checkUidSignatures(int uid1, int uid2) { 4485 // Map to base uids. 4486 uid1 = UserHandle.getAppId(uid1); 4487 uid2 = UserHandle.getAppId(uid2); 4488 // reader 4489 synchronized (mPackages) { 4490 Signature[] s1; 4491 Signature[] s2; 4492 Object obj = mSettings.getUserIdLPr(uid1); 4493 if (obj != null) { 4494 if (obj instanceof SharedUserSetting) { 4495 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4496 } else if (obj instanceof PackageSetting) { 4497 s1 = ((PackageSetting)obj).signatures.mSignatures; 4498 } else { 4499 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4500 } 4501 } else { 4502 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4503 } 4504 obj = mSettings.getUserIdLPr(uid2); 4505 if (obj != null) { 4506 if (obj instanceof SharedUserSetting) { 4507 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4508 } else if (obj instanceof PackageSetting) { 4509 s2 = ((PackageSetting)obj).signatures.mSignatures; 4510 } else { 4511 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4512 } 4513 } else { 4514 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4515 } 4516 return compareSignatures(s1, s2); 4517 } 4518 } 4519 4520 /** 4521 * This method should typically only be used when granting or revoking 4522 * permissions, since the app may immediately restart after this call. 4523 * <p> 4524 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4525 * guard your work against the app being relaunched. 4526 */ 4527 private void killUid(int appId, int userId, String reason) { 4528 final long identity = Binder.clearCallingIdentity(); 4529 try { 4530 IActivityManager am = ActivityManagerNative.getDefault(); 4531 if (am != null) { 4532 try { 4533 am.killUid(appId, userId, reason); 4534 } catch (RemoteException e) { 4535 /* ignore - same process */ 4536 } 4537 } 4538 } finally { 4539 Binder.restoreCallingIdentity(identity); 4540 } 4541 } 4542 4543 /** 4544 * Compares two sets of signatures. Returns: 4545 * <br /> 4546 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4547 * <br /> 4548 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4549 * <br /> 4550 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4551 * <br /> 4552 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4553 * <br /> 4554 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4555 */ 4556 static int compareSignatures(Signature[] s1, Signature[] s2) { 4557 if (s1 == null) { 4558 return s2 == null 4559 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4560 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4561 } 4562 4563 if (s2 == null) { 4564 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4565 } 4566 4567 if (s1.length != s2.length) { 4568 return PackageManager.SIGNATURE_NO_MATCH; 4569 } 4570 4571 // Since both signature sets are of size 1, we can compare without HashSets. 4572 if (s1.length == 1) { 4573 return s1[0].equals(s2[0]) ? 4574 PackageManager.SIGNATURE_MATCH : 4575 PackageManager.SIGNATURE_NO_MATCH; 4576 } 4577 4578 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4579 for (Signature sig : s1) { 4580 set1.add(sig); 4581 } 4582 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4583 for (Signature sig : s2) { 4584 set2.add(sig); 4585 } 4586 // Make sure s2 contains all signatures in s1. 4587 if (set1.equals(set2)) { 4588 return PackageManager.SIGNATURE_MATCH; 4589 } 4590 return PackageManager.SIGNATURE_NO_MATCH; 4591 } 4592 4593 /** 4594 * If the database version for this type of package (internal storage or 4595 * external storage) is less than the version where package signatures 4596 * were updated, return true. 4597 */ 4598 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4599 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4600 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4601 } 4602 4603 /** 4604 * Used for backward compatibility to make sure any packages with 4605 * certificate chains get upgraded to the new style. {@code existingSigs} 4606 * will be in the old format (since they were stored on disk from before the 4607 * system upgrade) and {@code scannedSigs} will be in the newer format. 4608 */ 4609 private int compareSignaturesCompat(PackageSignatures existingSigs, 4610 PackageParser.Package scannedPkg) { 4611 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4612 return PackageManager.SIGNATURE_NO_MATCH; 4613 } 4614 4615 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4616 for (Signature sig : existingSigs.mSignatures) { 4617 existingSet.add(sig); 4618 } 4619 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4620 for (Signature sig : scannedPkg.mSignatures) { 4621 try { 4622 Signature[] chainSignatures = sig.getChainSignatures(); 4623 for (Signature chainSig : chainSignatures) { 4624 scannedCompatSet.add(chainSig); 4625 } 4626 } catch (CertificateEncodingException e) { 4627 scannedCompatSet.add(sig); 4628 } 4629 } 4630 /* 4631 * Make sure the expanded scanned set contains all signatures in the 4632 * existing one. 4633 */ 4634 if (scannedCompatSet.equals(existingSet)) { 4635 // Migrate the old signatures to the new scheme. 4636 existingSigs.assignSignatures(scannedPkg.mSignatures); 4637 // The new KeySets will be re-added later in the scanning process. 4638 synchronized (mPackages) { 4639 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4640 } 4641 return PackageManager.SIGNATURE_MATCH; 4642 } 4643 return PackageManager.SIGNATURE_NO_MATCH; 4644 } 4645 4646 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4647 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4648 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4649 } 4650 4651 private int compareSignaturesRecover(PackageSignatures existingSigs, 4652 PackageParser.Package scannedPkg) { 4653 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4654 return PackageManager.SIGNATURE_NO_MATCH; 4655 } 4656 4657 String msg = null; 4658 try { 4659 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4660 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4661 + scannedPkg.packageName); 4662 return PackageManager.SIGNATURE_MATCH; 4663 } 4664 } catch (CertificateException e) { 4665 msg = e.getMessage(); 4666 } 4667 4668 logCriticalInfo(Log.INFO, 4669 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4670 return PackageManager.SIGNATURE_NO_MATCH; 4671 } 4672 4673 @Override 4674 public List<String> getAllPackages() { 4675 synchronized (mPackages) { 4676 return new ArrayList<String>(mPackages.keySet()); 4677 } 4678 } 4679 4680 @Override 4681 public String[] getPackagesForUid(int uid) { 4682 final int userId = UserHandle.getUserId(uid); 4683 uid = UserHandle.getAppId(uid); 4684 // reader 4685 synchronized (mPackages) { 4686 Object obj = mSettings.getUserIdLPr(uid); 4687 if (obj instanceof SharedUserSetting) { 4688 final SharedUserSetting sus = (SharedUserSetting) obj; 4689 final int N = sus.packages.size(); 4690 String[] res = new String[N]; 4691 final Iterator<PackageSetting> it = sus.packages.iterator(); 4692 int i = 0; 4693 while (it.hasNext()) { 4694 PackageSetting ps = it.next(); 4695 if (ps.getInstalled(userId)) { 4696 res[i++] = ps.name; 4697 } else { 4698 res = ArrayUtils.removeElement(String.class, res, res[i]); 4699 } 4700 } 4701 return res; 4702 } else if (obj instanceof PackageSetting) { 4703 final PackageSetting ps = (PackageSetting) obj; 4704 return new String[] { ps.name }; 4705 } 4706 } 4707 return null; 4708 } 4709 4710 @Override 4711 public String getNameForUid(int uid) { 4712 // reader 4713 synchronized (mPackages) { 4714 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4715 if (obj instanceof SharedUserSetting) { 4716 final SharedUserSetting sus = (SharedUserSetting) obj; 4717 return sus.name + ":" + sus.userId; 4718 } else if (obj instanceof PackageSetting) { 4719 final PackageSetting ps = (PackageSetting) obj; 4720 return ps.name; 4721 } 4722 } 4723 return null; 4724 } 4725 4726 @Override 4727 public int getUidForSharedUser(String sharedUserName) { 4728 if(sharedUserName == null) { 4729 return -1; 4730 } 4731 // reader 4732 synchronized (mPackages) { 4733 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4734 if (suid == null) { 4735 return -1; 4736 } 4737 return suid.userId; 4738 } 4739 } 4740 4741 @Override 4742 public int getFlagsForUid(int uid) { 4743 synchronized (mPackages) { 4744 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4745 if (obj instanceof SharedUserSetting) { 4746 final SharedUserSetting sus = (SharedUserSetting) obj; 4747 return sus.pkgFlags; 4748 } else if (obj instanceof PackageSetting) { 4749 final PackageSetting ps = (PackageSetting) obj; 4750 return ps.pkgFlags; 4751 } 4752 } 4753 return 0; 4754 } 4755 4756 @Override 4757 public int getPrivateFlagsForUid(int uid) { 4758 synchronized (mPackages) { 4759 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4760 if (obj instanceof SharedUserSetting) { 4761 final SharedUserSetting sus = (SharedUserSetting) obj; 4762 return sus.pkgPrivateFlags; 4763 } else if (obj instanceof PackageSetting) { 4764 final PackageSetting ps = (PackageSetting) obj; 4765 return ps.pkgPrivateFlags; 4766 } 4767 } 4768 return 0; 4769 } 4770 4771 @Override 4772 public boolean isUidPrivileged(int uid) { 4773 uid = UserHandle.getAppId(uid); 4774 // reader 4775 synchronized (mPackages) { 4776 Object obj = mSettings.getUserIdLPr(uid); 4777 if (obj instanceof SharedUserSetting) { 4778 final SharedUserSetting sus = (SharedUserSetting) obj; 4779 final Iterator<PackageSetting> it = sus.packages.iterator(); 4780 while (it.hasNext()) { 4781 if (it.next().isPrivileged()) { 4782 return true; 4783 } 4784 } 4785 } else if (obj instanceof PackageSetting) { 4786 final PackageSetting ps = (PackageSetting) obj; 4787 return ps.isPrivileged(); 4788 } 4789 } 4790 return false; 4791 } 4792 4793 @Override 4794 public String[] getAppOpPermissionPackages(String permissionName) { 4795 synchronized (mPackages) { 4796 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4797 if (pkgs == null) { 4798 return null; 4799 } 4800 return pkgs.toArray(new String[pkgs.size()]); 4801 } 4802 } 4803 4804 @Override 4805 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4806 int flags, int userId) { 4807 try { 4808 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4809 4810 if (!sUserManager.exists(userId)) return null; 4811 flags = updateFlagsForResolve(flags, userId, intent); 4812 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4813 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4814 4815 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4816 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4817 flags, userId); 4818 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4819 4820 final ResolveInfo bestChoice = 4821 chooseBestActivity(intent, resolvedType, flags, query, userId); 4822 return bestChoice; 4823 } finally { 4824 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4825 } 4826 } 4827 4828 @Override 4829 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4830 IntentFilter filter, int match, ComponentName activity) { 4831 final int userId = UserHandle.getCallingUserId(); 4832 if (DEBUG_PREFERRED) { 4833 Log.v(TAG, "setLastChosenActivity intent=" + intent 4834 + " resolvedType=" + resolvedType 4835 + " flags=" + flags 4836 + " filter=" + filter 4837 + " match=" + match 4838 + " activity=" + activity); 4839 filter.dump(new PrintStreamPrinter(System.out), " "); 4840 } 4841 intent.setComponent(null); 4842 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4843 userId); 4844 // Find any earlier preferred or last chosen entries and nuke them 4845 findPreferredActivity(intent, resolvedType, 4846 flags, query, 0, false, true, false, userId); 4847 // Add the new activity as the last chosen for this filter 4848 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4849 "Setting last chosen"); 4850 } 4851 4852 @Override 4853 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4854 final int userId = UserHandle.getCallingUserId(); 4855 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4856 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4857 userId); 4858 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4859 false, false, false, userId); 4860 } 4861 4862 private boolean isEphemeralDisabled() { 4863 // ephemeral apps have been disabled across the board 4864 if (DISABLE_EPHEMERAL_APPS) { 4865 return true; 4866 } 4867 // system isn't up yet; can't read settings, so, assume no ephemeral apps 4868 if (!mSystemReady) { 4869 return true; 4870 } 4871 // we can't get a content resolver until the system is ready; these checks must happen last 4872 final ContentResolver resolver = mContext.getContentResolver(); 4873 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 4874 return true; 4875 } 4876 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 4877 } 4878 4879 private boolean isEphemeralAllowed( 4880 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 4881 boolean skipPackageCheck) { 4882 // Short circuit and return early if possible. 4883 if (isEphemeralDisabled()) { 4884 return false; 4885 } 4886 final int callingUser = UserHandle.getCallingUserId(); 4887 if (callingUser != UserHandle.USER_SYSTEM) { 4888 return false; 4889 } 4890 if (mEphemeralResolverConnection == null) { 4891 return false; 4892 } 4893 if (intent.getComponent() != null) { 4894 return false; 4895 } 4896 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 4897 return false; 4898 } 4899 if (!skipPackageCheck && intent.getPackage() != null) { 4900 return false; 4901 } 4902 final boolean isWebUri = hasWebURI(intent); 4903 if (!isWebUri || intent.getData().getHost() == null) { 4904 return false; 4905 } 4906 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4907 synchronized (mPackages) { 4908 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 4909 for (int n = 0; n < count; n++) { 4910 ResolveInfo info = resolvedActivities.get(n); 4911 String packageName = info.activityInfo.packageName; 4912 PackageSetting ps = mSettings.mPackages.get(packageName); 4913 if (ps != null) { 4914 // Try to get the status from User settings first 4915 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4916 int status = (int) (packedStatus >> 32); 4917 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4918 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4919 if (DEBUG_EPHEMERAL) { 4920 Slog.v(TAG, "DENY ephemeral apps;" 4921 + " pkg: " + packageName + ", status: " + status); 4922 } 4923 return false; 4924 } 4925 } 4926 } 4927 } 4928 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4929 return true; 4930 } 4931 4932 private static EphemeralResolveInfo getEphemeralResolveInfo( 4933 Context context, EphemeralResolverConnection resolverConnection, Intent intent, 4934 String resolvedType, int userId, String packageName) { 4935 final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(), 4936 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 4937 final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(), 4938 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 4939 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 4940 ephemeralPrefixCount); 4941 final int[] shaPrefix = digest.getDigestPrefix(); 4942 final byte[][] digestBytes = digest.getDigestBytes(); 4943 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4944 resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask); 4945 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4946 // No hash prefix match; there are no ephemeral apps for this domain. 4947 return null; 4948 } 4949 4950 // Go in reverse order so we match the narrowest scope first. 4951 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 4952 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 4953 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 4954 continue; 4955 } 4956 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4957 // No filters; this should never happen. 4958 if (filters.isEmpty()) { 4959 continue; 4960 } 4961 if (packageName != null 4962 && !packageName.equals(ephemeralApplication.getPackageName())) { 4963 continue; 4964 } 4965 // We have a domain match; resolve the filters to see if anything matches. 4966 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4967 for (int j = filters.size() - 1; j >= 0; --j) { 4968 final EphemeralResolveIntentInfo intentInfo = 4969 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4970 ephemeralResolver.addFilter(intentInfo); 4971 } 4972 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4973 intent, resolvedType, false /*defaultOnly*/, userId); 4974 if (!matchedResolveInfoList.isEmpty()) { 4975 return matchedResolveInfoList.get(0); 4976 } 4977 } 4978 } 4979 // Hash or filter mis-match; no ephemeral apps for this domain. 4980 return null; 4981 } 4982 4983 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4984 int flags, List<ResolveInfo> query, int userId) { 4985 if (query != null) { 4986 final int N = query.size(); 4987 if (N == 1) { 4988 return query.get(0); 4989 } else if (N > 1) { 4990 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4991 // If there is more than one activity with the same priority, 4992 // then let the user decide between them. 4993 ResolveInfo r0 = query.get(0); 4994 ResolveInfo r1 = query.get(1); 4995 if (DEBUG_INTENT_MATCHING || debug) { 4996 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4997 + r1.activityInfo.name + "=" + r1.priority); 4998 } 4999 // If the first activity has a higher priority, or a different 5000 // default, then it is always desirable to pick it. 5001 if (r0.priority != r1.priority 5002 || r0.preferredOrder != r1.preferredOrder 5003 || r0.isDefault != r1.isDefault) { 5004 return query.get(0); 5005 } 5006 // If we have saved a preference for a preferred activity for 5007 // this Intent, use that. 5008 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5009 flags, query, r0.priority, true, false, debug, userId); 5010 if (ri != null) { 5011 return ri; 5012 } 5013 ri = new ResolveInfo(mResolveInfo); 5014 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5015 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5016 // If all of the options come from the same package, show the application's 5017 // label and icon instead of the generic resolver's. 5018 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5019 // and then throw away the ResolveInfo itself, meaning that the caller loses 5020 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5021 // a fallback for this case; we only set the target package's resources on 5022 // the ResolveInfo, not the ActivityInfo. 5023 final String intentPackage = intent.getPackage(); 5024 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5025 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5026 ri.resolvePackageName = intentPackage; 5027 if (userNeedsBadging(userId)) { 5028 ri.noResourceId = true; 5029 } else { 5030 ri.icon = appi.icon; 5031 } 5032 ri.iconResourceId = appi.icon; 5033 ri.labelRes = appi.labelRes; 5034 } 5035 ri.activityInfo.applicationInfo = new ApplicationInfo( 5036 ri.activityInfo.applicationInfo); 5037 if (userId != 0) { 5038 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5039 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5040 } 5041 // Make sure that the resolver is displayable in car mode 5042 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5043 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5044 return ri; 5045 } 5046 } 5047 return null; 5048 } 5049 5050 /** 5051 * Return true if the given list is not empty and all of its contents have 5052 * an activityInfo with the given package name. 5053 */ 5054 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5055 if (ArrayUtils.isEmpty(list)) { 5056 return false; 5057 } 5058 for (int i = 0, N = list.size(); i < N; i++) { 5059 final ResolveInfo ri = list.get(i); 5060 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5061 if (ai == null || !packageName.equals(ai.packageName)) { 5062 return false; 5063 } 5064 } 5065 return true; 5066 } 5067 5068 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5069 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5070 final int N = query.size(); 5071 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5072 .get(userId); 5073 // Get the list of persistent preferred activities that handle the intent 5074 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5075 List<PersistentPreferredActivity> pprefs = ppir != null 5076 ? ppir.queryIntent(intent, resolvedType, 5077 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5078 : null; 5079 if (pprefs != null && pprefs.size() > 0) { 5080 final int M = pprefs.size(); 5081 for (int i=0; i<M; i++) { 5082 final PersistentPreferredActivity ppa = pprefs.get(i); 5083 if (DEBUG_PREFERRED || debug) { 5084 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5085 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5086 + "\n component=" + ppa.mComponent); 5087 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5088 } 5089 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5090 flags | MATCH_DISABLED_COMPONENTS, userId); 5091 if (DEBUG_PREFERRED || debug) { 5092 Slog.v(TAG, "Found persistent preferred activity:"); 5093 if (ai != null) { 5094 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5095 } else { 5096 Slog.v(TAG, " null"); 5097 } 5098 } 5099 if (ai == null) { 5100 // This previously registered persistent preferred activity 5101 // component is no longer known. Ignore it and do NOT remove it. 5102 continue; 5103 } 5104 for (int j=0; j<N; j++) { 5105 final ResolveInfo ri = query.get(j); 5106 if (!ri.activityInfo.applicationInfo.packageName 5107 .equals(ai.applicationInfo.packageName)) { 5108 continue; 5109 } 5110 if (!ri.activityInfo.name.equals(ai.name)) { 5111 continue; 5112 } 5113 // Found a persistent preference that can handle the intent. 5114 if (DEBUG_PREFERRED || debug) { 5115 Slog.v(TAG, "Returning persistent preferred activity: " + 5116 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5117 } 5118 return ri; 5119 } 5120 } 5121 } 5122 return null; 5123 } 5124 5125 // TODO: handle preferred activities missing while user has amnesia 5126 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5127 List<ResolveInfo> query, int priority, boolean always, 5128 boolean removeMatches, boolean debug, int userId) { 5129 if (!sUserManager.exists(userId)) return null; 5130 flags = updateFlagsForResolve(flags, userId, intent); 5131 // writer 5132 synchronized (mPackages) { 5133 if (intent.getSelector() != null) { 5134 intent = intent.getSelector(); 5135 } 5136 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5137 5138 // Try to find a matching persistent preferred activity. 5139 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5140 debug, userId); 5141 5142 // If a persistent preferred activity matched, use it. 5143 if (pri != null) { 5144 return pri; 5145 } 5146 5147 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5148 // Get the list of preferred activities that handle the intent 5149 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5150 List<PreferredActivity> prefs = pir != null 5151 ? pir.queryIntent(intent, resolvedType, 5152 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5153 : null; 5154 if (prefs != null && prefs.size() > 0) { 5155 boolean changed = false; 5156 try { 5157 // First figure out how good the original match set is. 5158 // We will only allow preferred activities that came 5159 // from the same match quality. 5160 int match = 0; 5161 5162 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5163 5164 final int N = query.size(); 5165 for (int j=0; j<N; j++) { 5166 final ResolveInfo ri = query.get(j); 5167 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5168 + ": 0x" + Integer.toHexString(match)); 5169 if (ri.match > match) { 5170 match = ri.match; 5171 } 5172 } 5173 5174 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5175 + Integer.toHexString(match)); 5176 5177 match &= IntentFilter.MATCH_CATEGORY_MASK; 5178 final int M = prefs.size(); 5179 for (int i=0; i<M; i++) { 5180 final PreferredActivity pa = prefs.get(i); 5181 if (DEBUG_PREFERRED || debug) { 5182 Slog.v(TAG, "Checking PreferredActivity ds=" 5183 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5184 + "\n component=" + pa.mPref.mComponent); 5185 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5186 } 5187 if (pa.mPref.mMatch != match) { 5188 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5189 + Integer.toHexString(pa.mPref.mMatch)); 5190 continue; 5191 } 5192 // If it's not an "always" type preferred activity and that's what we're 5193 // looking for, skip it. 5194 if (always && !pa.mPref.mAlways) { 5195 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5196 continue; 5197 } 5198 final ActivityInfo ai = getActivityInfo( 5199 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5200 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5201 userId); 5202 if (DEBUG_PREFERRED || debug) { 5203 Slog.v(TAG, "Found preferred activity:"); 5204 if (ai != null) { 5205 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5206 } else { 5207 Slog.v(TAG, " null"); 5208 } 5209 } 5210 if (ai == null) { 5211 // This previously registered preferred activity 5212 // component is no longer known. Most likely an update 5213 // to the app was installed and in the new version this 5214 // component no longer exists. Clean it up by removing 5215 // it from the preferred activities list, and skip it. 5216 Slog.w(TAG, "Removing dangling preferred activity: " 5217 + pa.mPref.mComponent); 5218 pir.removeFilter(pa); 5219 changed = true; 5220 continue; 5221 } 5222 for (int j=0; j<N; j++) { 5223 final ResolveInfo ri = query.get(j); 5224 if (!ri.activityInfo.applicationInfo.packageName 5225 .equals(ai.applicationInfo.packageName)) { 5226 continue; 5227 } 5228 if (!ri.activityInfo.name.equals(ai.name)) { 5229 continue; 5230 } 5231 5232 if (removeMatches) { 5233 pir.removeFilter(pa); 5234 changed = true; 5235 if (DEBUG_PREFERRED) { 5236 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5237 } 5238 break; 5239 } 5240 5241 // Okay we found a previously set preferred or last chosen app. 5242 // If the result set is different from when this 5243 // was created, we need to clear it and re-ask the 5244 // user their preference, if we're looking for an "always" type entry. 5245 if (always && !pa.mPref.sameSet(query)) { 5246 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5247 + intent + " type " + resolvedType); 5248 if (DEBUG_PREFERRED) { 5249 Slog.v(TAG, "Removing preferred activity since set changed " 5250 + pa.mPref.mComponent); 5251 } 5252 pir.removeFilter(pa); 5253 // Re-add the filter as a "last chosen" entry (!always) 5254 PreferredActivity lastChosen = new PreferredActivity( 5255 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5256 pir.addFilter(lastChosen); 5257 changed = true; 5258 return null; 5259 } 5260 5261 // Yay! Either the set matched or we're looking for the last chosen 5262 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5263 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5264 return ri; 5265 } 5266 } 5267 } finally { 5268 if (changed) { 5269 if (DEBUG_PREFERRED) { 5270 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5271 } 5272 scheduleWritePackageRestrictionsLocked(userId); 5273 } 5274 } 5275 } 5276 } 5277 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5278 return null; 5279 } 5280 5281 /* 5282 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5283 */ 5284 @Override 5285 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5286 int targetUserId) { 5287 mContext.enforceCallingOrSelfPermission( 5288 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5289 List<CrossProfileIntentFilter> matches = 5290 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5291 if (matches != null) { 5292 int size = matches.size(); 5293 for (int i = 0; i < size; i++) { 5294 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5295 } 5296 } 5297 if (hasWebURI(intent)) { 5298 // cross-profile app linking works only towards the parent. 5299 final UserInfo parent = getProfileParent(sourceUserId); 5300 synchronized(mPackages) { 5301 int flags = updateFlagsForResolve(0, parent.id, intent); 5302 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5303 intent, resolvedType, flags, sourceUserId, parent.id); 5304 return xpDomainInfo != null; 5305 } 5306 } 5307 return false; 5308 } 5309 5310 private UserInfo getProfileParent(int userId) { 5311 final long identity = Binder.clearCallingIdentity(); 5312 try { 5313 return sUserManager.getProfileParent(userId); 5314 } finally { 5315 Binder.restoreCallingIdentity(identity); 5316 } 5317 } 5318 5319 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5320 String resolvedType, int userId) { 5321 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5322 if (resolver != null) { 5323 return resolver.queryIntent(intent, resolvedType, false, userId); 5324 } 5325 return null; 5326 } 5327 5328 @Override 5329 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5330 String resolvedType, int flags, int userId) { 5331 try { 5332 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5333 5334 return new ParceledListSlice<>( 5335 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5336 } finally { 5337 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5338 } 5339 } 5340 5341 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5342 String resolvedType, int flags, int userId) { 5343 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5344 flags = updateFlagsForResolve(flags, userId, intent); 5345 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5346 false /* requireFullPermission */, false /* checkShell */, 5347 "query intent activities"); 5348 ComponentName comp = intent.getComponent(); 5349 if (comp == null) { 5350 if (intent.getSelector() != null) { 5351 intent = intent.getSelector(); 5352 comp = intent.getComponent(); 5353 } 5354 } 5355 5356 if (comp != null) { 5357 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5358 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5359 if (ai != null) { 5360 final ResolveInfo ri = new ResolveInfo(); 5361 ri.activityInfo = ai; 5362 list.add(ri); 5363 } 5364 return list; 5365 } 5366 5367 // reader 5368 boolean sortResult = false; 5369 boolean addEphemeral = false; 5370 boolean matchEphemeralPackage = false; 5371 List<ResolveInfo> result; 5372 final String pkgName = intent.getPackage(); 5373 synchronized (mPackages) { 5374 if (pkgName == null) { 5375 List<CrossProfileIntentFilter> matchingFilters = 5376 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5377 // Check for results that need to skip the current profile. 5378 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5379 resolvedType, flags, userId); 5380 if (xpResolveInfo != null) { 5381 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5382 xpResult.add(xpResolveInfo); 5383 return filterIfNotSystemUser(xpResult, userId); 5384 } 5385 5386 // Check for results in the current profile. 5387 result = filterIfNotSystemUser(mActivities.queryIntent( 5388 intent, resolvedType, flags, userId), userId); 5389 addEphemeral = 5390 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5391 5392 // Check for cross profile results. 5393 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5394 xpResolveInfo = queryCrossProfileIntents( 5395 matchingFilters, intent, resolvedType, flags, userId, 5396 hasNonNegativePriorityResult); 5397 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5398 boolean isVisibleToUser = filterIfNotSystemUser( 5399 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5400 if (isVisibleToUser) { 5401 result.add(xpResolveInfo); 5402 sortResult = true; 5403 } 5404 } 5405 if (hasWebURI(intent)) { 5406 CrossProfileDomainInfo xpDomainInfo = null; 5407 final UserInfo parent = getProfileParent(userId); 5408 if (parent != null) { 5409 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5410 flags, userId, parent.id); 5411 } 5412 if (xpDomainInfo != null) { 5413 if (xpResolveInfo != null) { 5414 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5415 // in the result. 5416 result.remove(xpResolveInfo); 5417 } 5418 if (result.size() == 0 && !addEphemeral) { 5419 result.add(xpDomainInfo.resolveInfo); 5420 return result; 5421 } 5422 } 5423 if (result.size() > 1 || addEphemeral) { 5424 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5425 intent, flags, result, xpDomainInfo, userId); 5426 sortResult = true; 5427 } 5428 } 5429 } else { 5430 final PackageParser.Package pkg = mPackages.get(pkgName); 5431 if (pkg != null) { 5432 result = filterIfNotSystemUser( 5433 mActivities.queryIntentForPackage( 5434 intent, resolvedType, flags, pkg.activities, userId), 5435 userId); 5436 } else { 5437 // the caller wants to resolve for a particular package; however, there 5438 // were no installed results, so, try to find an ephemeral result 5439 addEphemeral = isEphemeralAllowed( 5440 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5441 matchEphemeralPackage = true; 5442 result = new ArrayList<ResolveInfo>(); 5443 } 5444 } 5445 } 5446 if (addEphemeral) { 5447 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5448 final EphemeralResolveInfo ai = getEphemeralResolveInfo( 5449 mContext, mEphemeralResolverConnection, intent, resolvedType, userId, 5450 matchEphemeralPackage ? pkgName : null); 5451 if (ai != null) { 5452 if (DEBUG_EPHEMERAL) { 5453 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5454 } 5455 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5456 ephemeralInstaller.ephemeralResolveInfo = ai; 5457 // make sure this resolver is the default 5458 ephemeralInstaller.isDefault = true; 5459 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5460 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5461 // add a non-generic filter 5462 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5463 ephemeralInstaller.filter.addDataPath( 5464 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5465 result.add(ephemeralInstaller); 5466 } 5467 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5468 } 5469 if (sortResult) { 5470 Collections.sort(result, mResolvePrioritySorter); 5471 } 5472 return result; 5473 } 5474 5475 private static class CrossProfileDomainInfo { 5476 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5477 ResolveInfo resolveInfo; 5478 /* Best domain verification status of the activities found in the other profile */ 5479 int bestDomainVerificationStatus; 5480 } 5481 5482 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5483 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5484 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5485 sourceUserId)) { 5486 return null; 5487 } 5488 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5489 resolvedType, flags, parentUserId); 5490 5491 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5492 return null; 5493 } 5494 CrossProfileDomainInfo result = null; 5495 int size = resultTargetUser.size(); 5496 for (int i = 0; i < size; i++) { 5497 ResolveInfo riTargetUser = resultTargetUser.get(i); 5498 // Intent filter verification is only for filters that specify a host. So don't return 5499 // those that handle all web uris. 5500 if (riTargetUser.handleAllWebDataURI) { 5501 continue; 5502 } 5503 String packageName = riTargetUser.activityInfo.packageName; 5504 PackageSetting ps = mSettings.mPackages.get(packageName); 5505 if (ps == null) { 5506 continue; 5507 } 5508 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5509 int status = (int)(verificationState >> 32); 5510 if (result == null) { 5511 result = new CrossProfileDomainInfo(); 5512 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5513 sourceUserId, parentUserId); 5514 result.bestDomainVerificationStatus = status; 5515 } else { 5516 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5517 result.bestDomainVerificationStatus); 5518 } 5519 } 5520 // Don't consider matches with status NEVER across profiles. 5521 if (result != null && result.bestDomainVerificationStatus 5522 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5523 return null; 5524 } 5525 return result; 5526 } 5527 5528 /** 5529 * Verification statuses are ordered from the worse to the best, except for 5530 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5531 */ 5532 private int bestDomainVerificationStatus(int status1, int status2) { 5533 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5534 return status2; 5535 } 5536 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5537 return status1; 5538 } 5539 return (int) MathUtils.max(status1, status2); 5540 } 5541 5542 private boolean isUserEnabled(int userId) { 5543 long callingId = Binder.clearCallingIdentity(); 5544 try { 5545 UserInfo userInfo = sUserManager.getUserInfo(userId); 5546 return userInfo != null && userInfo.isEnabled(); 5547 } finally { 5548 Binder.restoreCallingIdentity(callingId); 5549 } 5550 } 5551 5552 /** 5553 * Filter out activities with systemUserOnly flag set, when current user is not System. 5554 * 5555 * @return filtered list 5556 */ 5557 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5558 if (userId == UserHandle.USER_SYSTEM) { 5559 return resolveInfos; 5560 } 5561 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5562 ResolveInfo info = resolveInfos.get(i); 5563 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5564 resolveInfos.remove(i); 5565 } 5566 } 5567 return resolveInfos; 5568 } 5569 5570 /** 5571 * @param resolveInfos list of resolve infos in descending priority order 5572 * @return if the list contains a resolve info with non-negative priority 5573 */ 5574 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5575 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5576 } 5577 5578 private static boolean hasWebURI(Intent intent) { 5579 if (intent.getData() == null) { 5580 return false; 5581 } 5582 final String scheme = intent.getScheme(); 5583 if (TextUtils.isEmpty(scheme)) { 5584 return false; 5585 } 5586 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5587 } 5588 5589 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5590 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5591 int userId) { 5592 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5593 5594 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5595 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5596 candidates.size()); 5597 } 5598 5599 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5600 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5601 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5602 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5603 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5604 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5605 5606 synchronized (mPackages) { 5607 final int count = candidates.size(); 5608 // First, try to use linked apps. Partition the candidates into four lists: 5609 // one for the final results, one for the "do not use ever", one for "undefined status" 5610 // and finally one for "browser app type". 5611 for (int n=0; n<count; n++) { 5612 ResolveInfo info = candidates.get(n); 5613 String packageName = info.activityInfo.packageName; 5614 PackageSetting ps = mSettings.mPackages.get(packageName); 5615 if (ps != null) { 5616 // Add to the special match all list (Browser use case) 5617 if (info.handleAllWebDataURI) { 5618 matchAllList.add(info); 5619 continue; 5620 } 5621 // Try to get the status from User settings first 5622 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5623 int status = (int)(packedStatus >> 32); 5624 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5625 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5626 if (DEBUG_DOMAIN_VERIFICATION) { 5627 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5628 + " : linkgen=" + linkGeneration); 5629 } 5630 // Use link-enabled generation as preferredOrder, i.e. 5631 // prefer newly-enabled over earlier-enabled. 5632 info.preferredOrder = linkGeneration; 5633 alwaysList.add(info); 5634 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5635 if (DEBUG_DOMAIN_VERIFICATION) { 5636 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5637 } 5638 neverList.add(info); 5639 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5640 if (DEBUG_DOMAIN_VERIFICATION) { 5641 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5642 } 5643 alwaysAskList.add(info); 5644 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5645 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5646 if (DEBUG_DOMAIN_VERIFICATION) { 5647 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5648 } 5649 undefinedList.add(info); 5650 } 5651 } 5652 } 5653 5654 // We'll want to include browser possibilities in a few cases 5655 boolean includeBrowser = false; 5656 5657 // First try to add the "always" resolution(s) for the current user, if any 5658 if (alwaysList.size() > 0) { 5659 result.addAll(alwaysList); 5660 } else { 5661 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5662 result.addAll(undefinedList); 5663 // Maybe add one for the other profile. 5664 if (xpDomainInfo != null && ( 5665 xpDomainInfo.bestDomainVerificationStatus 5666 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5667 result.add(xpDomainInfo.resolveInfo); 5668 } 5669 includeBrowser = true; 5670 } 5671 5672 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5673 // If there were 'always' entries their preferred order has been set, so we also 5674 // back that off to make the alternatives equivalent 5675 if (alwaysAskList.size() > 0) { 5676 for (ResolveInfo i : result) { 5677 i.preferredOrder = 0; 5678 } 5679 result.addAll(alwaysAskList); 5680 includeBrowser = true; 5681 } 5682 5683 if (includeBrowser) { 5684 // Also add browsers (all of them or only the default one) 5685 if (DEBUG_DOMAIN_VERIFICATION) { 5686 Slog.v(TAG, " ...including browsers in candidate set"); 5687 } 5688 if ((matchFlags & MATCH_ALL) != 0) { 5689 result.addAll(matchAllList); 5690 } else { 5691 // Browser/generic handling case. If there's a default browser, go straight 5692 // to that (but only if there is no other higher-priority match). 5693 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5694 int maxMatchPrio = 0; 5695 ResolveInfo defaultBrowserMatch = null; 5696 final int numCandidates = matchAllList.size(); 5697 for (int n = 0; n < numCandidates; n++) { 5698 ResolveInfo info = matchAllList.get(n); 5699 // track the highest overall match priority... 5700 if (info.priority > maxMatchPrio) { 5701 maxMatchPrio = info.priority; 5702 } 5703 // ...and the highest-priority default browser match 5704 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5705 if (defaultBrowserMatch == null 5706 || (defaultBrowserMatch.priority < info.priority)) { 5707 if (debug) { 5708 Slog.v(TAG, "Considering default browser match " + info); 5709 } 5710 defaultBrowserMatch = info; 5711 } 5712 } 5713 } 5714 if (defaultBrowserMatch != null 5715 && defaultBrowserMatch.priority >= maxMatchPrio 5716 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5717 { 5718 if (debug) { 5719 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5720 } 5721 result.add(defaultBrowserMatch); 5722 } else { 5723 result.addAll(matchAllList); 5724 } 5725 } 5726 5727 // If there is nothing selected, add all candidates and remove the ones that the user 5728 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5729 if (result.size() == 0) { 5730 result.addAll(candidates); 5731 result.removeAll(neverList); 5732 } 5733 } 5734 } 5735 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5736 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5737 result.size()); 5738 for (ResolveInfo info : result) { 5739 Slog.v(TAG, " + " + info.activityInfo); 5740 } 5741 } 5742 return result; 5743 } 5744 5745 // Returns a packed value as a long: 5746 // 5747 // high 'int'-sized word: link status: undefined/ask/never/always. 5748 // low 'int'-sized word: relative priority among 'always' results. 5749 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5750 long result = ps.getDomainVerificationStatusForUser(userId); 5751 // if none available, get the master status 5752 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5753 if (ps.getIntentFilterVerificationInfo() != null) { 5754 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5755 } 5756 } 5757 return result; 5758 } 5759 5760 private ResolveInfo querySkipCurrentProfileIntents( 5761 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5762 int flags, int sourceUserId) { 5763 if (matchingFilters != null) { 5764 int size = matchingFilters.size(); 5765 for (int i = 0; i < size; i ++) { 5766 CrossProfileIntentFilter filter = matchingFilters.get(i); 5767 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5768 // Checking if there are activities in the target user that can handle the 5769 // intent. 5770 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5771 resolvedType, flags, sourceUserId); 5772 if (resolveInfo != null) { 5773 return resolveInfo; 5774 } 5775 } 5776 } 5777 } 5778 return null; 5779 } 5780 5781 // Return matching ResolveInfo in target user if any. 5782 private ResolveInfo queryCrossProfileIntents( 5783 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5784 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5785 if (matchingFilters != null) { 5786 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5787 // match the same intent. For performance reasons, it is better not to 5788 // run queryIntent twice for the same userId 5789 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5790 int size = matchingFilters.size(); 5791 for (int i = 0; i < size; i++) { 5792 CrossProfileIntentFilter filter = matchingFilters.get(i); 5793 int targetUserId = filter.getTargetUserId(); 5794 boolean skipCurrentProfile = 5795 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5796 boolean skipCurrentProfileIfNoMatchFound = 5797 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5798 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5799 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5800 // Checking if there are activities in the target user that can handle the 5801 // intent. 5802 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5803 resolvedType, flags, sourceUserId); 5804 if (resolveInfo != null) return resolveInfo; 5805 alreadyTriedUserIds.put(targetUserId, true); 5806 } 5807 } 5808 } 5809 return null; 5810 } 5811 5812 /** 5813 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5814 * will forward the intent to the filter's target user. 5815 * Otherwise, returns null. 5816 */ 5817 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5818 String resolvedType, int flags, int sourceUserId) { 5819 int targetUserId = filter.getTargetUserId(); 5820 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5821 resolvedType, flags, targetUserId); 5822 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5823 // If all the matches in the target profile are suspended, return null. 5824 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5825 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5826 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5827 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5828 targetUserId); 5829 } 5830 } 5831 } 5832 return null; 5833 } 5834 5835 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5836 int sourceUserId, int targetUserId) { 5837 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5838 long ident = Binder.clearCallingIdentity(); 5839 boolean targetIsProfile; 5840 try { 5841 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5842 } finally { 5843 Binder.restoreCallingIdentity(ident); 5844 } 5845 String className; 5846 if (targetIsProfile) { 5847 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5848 } else { 5849 className = FORWARD_INTENT_TO_PARENT; 5850 } 5851 ComponentName forwardingActivityComponentName = new ComponentName( 5852 mAndroidApplication.packageName, className); 5853 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5854 sourceUserId); 5855 if (!targetIsProfile) { 5856 forwardingActivityInfo.showUserIcon = targetUserId; 5857 forwardingResolveInfo.noResourceId = true; 5858 } 5859 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5860 forwardingResolveInfo.priority = 0; 5861 forwardingResolveInfo.preferredOrder = 0; 5862 forwardingResolveInfo.match = 0; 5863 forwardingResolveInfo.isDefault = true; 5864 forwardingResolveInfo.filter = filter; 5865 forwardingResolveInfo.targetUserId = targetUserId; 5866 return forwardingResolveInfo; 5867 } 5868 5869 @Override 5870 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5871 Intent[] specifics, String[] specificTypes, Intent intent, 5872 String resolvedType, int flags, int userId) { 5873 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5874 specificTypes, intent, resolvedType, flags, userId)); 5875 } 5876 5877 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5878 Intent[] specifics, String[] specificTypes, Intent intent, 5879 String resolvedType, int flags, int userId) { 5880 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5881 flags = updateFlagsForResolve(flags, userId, intent); 5882 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5883 false /* requireFullPermission */, false /* checkShell */, 5884 "query intent activity options"); 5885 final String resultsAction = intent.getAction(); 5886 5887 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5888 | PackageManager.GET_RESOLVED_FILTER, userId); 5889 5890 if (DEBUG_INTENT_MATCHING) { 5891 Log.v(TAG, "Query " + intent + ": " + results); 5892 } 5893 5894 int specificsPos = 0; 5895 int N; 5896 5897 // todo: note that the algorithm used here is O(N^2). This 5898 // isn't a problem in our current environment, but if we start running 5899 // into situations where we have more than 5 or 10 matches then this 5900 // should probably be changed to something smarter... 5901 5902 // First we go through and resolve each of the specific items 5903 // that were supplied, taking care of removing any corresponding 5904 // duplicate items in the generic resolve list. 5905 if (specifics != null) { 5906 for (int i=0; i<specifics.length; i++) { 5907 final Intent sintent = specifics[i]; 5908 if (sintent == null) { 5909 continue; 5910 } 5911 5912 if (DEBUG_INTENT_MATCHING) { 5913 Log.v(TAG, "Specific #" + i + ": " + sintent); 5914 } 5915 5916 String action = sintent.getAction(); 5917 if (resultsAction != null && resultsAction.equals(action)) { 5918 // If this action was explicitly requested, then don't 5919 // remove things that have it. 5920 action = null; 5921 } 5922 5923 ResolveInfo ri = null; 5924 ActivityInfo ai = null; 5925 5926 ComponentName comp = sintent.getComponent(); 5927 if (comp == null) { 5928 ri = resolveIntent( 5929 sintent, 5930 specificTypes != null ? specificTypes[i] : null, 5931 flags, userId); 5932 if (ri == null) { 5933 continue; 5934 } 5935 if (ri == mResolveInfo) { 5936 // ACK! Must do something better with this. 5937 } 5938 ai = ri.activityInfo; 5939 comp = new ComponentName(ai.applicationInfo.packageName, 5940 ai.name); 5941 } else { 5942 ai = getActivityInfo(comp, flags, userId); 5943 if (ai == null) { 5944 continue; 5945 } 5946 } 5947 5948 // Look for any generic query activities that are duplicates 5949 // of this specific one, and remove them from the results. 5950 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5951 N = results.size(); 5952 int j; 5953 for (j=specificsPos; j<N; j++) { 5954 ResolveInfo sri = results.get(j); 5955 if ((sri.activityInfo.name.equals(comp.getClassName()) 5956 && sri.activityInfo.applicationInfo.packageName.equals( 5957 comp.getPackageName())) 5958 || (action != null && sri.filter.matchAction(action))) { 5959 results.remove(j); 5960 if (DEBUG_INTENT_MATCHING) Log.v( 5961 TAG, "Removing duplicate item from " + j 5962 + " due to specific " + specificsPos); 5963 if (ri == null) { 5964 ri = sri; 5965 } 5966 j--; 5967 N--; 5968 } 5969 } 5970 5971 // Add this specific item to its proper place. 5972 if (ri == null) { 5973 ri = new ResolveInfo(); 5974 ri.activityInfo = ai; 5975 } 5976 results.add(specificsPos, ri); 5977 ri.specificIndex = i; 5978 specificsPos++; 5979 } 5980 } 5981 5982 // Now we go through the remaining generic results and remove any 5983 // duplicate actions that are found here. 5984 N = results.size(); 5985 for (int i=specificsPos; i<N-1; i++) { 5986 final ResolveInfo rii = results.get(i); 5987 if (rii.filter == null) { 5988 continue; 5989 } 5990 5991 // Iterate over all of the actions of this result's intent 5992 // filter... typically this should be just one. 5993 final Iterator<String> it = rii.filter.actionsIterator(); 5994 if (it == null) { 5995 continue; 5996 } 5997 while (it.hasNext()) { 5998 final String action = it.next(); 5999 if (resultsAction != null && resultsAction.equals(action)) { 6000 // If this action was explicitly requested, then don't 6001 // remove things that have it. 6002 continue; 6003 } 6004 for (int j=i+1; j<N; j++) { 6005 final ResolveInfo rij = results.get(j); 6006 if (rij.filter != null && rij.filter.hasAction(action)) { 6007 results.remove(j); 6008 if (DEBUG_INTENT_MATCHING) Log.v( 6009 TAG, "Removing duplicate item from " + j 6010 + " due to action " + action + " at " + i); 6011 j--; 6012 N--; 6013 } 6014 } 6015 } 6016 6017 // If the caller didn't request filter information, drop it now 6018 // so we don't have to marshall/unmarshall it. 6019 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6020 rii.filter = null; 6021 } 6022 } 6023 6024 // Filter out the caller activity if so requested. 6025 if (caller != null) { 6026 N = results.size(); 6027 for (int i=0; i<N; i++) { 6028 ActivityInfo ainfo = results.get(i).activityInfo; 6029 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6030 && caller.getClassName().equals(ainfo.name)) { 6031 results.remove(i); 6032 break; 6033 } 6034 } 6035 } 6036 6037 // If the caller didn't request filter information, 6038 // drop them now so we don't have to 6039 // marshall/unmarshall it. 6040 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6041 N = results.size(); 6042 for (int i=0; i<N; i++) { 6043 results.get(i).filter = null; 6044 } 6045 } 6046 6047 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6048 return results; 6049 } 6050 6051 @Override 6052 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6053 String resolvedType, int flags, int userId) { 6054 return new ParceledListSlice<>( 6055 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6056 } 6057 6058 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6059 String resolvedType, int flags, int userId) { 6060 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6061 flags = updateFlagsForResolve(flags, userId, intent); 6062 ComponentName comp = intent.getComponent(); 6063 if (comp == null) { 6064 if (intent.getSelector() != null) { 6065 intent = intent.getSelector(); 6066 comp = intent.getComponent(); 6067 } 6068 } 6069 if (comp != null) { 6070 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6071 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6072 if (ai != null) { 6073 ResolveInfo ri = new ResolveInfo(); 6074 ri.activityInfo = ai; 6075 list.add(ri); 6076 } 6077 return list; 6078 } 6079 6080 // reader 6081 synchronized (mPackages) { 6082 String pkgName = intent.getPackage(); 6083 if (pkgName == null) { 6084 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6085 } 6086 final PackageParser.Package pkg = mPackages.get(pkgName); 6087 if (pkg != null) { 6088 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6089 userId); 6090 } 6091 return Collections.emptyList(); 6092 } 6093 } 6094 6095 @Override 6096 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6097 if (!sUserManager.exists(userId)) return null; 6098 flags = updateFlagsForResolve(flags, userId, intent); 6099 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6100 if (query != null) { 6101 if (query.size() >= 1) { 6102 // If there is more than one service with the same priority, 6103 // just arbitrarily pick the first one. 6104 return query.get(0); 6105 } 6106 } 6107 return null; 6108 } 6109 6110 @Override 6111 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6112 String resolvedType, int flags, int userId) { 6113 return new ParceledListSlice<>( 6114 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6115 } 6116 6117 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6118 String resolvedType, int flags, int userId) { 6119 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6120 flags = updateFlagsForResolve(flags, userId, intent); 6121 ComponentName comp = intent.getComponent(); 6122 if (comp == null) { 6123 if (intent.getSelector() != null) { 6124 intent = intent.getSelector(); 6125 comp = intent.getComponent(); 6126 } 6127 } 6128 if (comp != null) { 6129 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6130 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6131 if (si != null) { 6132 final ResolveInfo ri = new ResolveInfo(); 6133 ri.serviceInfo = si; 6134 list.add(ri); 6135 } 6136 return list; 6137 } 6138 6139 // reader 6140 synchronized (mPackages) { 6141 String pkgName = intent.getPackage(); 6142 if (pkgName == null) { 6143 return mServices.queryIntent(intent, resolvedType, flags, userId); 6144 } 6145 final PackageParser.Package pkg = mPackages.get(pkgName); 6146 if (pkg != null) { 6147 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6148 userId); 6149 } 6150 return Collections.emptyList(); 6151 } 6152 } 6153 6154 @Override 6155 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6156 String resolvedType, int flags, int userId) { 6157 return new ParceledListSlice<>( 6158 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6159 } 6160 6161 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6162 Intent intent, String resolvedType, int flags, int userId) { 6163 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6164 flags = updateFlagsForResolve(flags, userId, intent); 6165 ComponentName comp = intent.getComponent(); 6166 if (comp == null) { 6167 if (intent.getSelector() != null) { 6168 intent = intent.getSelector(); 6169 comp = intent.getComponent(); 6170 } 6171 } 6172 if (comp != null) { 6173 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6174 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6175 if (pi != null) { 6176 final ResolveInfo ri = new ResolveInfo(); 6177 ri.providerInfo = pi; 6178 list.add(ri); 6179 } 6180 return list; 6181 } 6182 6183 // reader 6184 synchronized (mPackages) { 6185 String pkgName = intent.getPackage(); 6186 if (pkgName == null) { 6187 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6188 } 6189 final PackageParser.Package pkg = mPackages.get(pkgName); 6190 if (pkg != null) { 6191 return mProviders.queryIntentForPackage( 6192 intent, resolvedType, flags, pkg.providers, userId); 6193 } 6194 return Collections.emptyList(); 6195 } 6196 } 6197 6198 @Override 6199 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6200 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6201 flags = updateFlagsForPackage(flags, userId, null); 6202 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6203 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6204 true /* requireFullPermission */, false /* checkShell */, 6205 "get installed packages"); 6206 6207 // writer 6208 synchronized (mPackages) { 6209 ArrayList<PackageInfo> list; 6210 if (listUninstalled) { 6211 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6212 for (PackageSetting ps : mSettings.mPackages.values()) { 6213 final PackageInfo pi; 6214 if (ps.pkg != null) { 6215 pi = generatePackageInfo(ps, flags, userId); 6216 } else { 6217 pi = generatePackageInfo(ps, flags, userId); 6218 } 6219 if (pi != null) { 6220 list.add(pi); 6221 } 6222 } 6223 } else { 6224 list = new ArrayList<PackageInfo>(mPackages.size()); 6225 for (PackageParser.Package p : mPackages.values()) { 6226 final PackageInfo pi = 6227 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6228 if (pi != null) { 6229 list.add(pi); 6230 } 6231 } 6232 } 6233 6234 return new ParceledListSlice<PackageInfo>(list); 6235 } 6236 } 6237 6238 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6239 String[] permissions, boolean[] tmp, int flags, int userId) { 6240 int numMatch = 0; 6241 final PermissionsState permissionsState = ps.getPermissionsState(); 6242 for (int i=0; i<permissions.length; i++) { 6243 final String permission = permissions[i]; 6244 if (permissionsState.hasPermission(permission, userId)) { 6245 tmp[i] = true; 6246 numMatch++; 6247 } else { 6248 tmp[i] = false; 6249 } 6250 } 6251 if (numMatch == 0) { 6252 return; 6253 } 6254 final PackageInfo pi; 6255 if (ps.pkg != null) { 6256 pi = generatePackageInfo(ps, flags, userId); 6257 } else { 6258 pi = generatePackageInfo(ps, flags, userId); 6259 } 6260 // The above might return null in cases of uninstalled apps or install-state 6261 // skew across users/profiles. 6262 if (pi != null) { 6263 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6264 if (numMatch == permissions.length) { 6265 pi.requestedPermissions = permissions; 6266 } else { 6267 pi.requestedPermissions = new String[numMatch]; 6268 numMatch = 0; 6269 for (int i=0; i<permissions.length; i++) { 6270 if (tmp[i]) { 6271 pi.requestedPermissions[numMatch] = permissions[i]; 6272 numMatch++; 6273 } 6274 } 6275 } 6276 } 6277 list.add(pi); 6278 } 6279 } 6280 6281 @Override 6282 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6283 String[] permissions, int flags, int userId) { 6284 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6285 flags = updateFlagsForPackage(flags, userId, permissions); 6286 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6287 6288 // writer 6289 synchronized (mPackages) { 6290 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6291 boolean[] tmpBools = new boolean[permissions.length]; 6292 if (listUninstalled) { 6293 for (PackageSetting ps : mSettings.mPackages.values()) { 6294 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6295 } 6296 } else { 6297 for (PackageParser.Package pkg : mPackages.values()) { 6298 PackageSetting ps = (PackageSetting)pkg.mExtras; 6299 if (ps != null) { 6300 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6301 userId); 6302 } 6303 } 6304 } 6305 6306 return new ParceledListSlice<PackageInfo>(list); 6307 } 6308 } 6309 6310 @Override 6311 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6312 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6313 flags = updateFlagsForApplication(flags, userId, null); 6314 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6315 6316 // writer 6317 synchronized (mPackages) { 6318 ArrayList<ApplicationInfo> list; 6319 if (listUninstalled) { 6320 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6321 for (PackageSetting ps : mSettings.mPackages.values()) { 6322 ApplicationInfo ai; 6323 if (ps.pkg != null) { 6324 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6325 ps.readUserState(userId), userId); 6326 } else { 6327 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6328 } 6329 if (ai != null) { 6330 list.add(ai); 6331 } 6332 } 6333 } else { 6334 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6335 for (PackageParser.Package p : mPackages.values()) { 6336 if (p.mExtras != null) { 6337 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6338 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6339 if (ai != null) { 6340 list.add(ai); 6341 } 6342 } 6343 } 6344 } 6345 6346 return new ParceledListSlice<ApplicationInfo>(list); 6347 } 6348 } 6349 6350 @Override 6351 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6352 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6353 return null; 6354 } 6355 6356 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6357 "getEphemeralApplications"); 6358 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6359 true /* requireFullPermission */, false /* checkShell */, 6360 "getEphemeralApplications"); 6361 synchronized (mPackages) { 6362 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6363 .getEphemeralApplicationsLPw(userId); 6364 if (ephemeralApps != null) { 6365 return new ParceledListSlice<>(ephemeralApps); 6366 } 6367 } 6368 return null; 6369 } 6370 6371 @Override 6372 public boolean isEphemeralApplication(String packageName, int userId) { 6373 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6374 true /* requireFullPermission */, false /* checkShell */, 6375 "isEphemeral"); 6376 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6377 return false; 6378 } 6379 6380 if (!isCallerSameApp(packageName)) { 6381 return false; 6382 } 6383 synchronized (mPackages) { 6384 PackageParser.Package pkg = mPackages.get(packageName); 6385 if (pkg != null) { 6386 return pkg.applicationInfo.isEphemeralApp(); 6387 } 6388 } 6389 return false; 6390 } 6391 6392 @Override 6393 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6394 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6395 return null; 6396 } 6397 6398 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6399 true /* requireFullPermission */, false /* checkShell */, 6400 "getCookie"); 6401 if (!isCallerSameApp(packageName)) { 6402 return null; 6403 } 6404 synchronized (mPackages) { 6405 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6406 packageName, userId); 6407 } 6408 } 6409 6410 @Override 6411 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6412 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6413 return true; 6414 } 6415 6416 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6417 true /* requireFullPermission */, true /* checkShell */, 6418 "setCookie"); 6419 if (!isCallerSameApp(packageName)) { 6420 return false; 6421 } 6422 synchronized (mPackages) { 6423 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6424 packageName, cookie, userId); 6425 } 6426 } 6427 6428 @Override 6429 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6430 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6431 return null; 6432 } 6433 6434 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6435 "getEphemeralApplicationIcon"); 6436 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6437 true /* requireFullPermission */, false /* checkShell */, 6438 "getEphemeralApplicationIcon"); 6439 synchronized (mPackages) { 6440 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6441 packageName, userId); 6442 } 6443 } 6444 6445 private boolean isCallerSameApp(String packageName) { 6446 PackageParser.Package pkg = mPackages.get(packageName); 6447 return pkg != null 6448 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6449 } 6450 6451 @Override 6452 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6453 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6454 } 6455 6456 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6457 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6458 6459 // reader 6460 synchronized (mPackages) { 6461 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6462 final int userId = UserHandle.getCallingUserId(); 6463 while (i.hasNext()) { 6464 final PackageParser.Package p = i.next(); 6465 if (p.applicationInfo == null) continue; 6466 6467 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6468 && !p.applicationInfo.isDirectBootAware(); 6469 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6470 && p.applicationInfo.isDirectBootAware(); 6471 6472 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6473 && (!mSafeMode || isSystemApp(p)) 6474 && (matchesUnaware || matchesAware)) { 6475 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6476 if (ps != null) { 6477 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6478 ps.readUserState(userId), userId); 6479 if (ai != null) { 6480 finalList.add(ai); 6481 } 6482 } 6483 } 6484 } 6485 } 6486 6487 return finalList; 6488 } 6489 6490 @Override 6491 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6492 if (!sUserManager.exists(userId)) return null; 6493 flags = updateFlagsForComponent(flags, userId, name); 6494 // reader 6495 synchronized (mPackages) { 6496 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6497 PackageSetting ps = provider != null 6498 ? mSettings.mPackages.get(provider.owner.packageName) 6499 : null; 6500 return ps != null 6501 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6502 ? PackageParser.generateProviderInfo(provider, flags, 6503 ps.readUserState(userId), userId) 6504 : null; 6505 } 6506 } 6507 6508 /** 6509 * @deprecated 6510 */ 6511 @Deprecated 6512 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6513 // reader 6514 synchronized (mPackages) { 6515 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6516 .entrySet().iterator(); 6517 final int userId = UserHandle.getCallingUserId(); 6518 while (i.hasNext()) { 6519 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6520 PackageParser.Provider p = entry.getValue(); 6521 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6522 6523 if (ps != null && p.syncable 6524 && (!mSafeMode || (p.info.applicationInfo.flags 6525 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6526 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6527 ps.readUserState(userId), userId); 6528 if (info != null) { 6529 outNames.add(entry.getKey()); 6530 outInfo.add(info); 6531 } 6532 } 6533 } 6534 } 6535 } 6536 6537 @Override 6538 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6539 int uid, int flags) { 6540 final int userId = processName != null ? UserHandle.getUserId(uid) 6541 : UserHandle.getCallingUserId(); 6542 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6543 flags = updateFlagsForComponent(flags, userId, processName); 6544 6545 ArrayList<ProviderInfo> finalList = null; 6546 // reader 6547 synchronized (mPackages) { 6548 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6549 while (i.hasNext()) { 6550 final PackageParser.Provider p = i.next(); 6551 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6552 if (ps != null && p.info.authority != null 6553 && (processName == null 6554 || (p.info.processName.equals(processName) 6555 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6556 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6557 if (finalList == null) { 6558 finalList = new ArrayList<ProviderInfo>(3); 6559 } 6560 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6561 ps.readUserState(userId), userId); 6562 if (info != null) { 6563 finalList.add(info); 6564 } 6565 } 6566 } 6567 } 6568 6569 if (finalList != null) { 6570 Collections.sort(finalList, mProviderInitOrderSorter); 6571 return new ParceledListSlice<ProviderInfo>(finalList); 6572 } 6573 6574 return ParceledListSlice.emptyList(); 6575 } 6576 6577 @Override 6578 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6579 // reader 6580 synchronized (mPackages) { 6581 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6582 return PackageParser.generateInstrumentationInfo(i, flags); 6583 } 6584 } 6585 6586 @Override 6587 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6588 String targetPackage, int flags) { 6589 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6590 } 6591 6592 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6593 int flags) { 6594 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6595 6596 // reader 6597 synchronized (mPackages) { 6598 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6599 while (i.hasNext()) { 6600 final PackageParser.Instrumentation p = i.next(); 6601 if (targetPackage == null 6602 || targetPackage.equals(p.info.targetPackage)) { 6603 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6604 flags); 6605 if (ii != null) { 6606 finalList.add(ii); 6607 } 6608 } 6609 } 6610 } 6611 6612 return finalList; 6613 } 6614 6615 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6616 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6617 if (overlays == null) { 6618 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6619 return; 6620 } 6621 for (PackageParser.Package opkg : overlays.values()) { 6622 // Not much to do if idmap fails: we already logged the error 6623 // and we certainly don't want to abort installation of pkg simply 6624 // because an overlay didn't fit properly. For these reasons, 6625 // ignore the return value of createIdmapForPackagePairLI. 6626 createIdmapForPackagePairLI(pkg, opkg); 6627 } 6628 } 6629 6630 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6631 PackageParser.Package opkg) { 6632 if (!opkg.mTrustedOverlay) { 6633 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6634 opkg.baseCodePath + ": overlay not trusted"); 6635 return false; 6636 } 6637 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6638 if (overlaySet == null) { 6639 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6640 opkg.baseCodePath + " but target package has no known overlays"); 6641 return false; 6642 } 6643 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6644 // TODO: generate idmap for split APKs 6645 try { 6646 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6647 } catch (InstallerException e) { 6648 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6649 + opkg.baseCodePath); 6650 return false; 6651 } 6652 PackageParser.Package[] overlayArray = 6653 overlaySet.values().toArray(new PackageParser.Package[0]); 6654 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6655 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6656 return p1.mOverlayPriority - p2.mOverlayPriority; 6657 } 6658 }; 6659 Arrays.sort(overlayArray, cmp); 6660 6661 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6662 int i = 0; 6663 for (PackageParser.Package p : overlayArray) { 6664 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6665 } 6666 return true; 6667 } 6668 6669 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6670 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6671 try { 6672 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6673 } finally { 6674 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6675 } 6676 } 6677 6678 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6679 final File[] files = dir.listFiles(); 6680 if (ArrayUtils.isEmpty(files)) { 6681 Log.d(TAG, "No files in app dir " + dir); 6682 return; 6683 } 6684 6685 if (DEBUG_PACKAGE_SCANNING) { 6686 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6687 + " flags=0x" + Integer.toHexString(parseFlags)); 6688 } 6689 6690 for (File file : files) { 6691 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6692 && !PackageInstallerService.isStageName(file.getName()); 6693 if (!isPackage) { 6694 // Ignore entries which are not packages 6695 continue; 6696 } 6697 try { 6698 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6699 scanFlags, currentTime, null); 6700 } catch (PackageManagerException e) { 6701 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6702 6703 // Delete invalid userdata apps 6704 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6705 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6706 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6707 removeCodePathLI(file); 6708 } 6709 } 6710 } 6711 } 6712 6713 private static File getSettingsProblemFile() { 6714 File dataDir = Environment.getDataDirectory(); 6715 File systemDir = new File(dataDir, "system"); 6716 File fname = new File(systemDir, "uiderrors.txt"); 6717 return fname; 6718 } 6719 6720 static void reportSettingsProblem(int priority, String msg) { 6721 logCriticalInfo(priority, msg); 6722 } 6723 6724 static void logCriticalInfo(int priority, String msg) { 6725 Slog.println(priority, TAG, msg); 6726 EventLogTags.writePmCriticalInfo(msg); 6727 try { 6728 File fname = getSettingsProblemFile(); 6729 FileOutputStream out = new FileOutputStream(fname, true); 6730 PrintWriter pw = new FastPrintWriter(out); 6731 SimpleDateFormat formatter = new SimpleDateFormat(); 6732 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6733 pw.println(dateString + ": " + msg); 6734 pw.close(); 6735 FileUtils.setPermissions( 6736 fname.toString(), 6737 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6738 -1, -1); 6739 } catch (java.io.IOException e) { 6740 } 6741 } 6742 6743 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6744 if (srcFile.isDirectory()) { 6745 final File baseFile = new File(pkg.baseCodePath); 6746 long maxModifiedTime = baseFile.lastModified(); 6747 if (pkg.splitCodePaths != null) { 6748 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6749 final File splitFile = new File(pkg.splitCodePaths[i]); 6750 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6751 } 6752 } 6753 return maxModifiedTime; 6754 } 6755 return srcFile.lastModified(); 6756 } 6757 6758 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6759 final int policyFlags) throws PackageManagerException { 6760 // When upgrading from pre-N MR1, verify the package time stamp using the package 6761 // directory and not the APK file. 6762 final long lastModifiedTime = mIsPreNMR1Upgrade 6763 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 6764 if (ps != null 6765 && ps.codePath.equals(srcFile) 6766 && ps.timeStamp == lastModifiedTime 6767 && !isCompatSignatureUpdateNeeded(pkg) 6768 && !isRecoverSignatureUpdateNeeded(pkg)) { 6769 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6770 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6771 ArraySet<PublicKey> signingKs; 6772 synchronized (mPackages) { 6773 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6774 } 6775 if (ps.signatures.mSignatures != null 6776 && ps.signatures.mSignatures.length != 0 6777 && signingKs != null) { 6778 // Optimization: reuse the existing cached certificates 6779 // if the package appears to be unchanged. 6780 pkg.mSignatures = ps.signatures.mSignatures; 6781 pkg.mSigningKeys = signingKs; 6782 return; 6783 } 6784 6785 Slog.w(TAG, "PackageSetting for " + ps.name 6786 + " is missing signatures. Collecting certs again to recover them."); 6787 } else { 6788 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 6789 } 6790 6791 try { 6792 PackageParser.collectCertificates(pkg, policyFlags); 6793 } catch (PackageParserException e) { 6794 throw PackageManagerException.from(e); 6795 } 6796 } 6797 6798 /** 6799 * Traces a package scan. 6800 * @see #scanPackageLI(File, int, int, long, UserHandle) 6801 */ 6802 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6803 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6804 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6805 try { 6806 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6807 } finally { 6808 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6809 } 6810 } 6811 6812 /** 6813 * Scans a package and returns the newly parsed package. 6814 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6815 */ 6816 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6817 long currentTime, UserHandle user) throws PackageManagerException { 6818 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6819 PackageParser pp = new PackageParser(); 6820 pp.setSeparateProcesses(mSeparateProcesses); 6821 pp.setOnlyCoreApps(mOnlyCore); 6822 pp.setDisplayMetrics(mMetrics); 6823 6824 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6825 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6826 } 6827 6828 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6829 final PackageParser.Package pkg; 6830 try { 6831 pkg = pp.parsePackage(scanFile, parseFlags); 6832 } catch (PackageParserException e) { 6833 throw PackageManagerException.from(e); 6834 } finally { 6835 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6836 } 6837 6838 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6839 } 6840 6841 /** 6842 * Scans a package and returns the newly parsed package. 6843 * @throws PackageManagerException on a parse error. 6844 */ 6845 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6846 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6847 throws PackageManagerException { 6848 // If the package has children and this is the first dive in the function 6849 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6850 // packages (parent and children) would be successfully scanned before the 6851 // actual scan since scanning mutates internal state and we want to atomically 6852 // install the package and its children. 6853 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6854 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6855 scanFlags |= SCAN_CHECK_ONLY; 6856 } 6857 } else { 6858 scanFlags &= ~SCAN_CHECK_ONLY; 6859 } 6860 6861 // Scan the parent 6862 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6863 scanFlags, currentTime, user); 6864 6865 // Scan the children 6866 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6867 for (int i = 0; i < childCount; i++) { 6868 PackageParser.Package childPackage = pkg.childPackages.get(i); 6869 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6870 currentTime, user); 6871 } 6872 6873 6874 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6875 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6876 } 6877 6878 return scannedPkg; 6879 } 6880 6881 /** 6882 * Scans a package and returns the newly parsed package. 6883 * @throws PackageManagerException on a parse error. 6884 */ 6885 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6886 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6887 throws PackageManagerException { 6888 PackageSetting ps = null; 6889 PackageSetting updatedPkg; 6890 // reader 6891 synchronized (mPackages) { 6892 // Look to see if we already know about this package. 6893 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6894 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6895 // This package has been renamed to its original name. Let's 6896 // use that. 6897 ps = mSettings.peekPackageLPr(oldName); 6898 } 6899 // If there was no original package, see one for the real package name. 6900 if (ps == null) { 6901 ps = mSettings.peekPackageLPr(pkg.packageName); 6902 } 6903 // Check to see if this package could be hiding/updating a system 6904 // package. Must look for it either under the original or real 6905 // package name depending on our state. 6906 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6907 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6908 6909 // If this is a package we don't know about on the system partition, we 6910 // may need to remove disabled child packages on the system partition 6911 // or may need to not add child packages if the parent apk is updated 6912 // on the data partition and no longer defines this child package. 6913 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6914 // If this is a parent package for an updated system app and this system 6915 // app got an OTA update which no longer defines some of the child packages 6916 // we have to prune them from the disabled system packages. 6917 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6918 if (disabledPs != null) { 6919 final int scannedChildCount = (pkg.childPackages != null) 6920 ? pkg.childPackages.size() : 0; 6921 final int disabledChildCount = disabledPs.childPackageNames != null 6922 ? disabledPs.childPackageNames.size() : 0; 6923 for (int i = 0; i < disabledChildCount; i++) { 6924 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6925 boolean disabledPackageAvailable = false; 6926 for (int j = 0; j < scannedChildCount; j++) { 6927 PackageParser.Package childPkg = pkg.childPackages.get(j); 6928 if (childPkg.packageName.equals(disabledChildPackageName)) { 6929 disabledPackageAvailable = true; 6930 break; 6931 } 6932 } 6933 if (!disabledPackageAvailable) { 6934 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6935 } 6936 } 6937 } 6938 } 6939 } 6940 6941 boolean updatedPkgBetter = false; 6942 // First check if this is a system package that may involve an update 6943 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6944 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6945 // it needs to drop FLAG_PRIVILEGED. 6946 if (locationIsPrivileged(scanFile)) { 6947 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6948 } else { 6949 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6950 } 6951 6952 if (ps != null && !ps.codePath.equals(scanFile)) { 6953 // The path has changed from what was last scanned... check the 6954 // version of the new path against what we have stored to determine 6955 // what to do. 6956 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6957 if (pkg.mVersionCode <= ps.versionCode) { 6958 // The system package has been updated and the code path does not match 6959 // Ignore entry. Skip it. 6960 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6961 + " ignored: updated version " + ps.versionCode 6962 + " better than this " + pkg.mVersionCode); 6963 if (!updatedPkg.codePath.equals(scanFile)) { 6964 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6965 + ps.name + " changing from " + updatedPkg.codePathString 6966 + " to " + scanFile); 6967 updatedPkg.codePath = scanFile; 6968 updatedPkg.codePathString = scanFile.toString(); 6969 updatedPkg.resourcePath = scanFile; 6970 updatedPkg.resourcePathString = scanFile.toString(); 6971 } 6972 updatedPkg.pkg = pkg; 6973 updatedPkg.versionCode = pkg.mVersionCode; 6974 6975 // Update the disabled system child packages to point to the package too. 6976 final int childCount = updatedPkg.childPackageNames != null 6977 ? updatedPkg.childPackageNames.size() : 0; 6978 for (int i = 0; i < childCount; i++) { 6979 String childPackageName = updatedPkg.childPackageNames.get(i); 6980 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6981 childPackageName); 6982 if (updatedChildPkg != null) { 6983 updatedChildPkg.pkg = pkg; 6984 updatedChildPkg.versionCode = pkg.mVersionCode; 6985 } 6986 } 6987 6988 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6989 + scanFile + " ignored: updated version " + ps.versionCode 6990 + " better than this " + pkg.mVersionCode); 6991 } else { 6992 // The current app on the system partition is better than 6993 // what we have updated to on the data partition; switch 6994 // back to the system partition version. 6995 // At this point, its safely assumed that package installation for 6996 // apps in system partition will go through. If not there won't be a working 6997 // version of the app 6998 // writer 6999 synchronized (mPackages) { 7000 // Just remove the loaded entries from package lists. 7001 mPackages.remove(ps.name); 7002 } 7003 7004 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7005 + " reverting from " + ps.codePathString 7006 + ": new version " + pkg.mVersionCode 7007 + " better than installed " + ps.versionCode); 7008 7009 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7010 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7011 synchronized (mInstallLock) { 7012 args.cleanUpResourcesLI(); 7013 } 7014 synchronized (mPackages) { 7015 mSettings.enableSystemPackageLPw(ps.name); 7016 } 7017 updatedPkgBetter = true; 7018 } 7019 } 7020 } 7021 7022 if (updatedPkg != null) { 7023 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7024 // initially 7025 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7026 7027 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7028 // flag set initially 7029 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7030 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7031 } 7032 } 7033 7034 // Verify certificates against what was last scanned 7035 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7036 7037 /* 7038 * A new system app appeared, but we already had a non-system one of the 7039 * same name installed earlier. 7040 */ 7041 boolean shouldHideSystemApp = false; 7042 if (updatedPkg == null && ps != null 7043 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7044 /* 7045 * Check to make sure the signatures match first. If they don't, 7046 * wipe the installed application and its data. 7047 */ 7048 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7049 != PackageManager.SIGNATURE_MATCH) { 7050 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7051 + " signatures don't match existing userdata copy; removing"); 7052 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7053 "scanPackageInternalLI")) { 7054 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7055 } 7056 ps = null; 7057 } else { 7058 /* 7059 * If the newly-added system app is an older version than the 7060 * already installed version, hide it. It will be scanned later 7061 * and re-added like an update. 7062 */ 7063 if (pkg.mVersionCode <= ps.versionCode) { 7064 shouldHideSystemApp = true; 7065 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7066 + " but new version " + pkg.mVersionCode + " better than installed " 7067 + ps.versionCode + "; hiding system"); 7068 } else { 7069 /* 7070 * The newly found system app is a newer version that the 7071 * one previously installed. Simply remove the 7072 * already-installed application and replace it with our own 7073 * while keeping the application data. 7074 */ 7075 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7076 + " reverting from " + ps.codePathString + ": new version " 7077 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7078 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7079 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7080 synchronized (mInstallLock) { 7081 args.cleanUpResourcesLI(); 7082 } 7083 } 7084 } 7085 } 7086 7087 // The apk is forward locked (not public) if its code and resources 7088 // are kept in different files. (except for app in either system or 7089 // vendor path). 7090 // TODO grab this value from PackageSettings 7091 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7092 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7093 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7094 } 7095 } 7096 7097 // TODO: extend to support forward-locked splits 7098 String resourcePath = null; 7099 String baseResourcePath = null; 7100 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7101 if (ps != null && ps.resourcePathString != null) { 7102 resourcePath = ps.resourcePathString; 7103 baseResourcePath = ps.resourcePathString; 7104 } else { 7105 // Should not happen at all. Just log an error. 7106 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7107 } 7108 } else { 7109 resourcePath = pkg.codePath; 7110 baseResourcePath = pkg.baseCodePath; 7111 } 7112 7113 // Set application objects path explicitly. 7114 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7115 pkg.setApplicationInfoCodePath(pkg.codePath); 7116 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7117 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7118 pkg.setApplicationInfoResourcePath(resourcePath); 7119 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7120 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7121 7122 // Note that we invoke the following method only if we are about to unpack an application 7123 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7124 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7125 7126 /* 7127 * If the system app should be overridden by a previously installed 7128 * data, hide the system app now and let the /data/app scan pick it up 7129 * again. 7130 */ 7131 if (shouldHideSystemApp) { 7132 synchronized (mPackages) { 7133 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7134 } 7135 } 7136 7137 return scannedPkg; 7138 } 7139 7140 private static String fixProcessName(String defProcessName, 7141 String processName, int uid) { 7142 if (processName == null) { 7143 return defProcessName; 7144 } 7145 return processName; 7146 } 7147 7148 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7149 throws PackageManagerException { 7150 if (pkgSetting.signatures.mSignatures != null) { 7151 // Already existing package. Make sure signatures match 7152 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7153 == PackageManager.SIGNATURE_MATCH; 7154 if (!match) { 7155 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7156 == PackageManager.SIGNATURE_MATCH; 7157 } 7158 if (!match) { 7159 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7160 == PackageManager.SIGNATURE_MATCH; 7161 } 7162 if (!match) { 7163 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7164 + pkg.packageName + " signatures do not match the " 7165 + "previously installed version; ignoring!"); 7166 } 7167 } 7168 7169 // Check for shared user signatures 7170 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7171 // Already existing package. Make sure signatures match 7172 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7173 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7174 if (!match) { 7175 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7176 == PackageManager.SIGNATURE_MATCH; 7177 } 7178 if (!match) { 7179 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7180 == PackageManager.SIGNATURE_MATCH; 7181 } 7182 if (!match) { 7183 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7184 "Package " + pkg.packageName 7185 + " has no signatures that match those in shared user " 7186 + pkgSetting.sharedUser.name + "; ignoring!"); 7187 } 7188 } 7189 } 7190 7191 /** 7192 * Enforces that only the system UID or root's UID can call a method exposed 7193 * via Binder. 7194 * 7195 * @param message used as message if SecurityException is thrown 7196 * @throws SecurityException if the caller is not system or root 7197 */ 7198 private static final void enforceSystemOrRoot(String message) { 7199 final int uid = Binder.getCallingUid(); 7200 if (uid != Process.SYSTEM_UID && uid != 0) { 7201 throw new SecurityException(message); 7202 } 7203 } 7204 7205 @Override 7206 public void performFstrimIfNeeded() { 7207 enforceSystemOrRoot("Only the system can request fstrim"); 7208 7209 // Before everything else, see whether we need to fstrim. 7210 try { 7211 IMountService ms = PackageHelper.getMountService(); 7212 if (ms != null) { 7213 boolean doTrim = false; 7214 final long interval = android.provider.Settings.Global.getLong( 7215 mContext.getContentResolver(), 7216 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7217 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7218 if (interval > 0) { 7219 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7220 if (timeSinceLast > interval) { 7221 doTrim = true; 7222 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7223 + "; running immediately"); 7224 } 7225 } 7226 if (doTrim) { 7227 final boolean dexOptDialogShown; 7228 synchronized (mPackages) { 7229 dexOptDialogShown = mDexOptDialogShown; 7230 } 7231 if (!isFirstBoot() && dexOptDialogShown) { 7232 try { 7233 ActivityManagerNative.getDefault().showBootMessage( 7234 mContext.getResources().getString( 7235 R.string.android_upgrading_fstrim), true); 7236 } catch (RemoteException e) { 7237 } 7238 } 7239 ms.runMaintenance(); 7240 } 7241 } else { 7242 Slog.e(TAG, "Mount service unavailable!"); 7243 } 7244 } catch (RemoteException e) { 7245 // Can't happen; MountService is local 7246 } 7247 } 7248 7249 @Override 7250 public void updatePackagesIfNeeded() { 7251 enforceSystemOrRoot("Only the system can request package update"); 7252 7253 // We need to re-extract after an OTA. 7254 boolean causeUpgrade = isUpgrade(); 7255 7256 // First boot or factory reset. 7257 // Note: we also handle devices that are upgrading to N right now as if it is their 7258 // first boot, as they do not have profile data. 7259 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7260 7261 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7262 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7263 7264 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7265 return; 7266 } 7267 7268 List<PackageParser.Package> pkgs; 7269 synchronized (mPackages) { 7270 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7271 } 7272 7273 final long startTime = System.nanoTime(); 7274 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7275 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7276 7277 final int elapsedTimeSeconds = 7278 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7279 7280 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7281 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7282 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7283 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7284 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7285 } 7286 7287 /** 7288 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7289 * containing statistics about the invocation. The array consists of three elements, 7290 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7291 * and {@code numberOfPackagesFailed}. 7292 */ 7293 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7294 String compilerFilter) { 7295 7296 int numberOfPackagesVisited = 0; 7297 int numberOfPackagesOptimized = 0; 7298 int numberOfPackagesSkipped = 0; 7299 int numberOfPackagesFailed = 0; 7300 final int numberOfPackagesToDexopt = pkgs.size(); 7301 7302 for (PackageParser.Package pkg : pkgs) { 7303 numberOfPackagesVisited++; 7304 7305 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7306 if (DEBUG_DEXOPT) { 7307 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7308 } 7309 numberOfPackagesSkipped++; 7310 continue; 7311 } 7312 7313 if (DEBUG_DEXOPT) { 7314 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7315 numberOfPackagesToDexopt + ": " + pkg.packageName); 7316 } 7317 7318 if (showDialog) { 7319 try { 7320 ActivityManagerNative.getDefault().showBootMessage( 7321 mContext.getResources().getString(R.string.android_upgrading_apk, 7322 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7323 } catch (RemoteException e) { 7324 } 7325 synchronized (mPackages) { 7326 mDexOptDialogShown = true; 7327 } 7328 } 7329 7330 // If the OTA updates a system app which was previously preopted to a non-preopted state 7331 // the app might end up being verified at runtime. That's because by default the apps 7332 // are verify-profile but for preopted apps there's no profile. 7333 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7334 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7335 // filter (by default interpret-only). 7336 // Note that at this stage unused apps are already filtered. 7337 if (isSystemApp(pkg) && 7338 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7339 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7340 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7341 } 7342 7343 // If the OTA updates a system app which was previously preopted to a non-preopted state 7344 // the app might end up being verified at runtime. That's because by default the apps 7345 // are verify-profile but for preopted apps there's no profile. 7346 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7347 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7348 // filter (by default interpret-only). 7349 // Note that at this stage unused apps are already filtered. 7350 if (isSystemApp(pkg) && 7351 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7352 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7353 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7354 } 7355 7356 // checkProfiles is false to avoid merging profiles during boot which 7357 // might interfere with background compilation (b/28612421). 7358 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7359 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7360 // trade-off worth doing to save boot time work. 7361 int dexOptStatus = performDexOptTraced(pkg.packageName, 7362 false /* checkProfiles */, 7363 compilerFilter, 7364 false /* force */); 7365 switch (dexOptStatus) { 7366 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7367 numberOfPackagesOptimized++; 7368 break; 7369 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7370 numberOfPackagesSkipped++; 7371 break; 7372 case PackageDexOptimizer.DEX_OPT_FAILED: 7373 numberOfPackagesFailed++; 7374 break; 7375 default: 7376 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7377 break; 7378 } 7379 } 7380 7381 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7382 numberOfPackagesFailed }; 7383 } 7384 7385 @Override 7386 public void notifyPackageUse(String packageName, int reason) { 7387 synchronized (mPackages) { 7388 PackageParser.Package p = mPackages.get(packageName); 7389 if (p == null) { 7390 return; 7391 } 7392 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7393 } 7394 } 7395 7396 @Override 7397 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 7398 int userId = UserHandle.getCallingUserId(); 7399 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 7400 if (ai == null) { 7401 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 7402 + loadingPackageName + ", user=" + userId); 7403 return; 7404 } 7405 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 7406 } 7407 7408 // TODO: this is not used nor needed. Delete it. 7409 @Override 7410 public boolean performDexOptIfNeeded(String packageName) { 7411 int dexOptStatus = performDexOptTraced(packageName, 7412 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7413 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7414 } 7415 7416 @Override 7417 public boolean performDexOpt(String packageName, 7418 boolean checkProfiles, int compileReason, boolean force) { 7419 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7420 getCompilerFilterForReason(compileReason), force); 7421 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7422 } 7423 7424 @Override 7425 public boolean performDexOptMode(String packageName, 7426 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7427 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7428 targetCompilerFilter, force); 7429 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7430 } 7431 7432 private int performDexOptTraced(String packageName, 7433 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7434 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7435 try { 7436 return performDexOptInternal(packageName, checkProfiles, 7437 targetCompilerFilter, force); 7438 } finally { 7439 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7440 } 7441 } 7442 7443 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7444 // if the package can now be considered up to date for the given filter. 7445 private int performDexOptInternal(String packageName, 7446 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7447 PackageParser.Package p; 7448 synchronized (mPackages) { 7449 p = mPackages.get(packageName); 7450 if (p == null) { 7451 // Package could not be found. Report failure. 7452 return PackageDexOptimizer.DEX_OPT_FAILED; 7453 } 7454 mPackageUsage.maybeWriteAsync(mPackages); 7455 mCompilerStats.maybeWriteAsync(); 7456 } 7457 long callingId = Binder.clearCallingIdentity(); 7458 try { 7459 synchronized (mInstallLock) { 7460 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7461 targetCompilerFilter, force); 7462 } 7463 } finally { 7464 Binder.restoreCallingIdentity(callingId); 7465 } 7466 } 7467 7468 public ArraySet<String> getOptimizablePackages() { 7469 ArraySet<String> pkgs = new ArraySet<String>(); 7470 synchronized (mPackages) { 7471 for (PackageParser.Package p : mPackages.values()) { 7472 if (PackageDexOptimizer.canOptimizePackage(p)) { 7473 pkgs.add(p.packageName); 7474 } 7475 } 7476 } 7477 return pkgs; 7478 } 7479 7480 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7481 boolean checkProfiles, String targetCompilerFilter, 7482 boolean force) { 7483 // Select the dex optimizer based on the force parameter. 7484 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7485 // allocate an object here. 7486 PackageDexOptimizer pdo = force 7487 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7488 : mPackageDexOptimizer; 7489 7490 // Optimize all dependencies first. Note: we ignore the return value and march on 7491 // on errors. 7492 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7493 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7494 if (!deps.isEmpty()) { 7495 for (PackageParser.Package depPackage : deps) { 7496 // TODO: Analyze and investigate if we (should) profile libraries. 7497 // Currently this will do a full compilation of the library by default. 7498 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7499 false /* checkProfiles */, 7500 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7501 getOrCreateCompilerPackageStats(depPackage), 7502 mDexManager.isUsedByOtherApps(p.packageName)); 7503 } 7504 } 7505 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7506 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 7507 mDexManager.isUsedByOtherApps(p.packageName)); 7508 } 7509 7510 // Performs dexopt on the used secondary dex files belonging to the given package. 7511 // Returns true if all dex files were process successfully (which could mean either dexopt or 7512 // skip). Returns false if any of the files caused errors. 7513 @Override 7514 public boolean performDexOptSecondary(String packageName, String compilerFilter, 7515 boolean force) { 7516 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 7517 } 7518 7519 public boolean performDexOptSecondary(String packageName, int compileReason, 7520 boolean force) { 7521 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force); 7522 } 7523 7524 /** 7525 * Reconcile the information we have about the secondary dex files belonging to 7526 * {@code packagName} and the actual dex files. For all dex files that were 7527 * deleted, update the internal records and delete the generated oat files. 7528 */ 7529 @Override 7530 public void reconcileSecondaryDexFiles(String packageName) { 7531 mDexManager.reconcileSecondaryDexFiles(packageName); 7532 } 7533 7534 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 7535 // a reference there. 7536 /*package*/ DexManager getDexManager() { 7537 return mDexManager; 7538 } 7539 7540 /** 7541 * Execute the background dexopt job immediately. 7542 */ 7543 @Override 7544 public boolean runBackgroundDexoptJob() { 7545 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 7546 } 7547 7548 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7549 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7550 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7551 Set<String> collectedNames = new HashSet<>(); 7552 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7553 7554 retValue.remove(p); 7555 7556 return retValue; 7557 } else { 7558 return Collections.emptyList(); 7559 } 7560 } 7561 7562 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7563 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7564 if (!collectedNames.contains(p.packageName)) { 7565 collectedNames.add(p.packageName); 7566 collected.add(p); 7567 7568 if (p.usesLibraries != null) { 7569 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7570 } 7571 if (p.usesOptionalLibraries != null) { 7572 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7573 collectedNames); 7574 } 7575 } 7576 } 7577 7578 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7579 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7580 for (String libName : libs) { 7581 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7582 if (libPkg != null) { 7583 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7584 } 7585 } 7586 } 7587 7588 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7589 synchronized (mPackages) { 7590 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7591 if (lib != null && lib.apk != null) { 7592 return mPackages.get(lib.apk); 7593 } 7594 } 7595 return null; 7596 } 7597 7598 public void shutdown() { 7599 mPackageUsage.writeNow(mPackages); 7600 mCompilerStats.writeNow(); 7601 } 7602 7603 @Override 7604 public void dumpProfiles(String packageName) { 7605 PackageParser.Package pkg; 7606 synchronized (mPackages) { 7607 pkg = mPackages.get(packageName); 7608 if (pkg == null) { 7609 throw new IllegalArgumentException("Unknown package: " + packageName); 7610 } 7611 } 7612 /* Only the shell, root, or the app user should be able to dump profiles. */ 7613 int callingUid = Binder.getCallingUid(); 7614 if (callingUid != Process.SHELL_UID && 7615 callingUid != Process.ROOT_UID && 7616 callingUid != pkg.applicationInfo.uid) { 7617 throw new SecurityException("dumpProfiles"); 7618 } 7619 7620 synchronized (mInstallLock) { 7621 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7622 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7623 try { 7624 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7625 String codePaths = TextUtils.join(";", allCodePaths); 7626 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 7627 } catch (InstallerException e) { 7628 Slog.w(TAG, "Failed to dump profiles", e); 7629 } 7630 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7631 } 7632 } 7633 7634 @Override 7635 public void forceDexOpt(String packageName) { 7636 enforceSystemOrRoot("forceDexOpt"); 7637 7638 PackageParser.Package pkg; 7639 synchronized (mPackages) { 7640 pkg = mPackages.get(packageName); 7641 if (pkg == null) { 7642 throw new IllegalArgumentException("Unknown package: " + packageName); 7643 } 7644 } 7645 7646 synchronized (mInstallLock) { 7647 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7648 7649 // Whoever is calling forceDexOpt wants a fully compiled package. 7650 // Don't use profiles since that may cause compilation to be skipped. 7651 final int res = performDexOptInternalWithDependenciesLI(pkg, 7652 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7653 true /* force */); 7654 7655 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7656 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7657 throw new IllegalStateException("Failed to dexopt: " + res); 7658 } 7659 } 7660 } 7661 7662 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7663 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7664 Slog.w(TAG, "Unable to update from " + oldPkg.name 7665 + " to " + newPkg.packageName 7666 + ": old package not in system partition"); 7667 return false; 7668 } else if (mPackages.get(oldPkg.name) != null) { 7669 Slog.w(TAG, "Unable to update from " + oldPkg.name 7670 + " to " + newPkg.packageName 7671 + ": old package still exists"); 7672 return false; 7673 } 7674 return true; 7675 } 7676 7677 void removeCodePathLI(File codePath) { 7678 if (codePath.isDirectory()) { 7679 try { 7680 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7681 } catch (InstallerException e) { 7682 Slog.w(TAG, "Failed to remove code path", e); 7683 } 7684 } else { 7685 codePath.delete(); 7686 } 7687 } 7688 7689 private int[] resolveUserIds(int userId) { 7690 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7691 } 7692 7693 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7694 if (pkg == null) { 7695 Slog.wtf(TAG, "Package was null!", new Throwable()); 7696 return; 7697 } 7698 clearAppDataLeafLIF(pkg, userId, flags); 7699 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7700 for (int i = 0; i < childCount; i++) { 7701 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7702 } 7703 } 7704 7705 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7706 final PackageSetting ps; 7707 synchronized (mPackages) { 7708 ps = mSettings.mPackages.get(pkg.packageName); 7709 } 7710 for (int realUserId : resolveUserIds(userId)) { 7711 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7712 try { 7713 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7714 ceDataInode); 7715 } catch (InstallerException e) { 7716 Slog.w(TAG, String.valueOf(e)); 7717 } 7718 } 7719 } 7720 7721 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7722 if (pkg == null) { 7723 Slog.wtf(TAG, "Package was null!", new Throwable()); 7724 return; 7725 } 7726 destroyAppDataLeafLIF(pkg, userId, flags); 7727 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7728 for (int i = 0; i < childCount; i++) { 7729 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7730 } 7731 } 7732 7733 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7734 final PackageSetting ps; 7735 synchronized (mPackages) { 7736 ps = mSettings.mPackages.get(pkg.packageName); 7737 } 7738 for (int realUserId : resolveUserIds(userId)) { 7739 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7740 try { 7741 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7742 ceDataInode); 7743 } catch (InstallerException e) { 7744 Slog.w(TAG, String.valueOf(e)); 7745 } 7746 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 7747 } 7748 } 7749 7750 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7751 if (pkg == null) { 7752 Slog.wtf(TAG, "Package was null!", new Throwable()); 7753 return; 7754 } 7755 destroyAppProfilesLeafLIF(pkg); 7756 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7757 for (int i = 0; i < childCount; i++) { 7758 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 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 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7777 for (int i = 0; i < childCount; i++) { 7778 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7779 } 7780 } 7781 7782 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7783 try { 7784 mInstaller.clearAppProfiles(pkg.packageName); 7785 } catch (InstallerException e) { 7786 Slog.w(TAG, String.valueOf(e)); 7787 } 7788 } 7789 7790 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7791 long lastUpdateTime) { 7792 // Set parent install/update time 7793 PackageSetting ps = (PackageSetting) pkg.mExtras; 7794 if (ps != null) { 7795 ps.firstInstallTime = firstInstallTime; 7796 ps.lastUpdateTime = lastUpdateTime; 7797 } 7798 // Set children install/update time 7799 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7800 for (int i = 0; i < childCount; i++) { 7801 PackageParser.Package childPkg = pkg.childPackages.get(i); 7802 ps = (PackageSetting) childPkg.mExtras; 7803 if (ps != null) { 7804 ps.firstInstallTime = firstInstallTime; 7805 ps.lastUpdateTime = lastUpdateTime; 7806 } 7807 } 7808 } 7809 7810 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7811 PackageParser.Package changingLib) { 7812 if (file.path != null) { 7813 usesLibraryFiles.add(file.path); 7814 return; 7815 } 7816 PackageParser.Package p = mPackages.get(file.apk); 7817 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7818 // If we are doing this while in the middle of updating a library apk, 7819 // then we need to make sure to use that new apk for determining the 7820 // dependencies here. (We haven't yet finished committing the new apk 7821 // to the package manager state.) 7822 if (p == null || p.packageName.equals(changingLib.packageName)) { 7823 p = changingLib; 7824 } 7825 } 7826 if (p != null) { 7827 usesLibraryFiles.addAll(p.getAllCodePaths()); 7828 } 7829 } 7830 7831 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7832 PackageParser.Package changingLib) throws PackageManagerException { 7833 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7834 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7835 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7836 for (int i=0; i<N; i++) { 7837 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7838 if (file == null) { 7839 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7840 "Package " + pkg.packageName + " requires unavailable shared library " 7841 + pkg.usesLibraries.get(i) + "; failing!"); 7842 } 7843 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7844 } 7845 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7846 for (int i=0; i<N; i++) { 7847 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7848 if (file == null) { 7849 Slog.w(TAG, "Package " + pkg.packageName 7850 + " desires unavailable shared library " 7851 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7852 } else { 7853 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7854 } 7855 } 7856 N = usesLibraryFiles.size(); 7857 if (N > 0) { 7858 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7859 } else { 7860 pkg.usesLibraryFiles = null; 7861 } 7862 } 7863 } 7864 7865 private static boolean hasString(List<String> list, List<String> which) { 7866 if (list == null) { 7867 return false; 7868 } 7869 for (int i=list.size()-1; i>=0; i--) { 7870 for (int j=which.size()-1; j>=0; j--) { 7871 if (which.get(j).equals(list.get(i))) { 7872 return true; 7873 } 7874 } 7875 } 7876 return false; 7877 } 7878 7879 private void updateAllSharedLibrariesLPw() { 7880 for (PackageParser.Package pkg : mPackages.values()) { 7881 try { 7882 updateSharedLibrariesLPw(pkg, null); 7883 } catch (PackageManagerException e) { 7884 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7885 } 7886 } 7887 } 7888 7889 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7890 PackageParser.Package changingPkg) { 7891 ArrayList<PackageParser.Package> res = null; 7892 for (PackageParser.Package pkg : mPackages.values()) { 7893 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7894 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7895 if (res == null) { 7896 res = new ArrayList<PackageParser.Package>(); 7897 } 7898 res.add(pkg); 7899 try { 7900 updateSharedLibrariesLPw(pkg, changingPkg); 7901 } catch (PackageManagerException e) { 7902 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7903 } 7904 } 7905 } 7906 return res; 7907 } 7908 7909 /** 7910 * Derive the value of the {@code cpuAbiOverride} based on the provided 7911 * value and an optional stored value from the package settings. 7912 */ 7913 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7914 String cpuAbiOverride = null; 7915 7916 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7917 cpuAbiOverride = null; 7918 } else if (abiOverride != null) { 7919 cpuAbiOverride = abiOverride; 7920 } else if (settings != null) { 7921 cpuAbiOverride = settings.cpuAbiOverrideString; 7922 } 7923 7924 return cpuAbiOverride; 7925 } 7926 7927 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7928 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7929 throws PackageManagerException { 7930 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7931 // If the package has children and this is the first dive in the function 7932 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7933 // whether all packages (parent and children) would be successfully scanned 7934 // before the actual scan since scanning mutates internal state and we want 7935 // to atomically install the package and its children. 7936 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7937 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7938 scanFlags |= SCAN_CHECK_ONLY; 7939 } 7940 } else { 7941 scanFlags &= ~SCAN_CHECK_ONLY; 7942 } 7943 7944 final PackageParser.Package scannedPkg; 7945 try { 7946 // Scan the parent 7947 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7948 // Scan the children 7949 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7950 for (int i = 0; i < childCount; i++) { 7951 PackageParser.Package childPkg = pkg.childPackages.get(i); 7952 scanPackageLI(childPkg, policyFlags, 7953 scanFlags, currentTime, user); 7954 } 7955 } finally { 7956 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7957 } 7958 7959 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7960 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7961 } 7962 7963 return scannedPkg; 7964 } 7965 7966 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7967 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7968 boolean success = false; 7969 try { 7970 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7971 currentTime, user); 7972 success = true; 7973 return res; 7974 } finally { 7975 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7976 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7977 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7978 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7979 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7980 } 7981 } 7982 } 7983 7984 /** 7985 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7986 */ 7987 private static boolean apkHasCode(String fileName) { 7988 StrictJarFile jarFile = null; 7989 try { 7990 jarFile = new StrictJarFile(fileName, 7991 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7992 return jarFile.findEntry("classes.dex") != null; 7993 } catch (IOException ignore) { 7994 } finally { 7995 try { 7996 if (jarFile != null) { 7997 jarFile.close(); 7998 } 7999 } catch (IOException ignore) {} 8000 } 8001 return false; 8002 } 8003 8004 /** 8005 * Enforces code policy for the package. This ensures that if an APK has 8006 * declared hasCode="true" in its manifest that the APK actually contains 8007 * code. 8008 * 8009 * @throws PackageManagerException If bytecode could not be found when it should exist 8010 */ 8011 private static void enforceCodePolicy(PackageParser.Package pkg) 8012 throws PackageManagerException { 8013 final boolean shouldHaveCode = 8014 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8015 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8016 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8017 "Package " + pkg.baseCodePath + " code is missing"); 8018 } 8019 8020 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8021 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8022 final boolean splitShouldHaveCode = 8023 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8024 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8025 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8026 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8027 } 8028 } 8029 } 8030 } 8031 8032 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8033 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8034 throws PackageManagerException { 8035 final File scanFile = new File(pkg.codePath); 8036 if (pkg.applicationInfo.getCodePath() == null || 8037 pkg.applicationInfo.getResourcePath() == null) { 8038 // Bail out. The resource and code paths haven't been set. 8039 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8040 "Code and resource paths haven't been set correctly"); 8041 } 8042 8043 // Apply policy 8044 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8045 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8046 if (pkg.applicationInfo.isDirectBootAware()) { 8047 // we're direct boot aware; set for all components 8048 for (PackageParser.Service s : pkg.services) { 8049 s.info.encryptionAware = s.info.directBootAware = true; 8050 } 8051 for (PackageParser.Provider p : pkg.providers) { 8052 p.info.encryptionAware = p.info.directBootAware = true; 8053 } 8054 for (PackageParser.Activity a : pkg.activities) { 8055 a.info.encryptionAware = a.info.directBootAware = true; 8056 } 8057 for (PackageParser.Activity r : pkg.receivers) { 8058 r.info.encryptionAware = r.info.directBootAware = true; 8059 } 8060 } 8061 } else { 8062 // Only allow system apps to be flagged as core apps. 8063 pkg.coreApp = false; 8064 // clear flags not applicable to regular apps 8065 pkg.applicationInfo.privateFlags &= 8066 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8067 pkg.applicationInfo.privateFlags &= 8068 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8069 } 8070 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8071 8072 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8073 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8074 } 8075 8076 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8077 enforceCodePolicy(pkg); 8078 } 8079 8080 if (mCustomResolverComponentName != null && 8081 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8082 setUpCustomResolverActivity(pkg); 8083 } 8084 8085 if (pkg.packageName.equals("android")) { 8086 synchronized (mPackages) { 8087 if (mAndroidApplication != null) { 8088 Slog.w(TAG, "*************************************************"); 8089 Slog.w(TAG, "Core android package being redefined. Skipping."); 8090 Slog.w(TAG, " file=" + scanFile); 8091 Slog.w(TAG, "*************************************************"); 8092 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8093 "Core android package being redefined. Skipping."); 8094 } 8095 8096 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8097 // Set up information for our fall-back user intent resolution activity. 8098 mPlatformPackage = pkg; 8099 pkg.mVersionCode = mSdkVersion; 8100 mAndroidApplication = pkg.applicationInfo; 8101 8102 if (!mResolverReplaced) { 8103 mResolveActivity.applicationInfo = mAndroidApplication; 8104 mResolveActivity.name = ResolverActivity.class.getName(); 8105 mResolveActivity.packageName = mAndroidApplication.packageName; 8106 mResolveActivity.processName = "system:ui"; 8107 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8108 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8109 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8110 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8111 mResolveActivity.exported = true; 8112 mResolveActivity.enabled = true; 8113 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8114 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8115 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8116 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8117 | ActivityInfo.CONFIG_ORIENTATION 8118 | ActivityInfo.CONFIG_KEYBOARD 8119 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8120 mResolveInfo.activityInfo = mResolveActivity; 8121 mResolveInfo.priority = 0; 8122 mResolveInfo.preferredOrder = 0; 8123 mResolveInfo.match = 0; 8124 mResolveComponentName = new ComponentName( 8125 mAndroidApplication.packageName, mResolveActivity.name); 8126 } 8127 } 8128 } 8129 } 8130 8131 if (DEBUG_PACKAGE_SCANNING) { 8132 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8133 Log.d(TAG, "Scanning package " + pkg.packageName); 8134 } 8135 8136 synchronized (mPackages) { 8137 if (mPackages.containsKey(pkg.packageName) 8138 || mSharedLibraries.containsKey(pkg.packageName)) { 8139 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8140 "Application package " + pkg.packageName 8141 + " already installed. Skipping duplicate."); 8142 } 8143 8144 // If we're only installing presumed-existing packages, require that the 8145 // scanned APK is both already known and at the path previously established 8146 // for it. Previously unknown packages we pick up normally, but if we have an 8147 // a priori expectation about this package's install presence, enforce it. 8148 // With a singular exception for new system packages. When an OTA contains 8149 // a new system package, we allow the codepath to change from a system location 8150 // to the user-installed location. If we don't allow this change, any newer, 8151 // user-installed version of the application will be ignored. 8152 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8153 if (mExpectingBetter.containsKey(pkg.packageName)) { 8154 logCriticalInfo(Log.WARN, 8155 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8156 } else { 8157 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8158 if (known != null) { 8159 if (DEBUG_PACKAGE_SCANNING) { 8160 Log.d(TAG, "Examining " + pkg.codePath 8161 + " and requiring known paths " + known.codePathString 8162 + " & " + known.resourcePathString); 8163 } 8164 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8165 || !pkg.applicationInfo.getResourcePath().equals( 8166 known.resourcePathString)) { 8167 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8168 "Application package " + pkg.packageName 8169 + " found at " + pkg.applicationInfo.getCodePath() 8170 + " but expected at " + known.codePathString 8171 + "; ignoring."); 8172 } 8173 } 8174 } 8175 } 8176 } 8177 8178 // Initialize package source and resource directories 8179 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8180 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8181 8182 SharedUserSetting suid = null; 8183 PackageSetting pkgSetting = null; 8184 8185 if (!isSystemApp(pkg)) { 8186 // Only system apps can use these features. 8187 pkg.mOriginalPackages = null; 8188 pkg.mRealPackage = null; 8189 pkg.mAdoptPermissions = null; 8190 } 8191 8192 // Getting the package setting may have a side-effect, so if we 8193 // are only checking if scan would succeed, stash a copy of the 8194 // old setting to restore at the end. 8195 PackageSetting nonMutatedPs = null; 8196 8197 // writer 8198 synchronized (mPackages) { 8199 if (pkg.mSharedUserId != null) { 8200 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8201 if (suid == null) { 8202 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8203 "Creating application package " + pkg.packageName 8204 + " for shared user failed"); 8205 } 8206 if (DEBUG_PACKAGE_SCANNING) { 8207 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8208 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8209 + "): packages=" + suid.packages); 8210 } 8211 } 8212 8213 // Check if we are renaming from an original package name. 8214 PackageSetting origPackage = null; 8215 String realName = null; 8216 if (pkg.mOriginalPackages != null) { 8217 // This package may need to be renamed to a previously 8218 // installed name. Let's check on that... 8219 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8220 if (pkg.mOriginalPackages.contains(renamed)) { 8221 // This package had originally been installed as the 8222 // original name, and we have already taken care of 8223 // transitioning to the new one. Just update the new 8224 // one to continue using the old name. 8225 realName = pkg.mRealPackage; 8226 if (!pkg.packageName.equals(renamed)) { 8227 // Callers into this function may have already taken 8228 // care of renaming the package; only do it here if 8229 // it is not already done. 8230 pkg.setPackageName(renamed); 8231 } 8232 8233 } else { 8234 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8235 if ((origPackage = mSettings.peekPackageLPr( 8236 pkg.mOriginalPackages.get(i))) != null) { 8237 // We do have the package already installed under its 8238 // original name... should we use it? 8239 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8240 // New package is not compatible with original. 8241 origPackage = null; 8242 continue; 8243 } else if (origPackage.sharedUser != null) { 8244 // Make sure uid is compatible between packages. 8245 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8246 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8247 + " to " + pkg.packageName + ": old uid " 8248 + origPackage.sharedUser.name 8249 + " differs from " + pkg.mSharedUserId); 8250 origPackage = null; 8251 continue; 8252 } 8253 // TODO: Add case when shared user id is added [b/28144775] 8254 } else { 8255 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8256 + pkg.packageName + " to old name " + origPackage.name); 8257 } 8258 break; 8259 } 8260 } 8261 } 8262 } 8263 8264 if (mTransferedPackages.contains(pkg.packageName)) { 8265 Slog.w(TAG, "Package " + pkg.packageName 8266 + " was transferred to another, but its .apk remains"); 8267 } 8268 8269 // See comments in nonMutatedPs declaration 8270 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8271 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8272 if (foundPs != null) { 8273 nonMutatedPs = new PackageSetting(foundPs); 8274 } 8275 } 8276 8277 // Just create the setting, don't add it yet. For already existing packages 8278 // the PkgSetting exists already and doesn't have to be created. 8279 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8280 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8281 pkg.applicationInfo.primaryCpuAbi, 8282 pkg.applicationInfo.secondaryCpuAbi, 8283 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8284 user, false); 8285 if (pkgSetting == null) { 8286 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8287 "Creating application package " + pkg.packageName + " failed"); 8288 } 8289 8290 if (pkgSetting.origPackage != null) { 8291 // If we are first transitioning from an original package, 8292 // fix up the new package's name now. We need to do this after 8293 // looking up the package under its new name, so getPackageLP 8294 // can take care of fiddling things correctly. 8295 pkg.setPackageName(origPackage.name); 8296 8297 // File a report about this. 8298 String msg = "New package " + pkgSetting.realName 8299 + " renamed to replace old package " + pkgSetting.name; 8300 reportSettingsProblem(Log.WARN, msg); 8301 8302 // Make a note of it. 8303 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8304 mTransferedPackages.add(origPackage.name); 8305 } 8306 8307 // No longer need to retain this. 8308 pkgSetting.origPackage = null; 8309 } 8310 8311 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8312 // Make a note of it. 8313 mTransferedPackages.add(pkg.packageName); 8314 } 8315 8316 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8317 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8318 } 8319 8320 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8321 // Check all shared libraries and map to their actual file path. 8322 // We only do this here for apps not on a system dir, because those 8323 // are the only ones that can fail an install due to this. We 8324 // will take care of the system apps by updating all of their 8325 // library paths after the scan is done. 8326 updateSharedLibrariesLPw(pkg, null); 8327 } 8328 8329 if (mFoundPolicyFile) { 8330 SELinuxMMAC.assignSeinfoValue(pkg); 8331 } 8332 8333 pkg.applicationInfo.uid = pkgSetting.appId; 8334 pkg.mExtras = pkgSetting; 8335 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8336 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8337 // We just determined the app is signed correctly, so bring 8338 // over the latest parsed certs. 8339 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8340 } else { 8341 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8342 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8343 "Package " + pkg.packageName + " upgrade keys do not match the " 8344 + "previously installed version"); 8345 } else { 8346 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8347 String msg = "System package " + pkg.packageName 8348 + " signature changed; retaining data."; 8349 reportSettingsProblem(Log.WARN, msg); 8350 } 8351 } 8352 } else { 8353 try { 8354 verifySignaturesLP(pkgSetting, pkg); 8355 // We just determined the app is signed correctly, so bring 8356 // over the latest parsed certs. 8357 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8358 } catch (PackageManagerException e) { 8359 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8360 throw e; 8361 } 8362 // The signature has changed, but this package is in the system 8363 // image... let's recover! 8364 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8365 // However... if this package is part of a shared user, but it 8366 // doesn't match the signature of the shared user, let's fail. 8367 // What this means is that you can't change the signatures 8368 // associated with an overall shared user, which doesn't seem all 8369 // that unreasonable. 8370 if (pkgSetting.sharedUser != null) { 8371 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8372 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8373 throw new PackageManagerException( 8374 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8375 "Signature mismatch for shared user: " 8376 + pkgSetting.sharedUser); 8377 } 8378 } 8379 // File a report about this. 8380 String msg = "System package " + pkg.packageName 8381 + " signature changed; retaining data."; 8382 reportSettingsProblem(Log.WARN, msg); 8383 } 8384 } 8385 // Verify that this new package doesn't have any content providers 8386 // that conflict with existing packages. Only do this if the 8387 // package isn't already installed, since we don't want to break 8388 // things that are installed. 8389 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8390 final int N = pkg.providers.size(); 8391 int i; 8392 for (i=0; i<N; i++) { 8393 PackageParser.Provider p = pkg.providers.get(i); 8394 if (p.info.authority != null) { 8395 String names[] = p.info.authority.split(";"); 8396 for (int j = 0; j < names.length; j++) { 8397 if (mProvidersByAuthority.containsKey(names[j])) { 8398 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8399 final String otherPackageName = 8400 ((other != null && other.getComponentName() != null) ? 8401 other.getComponentName().getPackageName() : "?"); 8402 throw new PackageManagerException( 8403 INSTALL_FAILED_CONFLICTING_PROVIDER, 8404 "Can't install because provider name " + names[j] 8405 + " (in package " + pkg.applicationInfo.packageName 8406 + ") is already used by " + otherPackageName); 8407 } 8408 } 8409 } 8410 } 8411 } 8412 8413 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8414 // This package wants to adopt ownership of permissions from 8415 // another package. 8416 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8417 final String origName = pkg.mAdoptPermissions.get(i); 8418 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8419 if (orig != null) { 8420 if (verifyPackageUpdateLPr(orig, pkg)) { 8421 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8422 + pkg.packageName); 8423 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8424 } 8425 } 8426 } 8427 } 8428 } 8429 8430 final String pkgName = pkg.packageName; 8431 8432 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8433 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8434 pkg.applicationInfo.processName = fixProcessName( 8435 pkg.applicationInfo.packageName, 8436 pkg.applicationInfo.processName, 8437 pkg.applicationInfo.uid); 8438 8439 if (pkg != mPlatformPackage) { 8440 // Get all of our default paths setup 8441 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8442 } 8443 8444 final String path = scanFile.getPath(); 8445 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8446 8447 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8448 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8449 8450 // Some system apps still use directory structure for native libraries 8451 // in which case we might end up not detecting abi solely based on apk 8452 // structure. Try to detect abi based on directory structure. 8453 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8454 pkg.applicationInfo.primaryCpuAbi == null) { 8455 setBundledAppAbisAndRoots(pkg, pkgSetting); 8456 setNativeLibraryPaths(pkg); 8457 } 8458 8459 } else { 8460 if ((scanFlags & SCAN_MOVE) != 0) { 8461 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8462 // but we already have this packages package info in the PackageSetting. We just 8463 // use that and derive the native library path based on the new codepath. 8464 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8465 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8466 } 8467 8468 // Set native library paths again. For moves, the path will be updated based on the 8469 // ABIs we've determined above. For non-moves, the path will be updated based on the 8470 // ABIs we determined during compilation, but the path will depend on the final 8471 // package path (after the rename away from the stage path). 8472 setNativeLibraryPaths(pkg); 8473 } 8474 8475 // This is a special case for the "system" package, where the ABI is 8476 // dictated by the zygote configuration (and init.rc). We should keep track 8477 // of this ABI so that we can deal with "normal" applications that run under 8478 // the same UID correctly. 8479 if (mPlatformPackage == pkg) { 8480 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8481 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8482 } 8483 8484 // If there's a mismatch between the abi-override in the package setting 8485 // and the abiOverride specified for the install. Warn about this because we 8486 // would've already compiled the app without taking the package setting into 8487 // account. 8488 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8489 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8490 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8491 " for package " + pkg.packageName); 8492 } 8493 } 8494 8495 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8496 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8497 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8498 8499 // Copy the derived override back to the parsed package, so that we can 8500 // update the package settings accordingly. 8501 pkg.cpuAbiOverride = cpuAbiOverride; 8502 8503 if (DEBUG_ABI_SELECTION) { 8504 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8505 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8506 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8507 } 8508 8509 // Push the derived path down into PackageSettings so we know what to 8510 // clean up at uninstall time. 8511 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8512 8513 if (DEBUG_ABI_SELECTION) { 8514 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8515 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8516 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8517 } 8518 8519 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8520 // We don't do this here during boot because we can do it all 8521 // at once after scanning all existing packages. 8522 // 8523 // We also do this *before* we perform dexopt on this package, so that 8524 // we can avoid redundant dexopts, and also to make sure we've got the 8525 // code and package path correct. 8526 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8527 pkg, true /* boot complete */); 8528 } 8529 8530 if (mFactoryTest && pkg.requestedPermissions.contains( 8531 android.Manifest.permission.FACTORY_TEST)) { 8532 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8533 } 8534 8535 if (isSystemApp(pkg)) { 8536 pkgSetting.isOrphaned = true; 8537 } 8538 8539 ArrayList<PackageParser.Package> clientLibPkgs = null; 8540 8541 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8542 if (nonMutatedPs != null) { 8543 synchronized (mPackages) { 8544 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8545 } 8546 } 8547 return pkg; 8548 } 8549 8550 // Only privileged apps and updated privileged apps can add child packages. 8551 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8552 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8553 throw new PackageManagerException("Only privileged apps and updated " 8554 + "privileged apps can add child packages. Ignoring package " 8555 + pkg.packageName); 8556 } 8557 final int childCount = pkg.childPackages.size(); 8558 for (int i = 0; i < childCount; i++) { 8559 PackageParser.Package childPkg = pkg.childPackages.get(i); 8560 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8561 childPkg.packageName)) { 8562 throw new PackageManagerException("Cannot override a child package of " 8563 + "another disabled system app. Ignoring package " + pkg.packageName); 8564 } 8565 } 8566 } 8567 8568 // writer 8569 synchronized (mPackages) { 8570 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8571 // Only system apps can add new shared libraries. 8572 if (pkg.libraryNames != null) { 8573 for (int i=0; i<pkg.libraryNames.size(); i++) { 8574 String name = pkg.libraryNames.get(i); 8575 boolean allowed = false; 8576 if (pkg.isUpdatedSystemApp()) { 8577 // New library entries can only be added through the 8578 // system image. This is important to get rid of a lot 8579 // of nasty edge cases: for example if we allowed a non- 8580 // system update of the app to add a library, then uninstalling 8581 // the update would make the library go away, and assumptions 8582 // we made such as through app install filtering would now 8583 // have allowed apps on the device which aren't compatible 8584 // with it. Better to just have the restriction here, be 8585 // conservative, and create many fewer cases that can negatively 8586 // impact the user experience. 8587 final PackageSetting sysPs = mSettings 8588 .getDisabledSystemPkgLPr(pkg.packageName); 8589 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8590 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8591 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8592 allowed = true; 8593 break; 8594 } 8595 } 8596 } 8597 } else { 8598 allowed = true; 8599 } 8600 if (allowed) { 8601 if (!mSharedLibraries.containsKey(name)) { 8602 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8603 } else if (!name.equals(pkg.packageName)) { 8604 Slog.w(TAG, "Package " + pkg.packageName + " library " 8605 + name + " already exists; skipping"); 8606 } 8607 } else { 8608 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8609 + name + " that is not declared on system image; skipping"); 8610 } 8611 } 8612 if ((scanFlags & SCAN_BOOTING) == 0) { 8613 // If we are not booting, we need to update any applications 8614 // that are clients of our shared library. If we are booting, 8615 // this will all be done once the scan is complete. 8616 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8617 } 8618 } 8619 } 8620 } 8621 8622 if ((scanFlags & SCAN_BOOTING) != 0) { 8623 // No apps can run during boot scan, so they don't need to be frozen 8624 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8625 // Caller asked to not kill app, so it's probably not frozen 8626 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8627 // Caller asked us to ignore frozen check for some reason; they 8628 // probably didn't know the package name 8629 } else { 8630 // We're doing major surgery on this package, so it better be frozen 8631 // right now to keep it from launching 8632 checkPackageFrozen(pkgName); 8633 } 8634 8635 // Also need to kill any apps that are dependent on the library. 8636 if (clientLibPkgs != null) { 8637 for (int i=0; i<clientLibPkgs.size(); i++) { 8638 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8639 killApplication(clientPkg.applicationInfo.packageName, 8640 clientPkg.applicationInfo.uid, "update lib"); 8641 } 8642 } 8643 8644 // Make sure we're not adding any bogus keyset info 8645 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8646 ksms.assertScannedPackageValid(pkg); 8647 8648 // writer 8649 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8650 8651 boolean createIdmapFailed = false; 8652 synchronized (mPackages) { 8653 // We don't expect installation to fail beyond this point 8654 8655 // Add the new setting to mSettings 8656 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8657 // Add the new setting to mPackages 8658 mPackages.put(pkg.applicationInfo.packageName, pkg); 8659 // Make sure we don't accidentally delete its data. 8660 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8661 while (iter.hasNext()) { 8662 PackageCleanItem item = iter.next(); 8663 if (pkgName.equals(item.packageName)) { 8664 iter.remove(); 8665 } 8666 } 8667 8668 // Take care of first install / last update times. 8669 if (currentTime != 0) { 8670 if (pkgSetting.firstInstallTime == 0) { 8671 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8672 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8673 pkgSetting.lastUpdateTime = currentTime; 8674 } 8675 } else if (pkgSetting.firstInstallTime == 0) { 8676 // We need *something*. Take time time stamp of the file. 8677 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8678 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8679 if (scanFileTime != pkgSetting.timeStamp) { 8680 // A package on the system image has changed; consider this 8681 // to be an update. 8682 pkgSetting.lastUpdateTime = scanFileTime; 8683 } 8684 } 8685 8686 // Add the package's KeySets to the global KeySetManagerService 8687 ksms.addScannedPackageLPw(pkg); 8688 8689 int N = pkg.providers.size(); 8690 StringBuilder r = null; 8691 int i; 8692 for (i=0; i<N; i++) { 8693 PackageParser.Provider p = pkg.providers.get(i); 8694 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8695 p.info.processName, pkg.applicationInfo.uid); 8696 mProviders.addProvider(p); 8697 p.syncable = p.info.isSyncable; 8698 if (p.info.authority != null) { 8699 String names[] = p.info.authority.split(";"); 8700 p.info.authority = null; 8701 for (int j = 0; j < names.length; j++) { 8702 if (j == 1 && p.syncable) { 8703 // We only want the first authority for a provider to possibly be 8704 // syncable, so if we already added this provider using a different 8705 // authority clear the syncable flag. We copy the provider before 8706 // changing it because the mProviders object contains a reference 8707 // to a provider that we don't want to change. 8708 // Only do this for the second authority since the resulting provider 8709 // object can be the same for all future authorities for this provider. 8710 p = new PackageParser.Provider(p); 8711 p.syncable = false; 8712 } 8713 if (!mProvidersByAuthority.containsKey(names[j])) { 8714 mProvidersByAuthority.put(names[j], p); 8715 if (p.info.authority == null) { 8716 p.info.authority = names[j]; 8717 } else { 8718 p.info.authority = p.info.authority + ";" + names[j]; 8719 } 8720 if (DEBUG_PACKAGE_SCANNING) { 8721 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8722 Log.d(TAG, "Registered content provider: " + names[j] 8723 + ", className = " + p.info.name + ", isSyncable = " 8724 + p.info.isSyncable); 8725 } 8726 } else { 8727 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8728 Slog.w(TAG, "Skipping provider name " + names[j] + 8729 " (in package " + pkg.applicationInfo.packageName + 8730 "): name already used by " 8731 + ((other != null && other.getComponentName() != null) 8732 ? other.getComponentName().getPackageName() : "?")); 8733 } 8734 } 8735 } 8736 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8737 if (r == null) { 8738 r = new StringBuilder(256); 8739 } else { 8740 r.append(' '); 8741 } 8742 r.append(p.info.name); 8743 } 8744 } 8745 if (r != null) { 8746 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8747 } 8748 8749 N = pkg.services.size(); 8750 r = null; 8751 for (i=0; i<N; i++) { 8752 PackageParser.Service s = pkg.services.get(i); 8753 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8754 s.info.processName, pkg.applicationInfo.uid); 8755 mServices.addService(s); 8756 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8757 if (r == null) { 8758 r = new StringBuilder(256); 8759 } else { 8760 r.append(' '); 8761 } 8762 r.append(s.info.name); 8763 } 8764 } 8765 if (r != null) { 8766 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8767 } 8768 8769 N = pkg.receivers.size(); 8770 r = null; 8771 for (i=0; i<N; i++) { 8772 PackageParser.Activity a = pkg.receivers.get(i); 8773 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8774 a.info.processName, pkg.applicationInfo.uid); 8775 mReceivers.addActivity(a, "receiver"); 8776 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8777 if (r == null) { 8778 r = new StringBuilder(256); 8779 } else { 8780 r.append(' '); 8781 } 8782 r.append(a.info.name); 8783 } 8784 } 8785 if (r != null) { 8786 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8787 } 8788 8789 N = pkg.activities.size(); 8790 r = null; 8791 for (i=0; i<N; i++) { 8792 PackageParser.Activity a = pkg.activities.get(i); 8793 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8794 a.info.processName, pkg.applicationInfo.uid); 8795 mActivities.addActivity(a, "activity"); 8796 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8797 if (r == null) { 8798 r = new StringBuilder(256); 8799 } else { 8800 r.append(' '); 8801 } 8802 r.append(a.info.name); 8803 } 8804 } 8805 if (r != null) { 8806 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8807 } 8808 8809 N = pkg.permissionGroups.size(); 8810 r = null; 8811 for (i=0; i<N; i++) { 8812 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8813 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8814 final String curPackageName = cur == null ? null : cur.info.packageName; 8815 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 8816 if (cur == null || isPackageUpdate) { 8817 mPermissionGroups.put(pg.info.name, pg); 8818 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8819 if (r == null) { 8820 r = new StringBuilder(256); 8821 } else { 8822 r.append(' '); 8823 } 8824 if (isPackageUpdate) { 8825 r.append("UPD:"); 8826 } 8827 r.append(pg.info.name); 8828 } 8829 } else { 8830 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8831 + pg.info.packageName + " ignored: original from " 8832 + cur.info.packageName); 8833 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8834 if (r == null) { 8835 r = new StringBuilder(256); 8836 } else { 8837 r.append(' '); 8838 } 8839 r.append("DUP:"); 8840 r.append(pg.info.name); 8841 } 8842 } 8843 } 8844 if (r != null) { 8845 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8846 } 8847 8848 N = pkg.permissions.size(); 8849 r = null; 8850 for (i=0; i<N; i++) { 8851 PackageParser.Permission p = pkg.permissions.get(i); 8852 8853 // Assume by default that we did not install this permission into the system. 8854 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8855 8856 // Now that permission groups have a special meaning, we ignore permission 8857 // groups for legacy apps to prevent unexpected behavior. In particular, 8858 // permissions for one app being granted to someone just becase they happen 8859 // to be in a group defined by another app (before this had no implications). 8860 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8861 p.group = mPermissionGroups.get(p.info.group); 8862 // Warn for a permission in an unknown group. 8863 if (p.info.group != null && p.group == null) { 8864 Slog.w(TAG, "Permission " + p.info.name + " from package " 8865 + p.info.packageName + " in an unknown group " + p.info.group); 8866 } 8867 } 8868 8869 ArrayMap<String, BasePermission> permissionMap = 8870 p.tree ? mSettings.mPermissionTrees 8871 : mSettings.mPermissions; 8872 BasePermission bp = permissionMap.get(p.info.name); 8873 8874 // Allow system apps to redefine non-system permissions 8875 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8876 final boolean currentOwnerIsSystem = (bp.perm != null 8877 && isSystemApp(bp.perm.owner)); 8878 if (isSystemApp(p.owner)) { 8879 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8880 // It's a built-in permission and no owner, take ownership now 8881 bp.packageSetting = pkgSetting; 8882 bp.perm = p; 8883 bp.uid = pkg.applicationInfo.uid; 8884 bp.sourcePackage = p.info.packageName; 8885 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8886 } else if (!currentOwnerIsSystem) { 8887 String msg = "New decl " + p.owner + " of permission " 8888 + p.info.name + " is system; overriding " + bp.sourcePackage; 8889 reportSettingsProblem(Log.WARN, msg); 8890 bp = null; 8891 } 8892 } 8893 } 8894 8895 if (bp == null) { 8896 bp = new BasePermission(p.info.name, p.info.packageName, 8897 BasePermission.TYPE_NORMAL); 8898 permissionMap.put(p.info.name, bp); 8899 } 8900 8901 if (bp.perm == null) { 8902 if (bp.sourcePackage == null 8903 || bp.sourcePackage.equals(p.info.packageName)) { 8904 BasePermission tree = findPermissionTreeLP(p.info.name); 8905 if (tree == null 8906 || tree.sourcePackage.equals(p.info.packageName)) { 8907 bp.packageSetting = pkgSetting; 8908 bp.perm = p; 8909 bp.uid = pkg.applicationInfo.uid; 8910 bp.sourcePackage = p.info.packageName; 8911 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8912 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8913 if (r == null) { 8914 r = new StringBuilder(256); 8915 } else { 8916 r.append(' '); 8917 } 8918 r.append(p.info.name); 8919 } 8920 } else { 8921 Slog.w(TAG, "Permission " + p.info.name + " from package " 8922 + p.info.packageName + " ignored: base tree " 8923 + tree.name + " is from package " 8924 + tree.sourcePackage); 8925 } 8926 } else { 8927 Slog.w(TAG, "Permission " + p.info.name + " from package " 8928 + p.info.packageName + " ignored: original from " 8929 + bp.sourcePackage); 8930 } 8931 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8932 if (r == null) { 8933 r = new StringBuilder(256); 8934 } else { 8935 r.append(' '); 8936 } 8937 r.append("DUP:"); 8938 r.append(p.info.name); 8939 } 8940 if (bp.perm == p) { 8941 bp.protectionLevel = p.info.protectionLevel; 8942 } 8943 } 8944 8945 if (r != null) { 8946 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8947 } 8948 8949 N = pkg.instrumentation.size(); 8950 r = null; 8951 for (i=0; i<N; i++) { 8952 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8953 a.info.packageName = pkg.applicationInfo.packageName; 8954 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8955 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8956 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8957 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8958 a.info.dataDir = pkg.applicationInfo.dataDir; 8959 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8960 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8961 8962 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8963 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8964 mInstrumentation.put(a.getComponentName(), a); 8965 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8966 if (r == null) { 8967 r = new StringBuilder(256); 8968 } else { 8969 r.append(' '); 8970 } 8971 r.append(a.info.name); 8972 } 8973 } 8974 if (r != null) { 8975 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8976 } 8977 8978 if (pkg.protectedBroadcasts != null) { 8979 N = pkg.protectedBroadcasts.size(); 8980 for (i=0; i<N; i++) { 8981 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8982 } 8983 } 8984 8985 pkgSetting.setTimeStamp(scanFileTime); 8986 8987 // Create idmap files for pairs of (packages, overlay packages). 8988 // Note: "android", ie framework-res.apk, is handled by native layers. 8989 if (pkg.mOverlayTarget != null) { 8990 // This is an overlay package. 8991 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8992 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8993 mOverlays.put(pkg.mOverlayTarget, 8994 new ArrayMap<String, PackageParser.Package>()); 8995 } 8996 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8997 map.put(pkg.packageName, pkg); 8998 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8999 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9000 createIdmapFailed = true; 9001 } 9002 } 9003 } else if (mOverlays.containsKey(pkg.packageName) && 9004 !pkg.packageName.equals("android")) { 9005 // This is a regular package, with one or more known overlay packages. 9006 createIdmapsForPackageLI(pkg); 9007 } 9008 } 9009 9010 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9011 9012 if (createIdmapFailed) { 9013 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9014 "scanPackageLI failed to createIdmap"); 9015 } 9016 return pkg; 9017 } 9018 9019 /** 9020 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9021 * is derived purely on the basis of the contents of {@code scanFile} and 9022 * {@code cpuAbiOverride}. 9023 * 9024 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9025 */ 9026 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9027 String cpuAbiOverride, boolean extractLibs) 9028 throws PackageManagerException { 9029 // TODO: We can probably be smarter about this stuff. For installed apps, 9030 // we can calculate this information at install time once and for all. For 9031 // system apps, we can probably assume that this information doesn't change 9032 // after the first boot scan. As things stand, we do lots of unnecessary work. 9033 9034 // Give ourselves some initial paths; we'll come back for another 9035 // pass once we've determined ABI below. 9036 setNativeLibraryPaths(pkg); 9037 9038 // We would never need to extract libs for forward-locked and external packages, 9039 // since the container service will do it for us. We shouldn't attempt to 9040 // extract libs from system app when it was not updated. 9041 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9042 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9043 extractLibs = false; 9044 } 9045 9046 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9047 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9048 9049 NativeLibraryHelper.Handle handle = null; 9050 try { 9051 handle = NativeLibraryHelper.Handle.create(pkg); 9052 // TODO(multiArch): This can be null for apps that didn't go through the 9053 // usual installation process. We can calculate it again, like we 9054 // do during install time. 9055 // 9056 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9057 // unnecessary. 9058 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9059 9060 // Null out the abis so that they can be recalculated. 9061 pkg.applicationInfo.primaryCpuAbi = null; 9062 pkg.applicationInfo.secondaryCpuAbi = null; 9063 if (isMultiArch(pkg.applicationInfo)) { 9064 // Warn if we've set an abiOverride for multi-lib packages.. 9065 // By definition, we need to copy both 32 and 64 bit libraries for 9066 // such packages. 9067 if (pkg.cpuAbiOverride != null 9068 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9069 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9070 } 9071 9072 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9073 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9074 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9075 if (extractLibs) { 9076 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9077 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9078 useIsaSpecificSubdirs); 9079 } else { 9080 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9081 } 9082 } 9083 9084 maybeThrowExceptionForMultiArchCopy( 9085 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9086 9087 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9088 if (extractLibs) { 9089 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9090 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9091 useIsaSpecificSubdirs); 9092 } else { 9093 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9094 } 9095 } 9096 9097 maybeThrowExceptionForMultiArchCopy( 9098 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9099 9100 if (abi64 >= 0) { 9101 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9102 } 9103 9104 if (abi32 >= 0) { 9105 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9106 if (abi64 >= 0) { 9107 if (pkg.use32bitAbi) { 9108 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9109 pkg.applicationInfo.primaryCpuAbi = abi; 9110 } else { 9111 pkg.applicationInfo.secondaryCpuAbi = abi; 9112 } 9113 } else { 9114 pkg.applicationInfo.primaryCpuAbi = abi; 9115 } 9116 } 9117 9118 } else { 9119 String[] abiList = (cpuAbiOverride != null) ? 9120 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9121 9122 // Enable gross and lame hacks for apps that are built with old 9123 // SDK tools. We must scan their APKs for renderscript bitcode and 9124 // not launch them if it's present. Don't bother checking on devices 9125 // that don't have 64 bit support. 9126 boolean needsRenderScriptOverride = false; 9127 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9128 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9129 abiList = Build.SUPPORTED_32_BIT_ABIS; 9130 needsRenderScriptOverride = true; 9131 } 9132 9133 final int copyRet; 9134 if (extractLibs) { 9135 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9136 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9137 } else { 9138 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9139 } 9140 9141 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9142 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9143 "Error unpackaging native libs for app, errorCode=" + copyRet); 9144 } 9145 9146 if (copyRet >= 0) { 9147 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9148 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9149 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9150 } else if (needsRenderScriptOverride) { 9151 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9152 } 9153 } 9154 } catch (IOException ioe) { 9155 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9156 } finally { 9157 IoUtils.closeQuietly(handle); 9158 } 9159 9160 // Now that we've calculated the ABIs and determined if it's an internal app, 9161 // we will go ahead and populate the nativeLibraryPath. 9162 setNativeLibraryPaths(pkg); 9163 } 9164 9165 /** 9166 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9167 * i.e, so that all packages can be run inside a single process if required. 9168 * 9169 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9170 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9171 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9172 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9173 * updating a package that belongs to a shared user. 9174 * 9175 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9176 * adds unnecessary complexity. 9177 */ 9178 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9179 PackageParser.Package scannedPackage, boolean bootComplete) { 9180 String requiredInstructionSet = null; 9181 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9182 requiredInstructionSet = VMRuntime.getInstructionSet( 9183 scannedPackage.applicationInfo.primaryCpuAbi); 9184 } 9185 9186 PackageSetting requirer = null; 9187 for (PackageSetting ps : packagesForUser) { 9188 // If packagesForUser contains scannedPackage, we skip it. This will happen 9189 // when scannedPackage is an update of an existing package. Without this check, 9190 // we will never be able to change the ABI of any package belonging to a shared 9191 // user, even if it's compatible with other packages. 9192 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9193 if (ps.primaryCpuAbiString == null) { 9194 continue; 9195 } 9196 9197 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9198 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9199 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9200 // this but there's not much we can do. 9201 String errorMessage = "Instruction set mismatch, " 9202 + ((requirer == null) ? "[caller]" : requirer) 9203 + " requires " + requiredInstructionSet + " whereas " + ps 9204 + " requires " + instructionSet; 9205 Slog.w(TAG, errorMessage); 9206 } 9207 9208 if (requiredInstructionSet == null) { 9209 requiredInstructionSet = instructionSet; 9210 requirer = ps; 9211 } 9212 } 9213 } 9214 9215 if (requiredInstructionSet != null) { 9216 String adjustedAbi; 9217 if (requirer != null) { 9218 // requirer != null implies that either scannedPackage was null or that scannedPackage 9219 // did not require an ABI, in which case we have to adjust scannedPackage to match 9220 // the ABI of the set (which is the same as requirer's ABI) 9221 adjustedAbi = requirer.primaryCpuAbiString; 9222 if (scannedPackage != null) { 9223 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9224 } 9225 } else { 9226 // requirer == null implies that we're updating all ABIs in the set to 9227 // match scannedPackage. 9228 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9229 } 9230 9231 for (PackageSetting ps : packagesForUser) { 9232 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9233 if (ps.primaryCpuAbiString != null) { 9234 continue; 9235 } 9236 9237 ps.primaryCpuAbiString = adjustedAbi; 9238 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9239 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9240 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9241 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9242 + " (requirer=" 9243 + (requirer != null ? requirer.pkg : "null") 9244 + ", scannedPackage=" 9245 + (scannedPackage != null ? scannedPackage : "null") 9246 + ")"); 9247 try { 9248 mInstaller.rmdex(ps.codePathString, 9249 getDexCodeInstructionSet(getPreferredInstructionSet())); 9250 } catch (InstallerException ignored) { 9251 } 9252 } 9253 } 9254 } 9255 } 9256 } 9257 9258 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9259 synchronized (mPackages) { 9260 mResolverReplaced = true; 9261 // Set up information for custom user intent resolution activity. 9262 mResolveActivity.applicationInfo = pkg.applicationInfo; 9263 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9264 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9265 mResolveActivity.processName = pkg.applicationInfo.packageName; 9266 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9267 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9268 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9269 mResolveActivity.theme = 0; 9270 mResolveActivity.exported = true; 9271 mResolveActivity.enabled = true; 9272 mResolveInfo.activityInfo = mResolveActivity; 9273 mResolveInfo.priority = 0; 9274 mResolveInfo.preferredOrder = 0; 9275 mResolveInfo.match = 0; 9276 mResolveComponentName = mCustomResolverComponentName; 9277 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9278 mResolveComponentName); 9279 } 9280 } 9281 9282 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9283 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9284 9285 // Set up information for ephemeral installer activity 9286 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9287 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9288 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9289 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9290 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9291 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9292 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9293 mEphemeralInstallerActivity.theme = 0; 9294 mEphemeralInstallerActivity.exported = true; 9295 mEphemeralInstallerActivity.enabled = true; 9296 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9297 mEphemeralInstallerInfo.priority = 0; 9298 mEphemeralInstallerInfo.preferredOrder = 1; 9299 mEphemeralInstallerInfo.isDefault = true; 9300 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9301 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9302 9303 if (DEBUG_EPHEMERAL) { 9304 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9305 } 9306 } 9307 9308 private static String calculateBundledApkRoot(final String codePathString) { 9309 final File codePath = new File(codePathString); 9310 final File codeRoot; 9311 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9312 codeRoot = Environment.getRootDirectory(); 9313 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9314 codeRoot = Environment.getOemDirectory(); 9315 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9316 codeRoot = Environment.getVendorDirectory(); 9317 } else { 9318 // Unrecognized code path; take its top real segment as the apk root: 9319 // e.g. /something/app/blah.apk => /something 9320 try { 9321 File f = codePath.getCanonicalFile(); 9322 File parent = f.getParentFile(); // non-null because codePath is a file 9323 File tmp; 9324 while ((tmp = parent.getParentFile()) != null) { 9325 f = parent; 9326 parent = tmp; 9327 } 9328 codeRoot = f; 9329 Slog.w(TAG, "Unrecognized code path " 9330 + codePath + " - using " + codeRoot); 9331 } catch (IOException e) { 9332 // Can't canonicalize the code path -- shenanigans? 9333 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9334 return Environment.getRootDirectory().getPath(); 9335 } 9336 } 9337 return codeRoot.getPath(); 9338 } 9339 9340 /** 9341 * Derive and set the location of native libraries for the given package, 9342 * which varies depending on where and how the package was installed. 9343 */ 9344 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9345 final ApplicationInfo info = pkg.applicationInfo; 9346 final String codePath = pkg.codePath; 9347 final File codeFile = new File(codePath); 9348 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9349 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9350 9351 info.nativeLibraryRootDir = null; 9352 info.nativeLibraryRootRequiresIsa = false; 9353 info.nativeLibraryDir = null; 9354 info.secondaryNativeLibraryDir = null; 9355 9356 if (isApkFile(codeFile)) { 9357 // Monolithic install 9358 if (bundledApp) { 9359 // If "/system/lib64/apkname" exists, assume that is the per-package 9360 // native library directory to use; otherwise use "/system/lib/apkname". 9361 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9362 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9363 getPrimaryInstructionSet(info)); 9364 9365 // This is a bundled system app so choose the path based on the ABI. 9366 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9367 // is just the default path. 9368 final String apkName = deriveCodePathName(codePath); 9369 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9370 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9371 apkName).getAbsolutePath(); 9372 9373 if (info.secondaryCpuAbi != null) { 9374 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9375 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9376 secondaryLibDir, apkName).getAbsolutePath(); 9377 } 9378 } else if (asecApp) { 9379 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9380 .getAbsolutePath(); 9381 } else { 9382 final String apkName = deriveCodePathName(codePath); 9383 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9384 .getAbsolutePath(); 9385 } 9386 9387 info.nativeLibraryRootRequiresIsa = false; 9388 info.nativeLibraryDir = info.nativeLibraryRootDir; 9389 } else { 9390 // Cluster install 9391 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9392 info.nativeLibraryRootRequiresIsa = true; 9393 9394 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9395 getPrimaryInstructionSet(info)).getAbsolutePath(); 9396 9397 if (info.secondaryCpuAbi != null) { 9398 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9399 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9400 } 9401 } 9402 } 9403 9404 /** 9405 * Calculate the abis and roots for a bundled app. These can uniquely 9406 * be determined from the contents of the system partition, i.e whether 9407 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9408 * of this information, and instead assume that the system was built 9409 * sensibly. 9410 */ 9411 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9412 PackageSetting pkgSetting) { 9413 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9414 9415 // If "/system/lib64/apkname" exists, assume that is the per-package 9416 // native library directory to use; otherwise use "/system/lib/apkname". 9417 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9418 setBundledAppAbi(pkg, apkRoot, apkName); 9419 // pkgSetting might be null during rescan following uninstall of updates 9420 // to a bundled app, so accommodate that possibility. The settings in 9421 // that case will be established later from the parsed package. 9422 // 9423 // If the settings aren't null, sync them up with what we've just derived. 9424 // note that apkRoot isn't stored in the package settings. 9425 if (pkgSetting != null) { 9426 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9427 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9428 } 9429 } 9430 9431 /** 9432 * Deduces the ABI of a bundled app and sets the relevant fields on the 9433 * parsed pkg object. 9434 * 9435 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9436 * under which system libraries are installed. 9437 * @param apkName the name of the installed package. 9438 */ 9439 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9440 final File codeFile = new File(pkg.codePath); 9441 9442 final boolean has64BitLibs; 9443 final boolean has32BitLibs; 9444 if (isApkFile(codeFile)) { 9445 // Monolithic install 9446 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9447 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9448 } else { 9449 // Cluster install 9450 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9451 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9452 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9453 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9454 has64BitLibs = (new File(rootDir, isa)).exists(); 9455 } else { 9456 has64BitLibs = false; 9457 } 9458 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9459 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9460 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9461 has32BitLibs = (new File(rootDir, isa)).exists(); 9462 } else { 9463 has32BitLibs = false; 9464 } 9465 } 9466 9467 if (has64BitLibs && !has32BitLibs) { 9468 // The package has 64 bit libs, but not 32 bit libs. Its primary 9469 // ABI should be 64 bit. We can safely assume here that the bundled 9470 // native libraries correspond to the most preferred ABI in the list. 9471 9472 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9473 pkg.applicationInfo.secondaryCpuAbi = null; 9474 } else if (has32BitLibs && !has64BitLibs) { 9475 // The package has 32 bit libs but not 64 bit libs. Its primary 9476 // ABI should be 32 bit. 9477 9478 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9479 pkg.applicationInfo.secondaryCpuAbi = null; 9480 } else if (has32BitLibs && has64BitLibs) { 9481 // The application has both 64 and 32 bit bundled libraries. We check 9482 // here that the app declares multiArch support, and warn if it doesn't. 9483 // 9484 // We will be lenient here and record both ABIs. The primary will be the 9485 // ABI that's higher on the list, i.e, a device that's configured to prefer 9486 // 64 bit apps will see a 64 bit primary ABI, 9487 9488 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9489 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9490 } 9491 9492 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9493 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9494 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9495 } else { 9496 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9497 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9498 } 9499 } else { 9500 pkg.applicationInfo.primaryCpuAbi = null; 9501 pkg.applicationInfo.secondaryCpuAbi = null; 9502 } 9503 } 9504 9505 private void killApplication(String pkgName, int appId, String reason) { 9506 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9507 } 9508 9509 private void killApplication(String pkgName, int appId, int userId, String reason) { 9510 // Request the ActivityManager to kill the process(only for existing packages) 9511 // so that we do not end up in a confused state while the user is still using the older 9512 // version of the application while the new one gets installed. 9513 final long token = Binder.clearCallingIdentity(); 9514 try { 9515 IActivityManager am = ActivityManagerNative.getDefault(); 9516 if (am != null) { 9517 try { 9518 am.killApplication(pkgName, appId, userId, reason); 9519 } catch (RemoteException e) { 9520 } 9521 } 9522 } finally { 9523 Binder.restoreCallingIdentity(token); 9524 } 9525 } 9526 9527 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9528 // Remove the parent package setting 9529 PackageSetting ps = (PackageSetting) pkg.mExtras; 9530 if (ps != null) { 9531 removePackageLI(ps, chatty); 9532 } 9533 // Remove the child package setting 9534 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9535 for (int i = 0; i < childCount; i++) { 9536 PackageParser.Package childPkg = pkg.childPackages.get(i); 9537 ps = (PackageSetting) childPkg.mExtras; 9538 if (ps != null) { 9539 removePackageLI(ps, chatty); 9540 } 9541 } 9542 } 9543 9544 void removePackageLI(PackageSetting ps, boolean chatty) { 9545 if (DEBUG_INSTALL) { 9546 if (chatty) 9547 Log.d(TAG, "Removing package " + ps.name); 9548 } 9549 9550 // writer 9551 synchronized (mPackages) { 9552 mPackages.remove(ps.name); 9553 final PackageParser.Package pkg = ps.pkg; 9554 if (pkg != null) { 9555 cleanPackageDataStructuresLILPw(pkg, chatty); 9556 } 9557 } 9558 } 9559 9560 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9561 if (DEBUG_INSTALL) { 9562 if (chatty) 9563 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9564 } 9565 9566 // writer 9567 synchronized (mPackages) { 9568 // Remove the parent package 9569 mPackages.remove(pkg.applicationInfo.packageName); 9570 cleanPackageDataStructuresLILPw(pkg, chatty); 9571 9572 // Remove the child packages 9573 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9574 for (int i = 0; i < childCount; i++) { 9575 PackageParser.Package childPkg = pkg.childPackages.get(i); 9576 mPackages.remove(childPkg.applicationInfo.packageName); 9577 cleanPackageDataStructuresLILPw(childPkg, chatty); 9578 } 9579 } 9580 } 9581 9582 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9583 int N = pkg.providers.size(); 9584 StringBuilder r = null; 9585 int i; 9586 for (i=0; i<N; i++) { 9587 PackageParser.Provider p = pkg.providers.get(i); 9588 mProviders.removeProvider(p); 9589 if (p.info.authority == null) { 9590 9591 /* There was another ContentProvider with this authority when 9592 * this app was installed so this authority is null, 9593 * Ignore it as we don't have to unregister the provider. 9594 */ 9595 continue; 9596 } 9597 String names[] = p.info.authority.split(";"); 9598 for (int j = 0; j < names.length; j++) { 9599 if (mProvidersByAuthority.get(names[j]) == p) { 9600 mProvidersByAuthority.remove(names[j]); 9601 if (DEBUG_REMOVE) { 9602 if (chatty) 9603 Log.d(TAG, "Unregistered content provider: " + names[j] 9604 + ", className = " + p.info.name + ", isSyncable = " 9605 + p.info.isSyncable); 9606 } 9607 } 9608 } 9609 if (DEBUG_REMOVE && chatty) { 9610 if (r == null) { 9611 r = new StringBuilder(256); 9612 } else { 9613 r.append(' '); 9614 } 9615 r.append(p.info.name); 9616 } 9617 } 9618 if (r != null) { 9619 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9620 } 9621 9622 N = pkg.services.size(); 9623 r = null; 9624 for (i=0; i<N; i++) { 9625 PackageParser.Service s = pkg.services.get(i); 9626 mServices.removeService(s); 9627 if (chatty) { 9628 if (r == null) { 9629 r = new StringBuilder(256); 9630 } else { 9631 r.append(' '); 9632 } 9633 r.append(s.info.name); 9634 } 9635 } 9636 if (r != null) { 9637 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9638 } 9639 9640 N = pkg.receivers.size(); 9641 r = null; 9642 for (i=0; i<N; i++) { 9643 PackageParser.Activity a = pkg.receivers.get(i); 9644 mReceivers.removeActivity(a, "receiver"); 9645 if (DEBUG_REMOVE && chatty) { 9646 if (r == null) { 9647 r = new StringBuilder(256); 9648 } else { 9649 r.append(' '); 9650 } 9651 r.append(a.info.name); 9652 } 9653 } 9654 if (r != null) { 9655 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9656 } 9657 9658 N = pkg.activities.size(); 9659 r = null; 9660 for (i=0; i<N; i++) { 9661 PackageParser.Activity a = pkg.activities.get(i); 9662 mActivities.removeActivity(a, "activity"); 9663 if (DEBUG_REMOVE && chatty) { 9664 if (r == null) { 9665 r = new StringBuilder(256); 9666 } else { 9667 r.append(' '); 9668 } 9669 r.append(a.info.name); 9670 } 9671 } 9672 if (r != null) { 9673 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9674 } 9675 9676 N = pkg.permissions.size(); 9677 r = null; 9678 for (i=0; i<N; i++) { 9679 PackageParser.Permission p = pkg.permissions.get(i); 9680 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9681 if (bp == null) { 9682 bp = mSettings.mPermissionTrees.get(p.info.name); 9683 } 9684 if (bp != null && bp.perm == p) { 9685 bp.perm = null; 9686 if (DEBUG_REMOVE && chatty) { 9687 if (r == null) { 9688 r = new StringBuilder(256); 9689 } else { 9690 r.append(' '); 9691 } 9692 r.append(p.info.name); 9693 } 9694 } 9695 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9696 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9697 if (appOpPkgs != null) { 9698 appOpPkgs.remove(pkg.packageName); 9699 } 9700 } 9701 } 9702 if (r != null) { 9703 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9704 } 9705 9706 N = pkg.requestedPermissions.size(); 9707 r = null; 9708 for (i=0; i<N; i++) { 9709 String perm = pkg.requestedPermissions.get(i); 9710 BasePermission bp = mSettings.mPermissions.get(perm); 9711 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9712 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9713 if (appOpPkgs != null) { 9714 appOpPkgs.remove(pkg.packageName); 9715 if (appOpPkgs.isEmpty()) { 9716 mAppOpPermissionPackages.remove(perm); 9717 } 9718 } 9719 } 9720 } 9721 if (r != null) { 9722 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9723 } 9724 9725 N = pkg.instrumentation.size(); 9726 r = null; 9727 for (i=0; i<N; i++) { 9728 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9729 mInstrumentation.remove(a.getComponentName()); 9730 if (DEBUG_REMOVE && chatty) { 9731 if (r == null) { 9732 r = new StringBuilder(256); 9733 } else { 9734 r.append(' '); 9735 } 9736 r.append(a.info.name); 9737 } 9738 } 9739 if (r != null) { 9740 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9741 } 9742 9743 r = null; 9744 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9745 // Only system apps can hold shared libraries. 9746 if (pkg.libraryNames != null) { 9747 for (i=0; i<pkg.libraryNames.size(); i++) { 9748 String name = pkg.libraryNames.get(i); 9749 SharedLibraryEntry cur = mSharedLibraries.get(name); 9750 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9751 mSharedLibraries.remove(name); 9752 if (DEBUG_REMOVE && chatty) { 9753 if (r == null) { 9754 r = new StringBuilder(256); 9755 } else { 9756 r.append(' '); 9757 } 9758 r.append(name); 9759 } 9760 } 9761 } 9762 } 9763 } 9764 if (r != null) { 9765 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9766 } 9767 } 9768 9769 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9770 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9771 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9772 return true; 9773 } 9774 } 9775 return false; 9776 } 9777 9778 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9779 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9780 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9781 9782 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9783 // Update the parent permissions 9784 updatePermissionsLPw(pkg.packageName, pkg, flags); 9785 // Update the child permissions 9786 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9787 for (int i = 0; i < childCount; i++) { 9788 PackageParser.Package childPkg = pkg.childPackages.get(i); 9789 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9790 } 9791 } 9792 9793 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9794 int flags) { 9795 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9796 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9797 } 9798 9799 private void updatePermissionsLPw(String changingPkg, 9800 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9801 // Make sure there are no dangling permission trees. 9802 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9803 while (it.hasNext()) { 9804 final BasePermission bp = it.next(); 9805 if (bp.packageSetting == null) { 9806 // We may not yet have parsed the package, so just see if 9807 // we still know about its settings. 9808 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9809 } 9810 if (bp.packageSetting == null) { 9811 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9812 + " from package " + bp.sourcePackage); 9813 it.remove(); 9814 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9815 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9816 Slog.i(TAG, "Removing old permission tree: " + bp.name 9817 + " from package " + bp.sourcePackage); 9818 flags |= UPDATE_PERMISSIONS_ALL; 9819 it.remove(); 9820 } 9821 } 9822 } 9823 9824 // Make sure all dynamic permissions have been assigned to a package, 9825 // and make sure there are no dangling permissions. 9826 it = mSettings.mPermissions.values().iterator(); 9827 while (it.hasNext()) { 9828 final BasePermission bp = it.next(); 9829 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9830 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9831 + bp.name + " pkg=" + bp.sourcePackage 9832 + " info=" + bp.pendingInfo); 9833 if (bp.packageSetting == null && bp.pendingInfo != null) { 9834 final BasePermission tree = findPermissionTreeLP(bp.name); 9835 if (tree != null && tree.perm != null) { 9836 bp.packageSetting = tree.packageSetting; 9837 bp.perm = new PackageParser.Permission(tree.perm.owner, 9838 new PermissionInfo(bp.pendingInfo)); 9839 bp.perm.info.packageName = tree.perm.info.packageName; 9840 bp.perm.info.name = bp.name; 9841 bp.uid = tree.uid; 9842 } 9843 } 9844 } 9845 if (bp.packageSetting == null) { 9846 // We may not yet have parsed the package, so just see if 9847 // we still know about its settings. 9848 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9849 } 9850 if (bp.packageSetting == null) { 9851 Slog.w(TAG, "Removing dangling permission: " + bp.name 9852 + " from package " + bp.sourcePackage); 9853 it.remove(); 9854 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9855 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9856 Slog.i(TAG, "Removing old permission: " + bp.name 9857 + " from package " + bp.sourcePackage); 9858 flags |= UPDATE_PERMISSIONS_ALL; 9859 it.remove(); 9860 } 9861 } 9862 } 9863 9864 // Now update the permissions for all packages, in particular 9865 // replace the granted permissions of the system packages. 9866 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9867 for (PackageParser.Package pkg : mPackages.values()) { 9868 if (pkg != pkgInfo) { 9869 // Only replace for packages on requested volume 9870 final String volumeUuid = getVolumeUuidForPackage(pkg); 9871 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9872 && Objects.equals(replaceVolumeUuid, volumeUuid); 9873 grantPermissionsLPw(pkg, replace, changingPkg); 9874 } 9875 } 9876 } 9877 9878 if (pkgInfo != null) { 9879 // Only replace for packages on requested volume 9880 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9881 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9882 && Objects.equals(replaceVolumeUuid, volumeUuid); 9883 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9884 } 9885 } 9886 9887 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9888 String packageOfInterest) { 9889 // IMPORTANT: There are two types of permissions: install and runtime. 9890 // Install time permissions are granted when the app is installed to 9891 // all device users and users added in the future. Runtime permissions 9892 // are granted at runtime explicitly to specific users. Normal and signature 9893 // protected permissions are install time permissions. Dangerous permissions 9894 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9895 // otherwise they are runtime permissions. This function does not manage 9896 // runtime permissions except for the case an app targeting Lollipop MR1 9897 // being upgraded to target a newer SDK, in which case dangerous permissions 9898 // are transformed from install time to runtime ones. 9899 9900 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9901 if (ps == null) { 9902 return; 9903 } 9904 9905 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9906 9907 PermissionsState permissionsState = ps.getPermissionsState(); 9908 PermissionsState origPermissions = permissionsState; 9909 9910 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9911 9912 boolean runtimePermissionsRevoked = false; 9913 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9914 9915 boolean changedInstallPermission = false; 9916 9917 if (replace) { 9918 ps.installPermissionsFixed = false; 9919 if (!ps.isSharedUser()) { 9920 origPermissions = new PermissionsState(permissionsState); 9921 permissionsState.reset(); 9922 } else { 9923 // We need to know only about runtime permission changes since the 9924 // calling code always writes the install permissions state but 9925 // the runtime ones are written only if changed. The only cases of 9926 // changed runtime permissions here are promotion of an install to 9927 // runtime and revocation of a runtime from a shared user. 9928 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9929 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9930 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9931 runtimePermissionsRevoked = true; 9932 } 9933 } 9934 } 9935 9936 permissionsState.setGlobalGids(mGlobalGids); 9937 9938 final int N = pkg.requestedPermissions.size(); 9939 for (int i=0; i<N; i++) { 9940 final String name = pkg.requestedPermissions.get(i); 9941 final BasePermission bp = mSettings.mPermissions.get(name); 9942 9943 if (DEBUG_INSTALL) { 9944 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9945 } 9946 9947 if (bp == null || bp.packageSetting == null) { 9948 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9949 Slog.w(TAG, "Unknown permission " + name 9950 + " in package " + pkg.packageName); 9951 } 9952 continue; 9953 } 9954 9955 final String perm = bp.name; 9956 boolean allowedSig = false; 9957 int grant = GRANT_DENIED; 9958 9959 // Keep track of app op permissions. 9960 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9961 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9962 if (pkgs == null) { 9963 pkgs = new ArraySet<>(); 9964 mAppOpPermissionPackages.put(bp.name, pkgs); 9965 } 9966 pkgs.add(pkg.packageName); 9967 } 9968 9969 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9970 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9971 >= Build.VERSION_CODES.M; 9972 switch (level) { 9973 case PermissionInfo.PROTECTION_NORMAL: { 9974 // For all apps normal permissions are install time ones. 9975 grant = GRANT_INSTALL; 9976 } break; 9977 9978 case PermissionInfo.PROTECTION_DANGEROUS: { 9979 // If a permission review is required for legacy apps we represent 9980 // their permissions as always granted runtime ones since we need 9981 // to keep the review required permission flag per user while an 9982 // install permission's state is shared across all users. 9983 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired 9984 && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9985 // For legacy apps dangerous permissions are install time ones. 9986 grant = GRANT_INSTALL; 9987 } else if (origPermissions.hasInstallPermission(bp.name)) { 9988 // For legacy apps that became modern, install becomes runtime. 9989 grant = GRANT_UPGRADE; 9990 } else if (mPromoteSystemApps 9991 && isSystemApp(ps) 9992 && mExistingSystemPackages.contains(ps.name)) { 9993 // For legacy system apps, install becomes runtime. 9994 // We cannot check hasInstallPermission() for system apps since those 9995 // permissions were granted implicitly and not persisted pre-M. 9996 grant = GRANT_UPGRADE; 9997 } else { 9998 // For modern apps keep runtime permissions unchanged. 9999 grant = GRANT_RUNTIME; 10000 } 10001 } break; 10002 10003 case PermissionInfo.PROTECTION_SIGNATURE: { 10004 // For all apps signature permissions are install time ones. 10005 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10006 if (allowedSig) { 10007 grant = GRANT_INSTALL; 10008 } 10009 } break; 10010 } 10011 10012 if (DEBUG_INSTALL) { 10013 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10014 } 10015 10016 if (grant != GRANT_DENIED) { 10017 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10018 // If this is an existing, non-system package, then 10019 // we can't add any new permissions to it. 10020 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10021 // Except... if this is a permission that was added 10022 // to the platform (note: need to only do this when 10023 // updating the platform). 10024 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10025 grant = GRANT_DENIED; 10026 } 10027 } 10028 } 10029 10030 switch (grant) { 10031 case GRANT_INSTALL: { 10032 // Revoke this as runtime permission to handle the case of 10033 // a runtime permission being downgraded to an install one. 10034 // Also in permission review mode we keep dangerous permissions 10035 // for legacy apps 10036 for (int userId : UserManagerService.getInstance().getUserIds()) { 10037 if (origPermissions.getRuntimePermissionState( 10038 bp.name, userId) != null) { 10039 // Revoke the runtime permission and clear the flags. 10040 origPermissions.revokeRuntimePermission(bp, userId); 10041 origPermissions.updatePermissionFlags(bp, userId, 10042 PackageManager.MASK_PERMISSION_FLAGS, 0); 10043 // If we revoked a permission permission, we have to write. 10044 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10045 changedRuntimePermissionUserIds, userId); 10046 } 10047 } 10048 // Grant an install permission. 10049 if (permissionsState.grantInstallPermission(bp) != 10050 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10051 changedInstallPermission = true; 10052 } 10053 } break; 10054 10055 case GRANT_RUNTIME: { 10056 // Grant previously granted runtime permissions. 10057 for (int userId : UserManagerService.getInstance().getUserIds()) { 10058 PermissionState permissionState = origPermissions 10059 .getRuntimePermissionState(bp.name, userId); 10060 int flags = permissionState != null 10061 ? permissionState.getFlags() : 0; 10062 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10063 if (permissionsState.grantRuntimePermission(bp, userId) == 10064 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10065 // If we cannot put the permission as it was, we have to write. 10066 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10067 changedRuntimePermissionUserIds, userId); 10068 } 10069 // If the app supports runtime permissions no need for a review. 10070 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) 10071 && appSupportsRuntimePermissions 10072 && (flags & PackageManager 10073 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10074 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10075 // Since we changed the flags, we have to write. 10076 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10077 changedRuntimePermissionUserIds, userId); 10078 } 10079 } else if ((mPermissionReviewRequired 10080 || Build.PERMISSIONS_REVIEW_REQUIRED) 10081 && !appSupportsRuntimePermissions) { 10082 // For legacy apps that need a permission review, every new 10083 // runtime permission is granted but it is pending a review. 10084 // We also need to review only platform defined runtime 10085 // permissions as these are the only ones the platform knows 10086 // how to disable the API to simulate revocation as legacy 10087 // apps don't expect to run with revoked permissions. 10088 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10089 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10090 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10091 // We changed the flags, hence have to write. 10092 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10093 changedRuntimePermissionUserIds, userId); 10094 } 10095 } 10096 if (permissionsState.grantRuntimePermission(bp, userId) 10097 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10098 // We changed the permission, hence have to write. 10099 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10100 changedRuntimePermissionUserIds, userId); 10101 } 10102 } 10103 // Propagate the permission flags. 10104 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10105 } 10106 } break; 10107 10108 case GRANT_UPGRADE: { 10109 // Grant runtime permissions for a previously held install permission. 10110 PermissionState permissionState = origPermissions 10111 .getInstallPermissionState(bp.name); 10112 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10113 10114 if (origPermissions.revokeInstallPermission(bp) 10115 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10116 // We will be transferring the permission flags, so clear them. 10117 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10118 PackageManager.MASK_PERMISSION_FLAGS, 0); 10119 changedInstallPermission = true; 10120 } 10121 10122 // If the permission is not to be promoted to runtime we ignore it and 10123 // also its other flags as they are not applicable to install permissions. 10124 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10125 for (int userId : currentUserIds) { 10126 if (permissionsState.grantRuntimePermission(bp, userId) != 10127 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10128 // Transfer the permission flags. 10129 permissionsState.updatePermissionFlags(bp, userId, 10130 flags, flags); 10131 // If we granted the permission, we have to write. 10132 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10133 changedRuntimePermissionUserIds, userId); 10134 } 10135 } 10136 } 10137 } break; 10138 10139 default: { 10140 if (packageOfInterest == null 10141 || packageOfInterest.equals(pkg.packageName)) { 10142 Slog.w(TAG, "Not granting permission " + perm 10143 + " to package " + pkg.packageName 10144 + " because it was previously installed without"); 10145 } 10146 } break; 10147 } 10148 } else { 10149 if (permissionsState.revokeInstallPermission(bp) != 10150 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10151 // Also drop the permission flags. 10152 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10153 PackageManager.MASK_PERMISSION_FLAGS, 0); 10154 changedInstallPermission = true; 10155 Slog.i(TAG, "Un-granting permission " + perm 10156 + " from package " + pkg.packageName 10157 + " (protectionLevel=" + bp.protectionLevel 10158 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10159 + ")"); 10160 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10161 // Don't print warning for app op permissions, since it is fine for them 10162 // not to be granted, there is a UI for the user to decide. 10163 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10164 Slog.w(TAG, "Not granting permission " + perm 10165 + " to package " + pkg.packageName 10166 + " (protectionLevel=" + bp.protectionLevel 10167 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10168 + ")"); 10169 } 10170 } 10171 } 10172 } 10173 10174 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10175 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10176 // This is the first that we have heard about this package, so the 10177 // permissions we have now selected are fixed until explicitly 10178 // changed. 10179 ps.installPermissionsFixed = true; 10180 } 10181 10182 // Persist the runtime permissions state for users with changes. If permissions 10183 // were revoked because no app in the shared user declares them we have to 10184 // write synchronously to avoid losing runtime permissions state. 10185 for (int userId : changedRuntimePermissionUserIds) { 10186 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10187 } 10188 10189 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10190 } 10191 10192 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10193 boolean allowed = false; 10194 final int NP = PackageParser.NEW_PERMISSIONS.length; 10195 for (int ip=0; ip<NP; ip++) { 10196 final PackageParser.NewPermissionInfo npi 10197 = PackageParser.NEW_PERMISSIONS[ip]; 10198 if (npi.name.equals(perm) 10199 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10200 allowed = true; 10201 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10202 + pkg.packageName); 10203 break; 10204 } 10205 } 10206 return allowed; 10207 } 10208 10209 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10210 BasePermission bp, PermissionsState origPermissions) { 10211 boolean allowed; 10212 allowed = (compareSignatures( 10213 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10214 == PackageManager.SIGNATURE_MATCH) 10215 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10216 == PackageManager.SIGNATURE_MATCH); 10217 if (!allowed && (bp.protectionLevel 10218 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10219 if (isSystemApp(pkg)) { 10220 // For updated system applications, a system permission 10221 // is granted only if it had been defined by the original application. 10222 if (pkg.isUpdatedSystemApp()) { 10223 final PackageSetting sysPs = mSettings 10224 .getDisabledSystemPkgLPr(pkg.packageName); 10225 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10226 // If the original was granted this permission, we take 10227 // that grant decision as read and propagate it to the 10228 // update. 10229 if (sysPs.isPrivileged()) { 10230 allowed = true; 10231 } 10232 } else { 10233 // The system apk may have been updated with an older 10234 // version of the one on the data partition, but which 10235 // granted a new system permission that it didn't have 10236 // before. In this case we do want to allow the app to 10237 // now get the new permission if the ancestral apk is 10238 // privileged to get it. 10239 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10240 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10241 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10242 allowed = true; 10243 break; 10244 } 10245 } 10246 } 10247 // Also if a privileged parent package on the system image or any of 10248 // its children requested a privileged permission, the updated child 10249 // packages can also get the permission. 10250 if (pkg.parentPackage != null) { 10251 final PackageSetting disabledSysParentPs = mSettings 10252 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10253 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10254 && disabledSysParentPs.isPrivileged()) { 10255 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10256 allowed = true; 10257 } else if (disabledSysParentPs.pkg.childPackages != null) { 10258 final int count = disabledSysParentPs.pkg.childPackages.size(); 10259 for (int i = 0; i < count; i++) { 10260 PackageParser.Package disabledSysChildPkg = 10261 disabledSysParentPs.pkg.childPackages.get(i); 10262 if (isPackageRequestingPermission(disabledSysChildPkg, 10263 perm)) { 10264 allowed = true; 10265 break; 10266 } 10267 } 10268 } 10269 } 10270 } 10271 } 10272 } else { 10273 allowed = isPrivilegedApp(pkg); 10274 } 10275 } 10276 } 10277 if (!allowed) { 10278 if (!allowed && (bp.protectionLevel 10279 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10280 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10281 // If this was a previously normal/dangerous permission that got moved 10282 // to a system permission as part of the runtime permission redesign, then 10283 // we still want to blindly grant it to old apps. 10284 allowed = true; 10285 } 10286 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10287 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10288 // If this permission is to be granted to the system installer and 10289 // this app is an installer, then it gets the permission. 10290 allowed = true; 10291 } 10292 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10293 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10294 // If this permission is to be granted to the system verifier and 10295 // this app is a verifier, then it gets the permission. 10296 allowed = true; 10297 } 10298 if (!allowed && (bp.protectionLevel 10299 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10300 && isSystemApp(pkg)) { 10301 // Any pre-installed system app is allowed to get this permission. 10302 allowed = true; 10303 } 10304 if (!allowed && (bp.protectionLevel 10305 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10306 // For development permissions, a development permission 10307 // is granted only if it was already granted. 10308 allowed = origPermissions.hasInstallPermission(perm); 10309 } 10310 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10311 && pkg.packageName.equals(mSetupWizardPackage)) { 10312 // If this permission is to be granted to the system setup wizard and 10313 // this app is a setup wizard, then it gets the permission. 10314 allowed = true; 10315 } 10316 } 10317 return allowed; 10318 } 10319 10320 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10321 final int permCount = pkg.requestedPermissions.size(); 10322 for (int j = 0; j < permCount; j++) { 10323 String requestedPermission = pkg.requestedPermissions.get(j); 10324 if (permission.equals(requestedPermission)) { 10325 return true; 10326 } 10327 } 10328 return false; 10329 } 10330 10331 final class ActivityIntentResolver 10332 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10333 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10334 boolean defaultOnly, int userId) { 10335 if (!sUserManager.exists(userId)) return null; 10336 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10337 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10338 } 10339 10340 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10341 int userId) { 10342 if (!sUserManager.exists(userId)) return null; 10343 mFlags = flags; 10344 return super.queryIntent(intent, resolvedType, 10345 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10346 } 10347 10348 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10349 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10350 if (!sUserManager.exists(userId)) return null; 10351 if (packageActivities == null) { 10352 return null; 10353 } 10354 mFlags = flags; 10355 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10356 final int N = packageActivities.size(); 10357 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10358 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10359 10360 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10361 for (int i = 0; i < N; ++i) { 10362 intentFilters = packageActivities.get(i).intents; 10363 if (intentFilters != null && intentFilters.size() > 0) { 10364 PackageParser.ActivityIntentInfo[] array = 10365 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10366 intentFilters.toArray(array); 10367 listCut.add(array); 10368 } 10369 } 10370 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10371 } 10372 10373 /** 10374 * Finds a privileged activity that matches the specified activity names. 10375 */ 10376 private PackageParser.Activity findMatchingActivity( 10377 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10378 for (PackageParser.Activity sysActivity : activityList) { 10379 if (sysActivity.info.name.equals(activityInfo.name)) { 10380 return sysActivity; 10381 } 10382 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10383 return sysActivity; 10384 } 10385 if (sysActivity.info.targetActivity != null) { 10386 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10387 return sysActivity; 10388 } 10389 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10390 return sysActivity; 10391 } 10392 } 10393 } 10394 return null; 10395 } 10396 10397 public class IterGenerator<E> { 10398 public Iterator<E> generate(ActivityIntentInfo info) { 10399 return null; 10400 } 10401 } 10402 10403 public class ActionIterGenerator extends IterGenerator<String> { 10404 @Override 10405 public Iterator<String> generate(ActivityIntentInfo info) { 10406 return info.actionsIterator(); 10407 } 10408 } 10409 10410 public class CategoriesIterGenerator extends IterGenerator<String> { 10411 @Override 10412 public Iterator<String> generate(ActivityIntentInfo info) { 10413 return info.categoriesIterator(); 10414 } 10415 } 10416 10417 public class SchemesIterGenerator extends IterGenerator<String> { 10418 @Override 10419 public Iterator<String> generate(ActivityIntentInfo info) { 10420 return info.schemesIterator(); 10421 } 10422 } 10423 10424 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10425 @Override 10426 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10427 return info.authoritiesIterator(); 10428 } 10429 } 10430 10431 /** 10432 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10433 * MODIFIED. Do not pass in a list that should not be changed. 10434 */ 10435 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10436 IterGenerator<T> generator, Iterator<T> searchIterator) { 10437 // loop through the set of actions; every one must be found in the intent filter 10438 while (searchIterator.hasNext()) { 10439 // we must have at least one filter in the list to consider a match 10440 if (intentList.size() == 0) { 10441 break; 10442 } 10443 10444 final T searchAction = searchIterator.next(); 10445 10446 // loop through the set of intent filters 10447 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10448 while (intentIter.hasNext()) { 10449 final ActivityIntentInfo intentInfo = intentIter.next(); 10450 boolean selectionFound = false; 10451 10452 // loop through the intent filter's selection criteria; at least one 10453 // of them must match the searched criteria 10454 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10455 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10456 final T intentSelection = intentSelectionIter.next(); 10457 if (intentSelection != null && intentSelection.equals(searchAction)) { 10458 selectionFound = true; 10459 break; 10460 } 10461 } 10462 10463 // the selection criteria wasn't found in this filter's set; this filter 10464 // is not a potential match 10465 if (!selectionFound) { 10466 intentIter.remove(); 10467 } 10468 } 10469 } 10470 } 10471 10472 private boolean isProtectedAction(ActivityIntentInfo filter) { 10473 final Iterator<String> actionsIter = filter.actionsIterator(); 10474 while (actionsIter != null && actionsIter.hasNext()) { 10475 final String filterAction = actionsIter.next(); 10476 if (PROTECTED_ACTIONS.contains(filterAction)) { 10477 return true; 10478 } 10479 } 10480 return false; 10481 } 10482 10483 /** 10484 * Adjusts the priority of the given intent filter according to policy. 10485 * <p> 10486 * <ul> 10487 * <li>The priority for non privileged applications is capped to '0'</li> 10488 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10489 * <li>The priority for unbundled updates to privileged applications is capped to the 10490 * priority defined on the system partition</li> 10491 * </ul> 10492 * <p> 10493 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10494 * allowed to obtain any priority on any action. 10495 */ 10496 private void adjustPriority( 10497 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10498 // nothing to do; priority is fine as-is 10499 if (intent.getPriority() <= 0) { 10500 return; 10501 } 10502 10503 final ActivityInfo activityInfo = intent.activity.info; 10504 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10505 10506 final boolean privilegedApp = 10507 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10508 if (!privilegedApp) { 10509 // non-privileged applications can never define a priority >0 10510 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10511 + " package: " + applicationInfo.packageName 10512 + " activity: " + intent.activity.className 10513 + " origPrio: " + intent.getPriority()); 10514 intent.setPriority(0); 10515 return; 10516 } 10517 10518 if (systemActivities == null) { 10519 // the system package is not disabled; we're parsing the system partition 10520 if (isProtectedAction(intent)) { 10521 if (mDeferProtectedFilters) { 10522 // We can't deal with these just yet. No component should ever obtain a 10523 // >0 priority for a protected actions, with ONE exception -- the setup 10524 // wizard. The setup wizard, however, cannot be known until we're able to 10525 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10526 // until all intent filters have been processed. Chicken, meet egg. 10527 // Let the filter temporarily have a high priority and rectify the 10528 // priorities after all system packages have been scanned. 10529 mProtectedFilters.add(intent); 10530 if (DEBUG_FILTERS) { 10531 Slog.i(TAG, "Protected action; save for later;" 10532 + " package: " + applicationInfo.packageName 10533 + " activity: " + intent.activity.className 10534 + " origPrio: " + intent.getPriority()); 10535 } 10536 return; 10537 } else { 10538 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10539 Slog.i(TAG, "No setup wizard;" 10540 + " All protected intents capped to priority 0"); 10541 } 10542 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10543 if (DEBUG_FILTERS) { 10544 Slog.i(TAG, "Found setup wizard;" 10545 + " allow priority " + intent.getPriority() + ";" 10546 + " package: " + intent.activity.info.packageName 10547 + " activity: " + intent.activity.className 10548 + " priority: " + intent.getPriority()); 10549 } 10550 // setup wizard gets whatever it wants 10551 return; 10552 } 10553 Slog.w(TAG, "Protected action; cap priority to 0;" 10554 + " package: " + intent.activity.info.packageName 10555 + " activity: " + intent.activity.className 10556 + " origPrio: " + intent.getPriority()); 10557 intent.setPriority(0); 10558 return; 10559 } 10560 } 10561 // privileged apps on the system image get whatever priority they request 10562 return; 10563 } 10564 10565 // privileged app unbundled update ... try to find the same activity 10566 final PackageParser.Activity foundActivity = 10567 findMatchingActivity(systemActivities, activityInfo); 10568 if (foundActivity == null) { 10569 // this is a new activity; it cannot obtain >0 priority 10570 if (DEBUG_FILTERS) { 10571 Slog.i(TAG, "New activity; cap priority to 0;" 10572 + " package: " + applicationInfo.packageName 10573 + " activity: " + intent.activity.className 10574 + " origPrio: " + intent.getPriority()); 10575 } 10576 intent.setPriority(0); 10577 return; 10578 } 10579 10580 // found activity, now check for filter equivalence 10581 10582 // a shallow copy is enough; we modify the list, not its contents 10583 final List<ActivityIntentInfo> intentListCopy = 10584 new ArrayList<>(foundActivity.intents); 10585 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10586 10587 // find matching action subsets 10588 final Iterator<String> actionsIterator = intent.actionsIterator(); 10589 if (actionsIterator != null) { 10590 getIntentListSubset( 10591 intentListCopy, new ActionIterGenerator(), actionsIterator); 10592 if (intentListCopy.size() == 0) { 10593 // no more intents to match; we're not equivalent 10594 if (DEBUG_FILTERS) { 10595 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10596 + " package: " + applicationInfo.packageName 10597 + " activity: " + intent.activity.className 10598 + " origPrio: " + intent.getPriority()); 10599 } 10600 intent.setPriority(0); 10601 return; 10602 } 10603 } 10604 10605 // find matching category subsets 10606 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10607 if (categoriesIterator != null) { 10608 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10609 categoriesIterator); 10610 if (intentListCopy.size() == 0) { 10611 // no more intents to match; we're not equivalent 10612 if (DEBUG_FILTERS) { 10613 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10614 + " package: " + applicationInfo.packageName 10615 + " activity: " + intent.activity.className 10616 + " origPrio: " + intent.getPriority()); 10617 } 10618 intent.setPriority(0); 10619 return; 10620 } 10621 } 10622 10623 // find matching schemes subsets 10624 final Iterator<String> schemesIterator = intent.schemesIterator(); 10625 if (schemesIterator != null) { 10626 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10627 schemesIterator); 10628 if (intentListCopy.size() == 0) { 10629 // no more intents to match; we're not equivalent 10630 if (DEBUG_FILTERS) { 10631 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10632 + " package: " + applicationInfo.packageName 10633 + " activity: " + intent.activity.className 10634 + " origPrio: " + intent.getPriority()); 10635 } 10636 intent.setPriority(0); 10637 return; 10638 } 10639 } 10640 10641 // find matching authorities subsets 10642 final Iterator<IntentFilter.AuthorityEntry> 10643 authoritiesIterator = intent.authoritiesIterator(); 10644 if (authoritiesIterator != null) { 10645 getIntentListSubset(intentListCopy, 10646 new AuthoritiesIterGenerator(), 10647 authoritiesIterator); 10648 if (intentListCopy.size() == 0) { 10649 // no more intents to match; we're not equivalent 10650 if (DEBUG_FILTERS) { 10651 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10652 + " package: " + applicationInfo.packageName 10653 + " activity: " + intent.activity.className 10654 + " origPrio: " + intent.getPriority()); 10655 } 10656 intent.setPriority(0); 10657 return; 10658 } 10659 } 10660 10661 // we found matching filter(s); app gets the max priority of all intents 10662 int cappedPriority = 0; 10663 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10664 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10665 } 10666 if (intent.getPriority() > cappedPriority) { 10667 if (DEBUG_FILTERS) { 10668 Slog.i(TAG, "Found matching filter(s);" 10669 + " cap priority to " + cappedPriority + ";" 10670 + " package: " + applicationInfo.packageName 10671 + " activity: " + intent.activity.className 10672 + " origPrio: " + intent.getPriority()); 10673 } 10674 intent.setPriority(cappedPriority); 10675 return; 10676 } 10677 // all this for nothing; the requested priority was <= what was on the system 10678 } 10679 10680 public final void addActivity(PackageParser.Activity a, String type) { 10681 mActivities.put(a.getComponentName(), a); 10682 if (DEBUG_SHOW_INFO) 10683 Log.v( 10684 TAG, " " + type + " " + 10685 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10686 if (DEBUG_SHOW_INFO) 10687 Log.v(TAG, " Class=" + a.info.name); 10688 final int NI = a.intents.size(); 10689 for (int j=0; j<NI; j++) { 10690 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10691 if ("activity".equals(type)) { 10692 final PackageSetting ps = 10693 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10694 final List<PackageParser.Activity> systemActivities = 10695 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10696 adjustPriority(systemActivities, intent); 10697 } 10698 if (DEBUG_SHOW_INFO) { 10699 Log.v(TAG, " IntentFilter:"); 10700 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10701 } 10702 if (!intent.debugCheck()) { 10703 Log.w(TAG, "==> For Activity " + a.info.name); 10704 } 10705 addFilter(intent); 10706 } 10707 } 10708 10709 public final void removeActivity(PackageParser.Activity a, String type) { 10710 mActivities.remove(a.getComponentName()); 10711 if (DEBUG_SHOW_INFO) { 10712 Log.v(TAG, " " + type + " " 10713 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10714 : a.info.name) + ":"); 10715 Log.v(TAG, " Class=" + a.info.name); 10716 } 10717 final int NI = a.intents.size(); 10718 for (int j=0; j<NI; j++) { 10719 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10720 if (DEBUG_SHOW_INFO) { 10721 Log.v(TAG, " IntentFilter:"); 10722 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10723 } 10724 removeFilter(intent); 10725 } 10726 } 10727 10728 @Override 10729 protected boolean allowFilterResult( 10730 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10731 ActivityInfo filterAi = filter.activity.info; 10732 for (int i=dest.size()-1; i>=0; i--) { 10733 ActivityInfo destAi = dest.get(i).activityInfo; 10734 if (destAi.name == filterAi.name 10735 && destAi.packageName == filterAi.packageName) { 10736 return false; 10737 } 10738 } 10739 return true; 10740 } 10741 10742 @Override 10743 protected ActivityIntentInfo[] newArray(int size) { 10744 return new ActivityIntentInfo[size]; 10745 } 10746 10747 @Override 10748 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10749 if (!sUserManager.exists(userId)) return true; 10750 PackageParser.Package p = filter.activity.owner; 10751 if (p != null) { 10752 PackageSetting ps = (PackageSetting)p.mExtras; 10753 if (ps != null) { 10754 // System apps are never considered stopped for purposes of 10755 // filtering, because there may be no way for the user to 10756 // actually re-launch them. 10757 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10758 && ps.getStopped(userId); 10759 } 10760 } 10761 return false; 10762 } 10763 10764 @Override 10765 protected boolean isPackageForFilter(String packageName, 10766 PackageParser.ActivityIntentInfo info) { 10767 return packageName.equals(info.activity.owner.packageName); 10768 } 10769 10770 @Override 10771 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10772 int match, int userId) { 10773 if (!sUserManager.exists(userId)) return null; 10774 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10775 return null; 10776 } 10777 final PackageParser.Activity activity = info.activity; 10778 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10779 if (ps == null) { 10780 return null; 10781 } 10782 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10783 ps.readUserState(userId), userId); 10784 if (ai == null) { 10785 return null; 10786 } 10787 final ResolveInfo res = new ResolveInfo(); 10788 res.activityInfo = ai; 10789 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10790 res.filter = info; 10791 } 10792 if (info != null) { 10793 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10794 } 10795 res.priority = info.getPriority(); 10796 res.preferredOrder = activity.owner.mPreferredOrder; 10797 //System.out.println("Result: " + res.activityInfo.className + 10798 // " = " + res.priority); 10799 res.match = match; 10800 res.isDefault = info.hasDefault; 10801 res.labelRes = info.labelRes; 10802 res.nonLocalizedLabel = info.nonLocalizedLabel; 10803 if (userNeedsBadging(userId)) { 10804 res.noResourceId = true; 10805 } else { 10806 res.icon = info.icon; 10807 } 10808 res.iconResourceId = info.icon; 10809 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10810 return res; 10811 } 10812 10813 @Override 10814 protected void sortResults(List<ResolveInfo> results) { 10815 Collections.sort(results, mResolvePrioritySorter); 10816 } 10817 10818 @Override 10819 protected void dumpFilter(PrintWriter out, String prefix, 10820 PackageParser.ActivityIntentInfo filter) { 10821 out.print(prefix); out.print( 10822 Integer.toHexString(System.identityHashCode(filter.activity))); 10823 out.print(' '); 10824 filter.activity.printComponentShortName(out); 10825 out.print(" filter "); 10826 out.println(Integer.toHexString(System.identityHashCode(filter))); 10827 } 10828 10829 @Override 10830 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10831 return filter.activity; 10832 } 10833 10834 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10835 PackageParser.Activity activity = (PackageParser.Activity)label; 10836 out.print(prefix); out.print( 10837 Integer.toHexString(System.identityHashCode(activity))); 10838 out.print(' '); 10839 activity.printComponentShortName(out); 10840 if (count > 1) { 10841 out.print(" ("); out.print(count); out.print(" filters)"); 10842 } 10843 out.println(); 10844 } 10845 10846 // Keys are String (activity class name), values are Activity. 10847 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10848 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10849 private int mFlags; 10850 } 10851 10852 private final class ServiceIntentResolver 10853 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10854 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10855 boolean defaultOnly, int userId) { 10856 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10857 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10858 } 10859 10860 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10861 int userId) { 10862 if (!sUserManager.exists(userId)) return null; 10863 mFlags = flags; 10864 return super.queryIntent(intent, resolvedType, 10865 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10866 } 10867 10868 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10869 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10870 if (!sUserManager.exists(userId)) return null; 10871 if (packageServices == null) { 10872 return null; 10873 } 10874 mFlags = flags; 10875 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10876 final int N = packageServices.size(); 10877 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10878 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10879 10880 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10881 for (int i = 0; i < N; ++i) { 10882 intentFilters = packageServices.get(i).intents; 10883 if (intentFilters != null && intentFilters.size() > 0) { 10884 PackageParser.ServiceIntentInfo[] array = 10885 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10886 intentFilters.toArray(array); 10887 listCut.add(array); 10888 } 10889 } 10890 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10891 } 10892 10893 public final void addService(PackageParser.Service s) { 10894 mServices.put(s.getComponentName(), s); 10895 if (DEBUG_SHOW_INFO) { 10896 Log.v(TAG, " " 10897 + (s.info.nonLocalizedLabel != null 10898 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10899 Log.v(TAG, " Class=" + s.info.name); 10900 } 10901 final int NI = s.intents.size(); 10902 int j; 10903 for (j=0; j<NI; j++) { 10904 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10905 if (DEBUG_SHOW_INFO) { 10906 Log.v(TAG, " IntentFilter:"); 10907 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10908 } 10909 if (!intent.debugCheck()) { 10910 Log.w(TAG, "==> For Service " + s.info.name); 10911 } 10912 addFilter(intent); 10913 } 10914 } 10915 10916 public final void removeService(PackageParser.Service s) { 10917 mServices.remove(s.getComponentName()); 10918 if (DEBUG_SHOW_INFO) { 10919 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10920 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10921 Log.v(TAG, " Class=" + s.info.name); 10922 } 10923 final int NI = s.intents.size(); 10924 int j; 10925 for (j=0; j<NI; j++) { 10926 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10927 if (DEBUG_SHOW_INFO) { 10928 Log.v(TAG, " IntentFilter:"); 10929 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10930 } 10931 removeFilter(intent); 10932 } 10933 } 10934 10935 @Override 10936 protected boolean allowFilterResult( 10937 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10938 ServiceInfo filterSi = filter.service.info; 10939 for (int i=dest.size()-1; i>=0; i--) { 10940 ServiceInfo destAi = dest.get(i).serviceInfo; 10941 if (destAi.name == filterSi.name 10942 && destAi.packageName == filterSi.packageName) { 10943 return false; 10944 } 10945 } 10946 return true; 10947 } 10948 10949 @Override 10950 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10951 return new PackageParser.ServiceIntentInfo[size]; 10952 } 10953 10954 @Override 10955 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10956 if (!sUserManager.exists(userId)) return true; 10957 PackageParser.Package p = filter.service.owner; 10958 if (p != null) { 10959 PackageSetting ps = (PackageSetting)p.mExtras; 10960 if (ps != null) { 10961 // System apps are never considered stopped for purposes of 10962 // filtering, because there may be no way for the user to 10963 // actually re-launch them. 10964 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10965 && ps.getStopped(userId); 10966 } 10967 } 10968 return false; 10969 } 10970 10971 @Override 10972 protected boolean isPackageForFilter(String packageName, 10973 PackageParser.ServiceIntentInfo info) { 10974 return packageName.equals(info.service.owner.packageName); 10975 } 10976 10977 @Override 10978 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10979 int match, int userId) { 10980 if (!sUserManager.exists(userId)) return null; 10981 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10982 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10983 return null; 10984 } 10985 final PackageParser.Service service = info.service; 10986 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10987 if (ps == null) { 10988 return null; 10989 } 10990 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10991 ps.readUserState(userId), userId); 10992 if (si == null) { 10993 return null; 10994 } 10995 final ResolveInfo res = new ResolveInfo(); 10996 res.serviceInfo = si; 10997 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10998 res.filter = filter; 10999 } 11000 res.priority = info.getPriority(); 11001 res.preferredOrder = service.owner.mPreferredOrder; 11002 res.match = match; 11003 res.isDefault = info.hasDefault; 11004 res.labelRes = info.labelRes; 11005 res.nonLocalizedLabel = info.nonLocalizedLabel; 11006 res.icon = info.icon; 11007 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11008 return res; 11009 } 11010 11011 @Override 11012 protected void sortResults(List<ResolveInfo> results) { 11013 Collections.sort(results, mResolvePrioritySorter); 11014 } 11015 11016 @Override 11017 protected void dumpFilter(PrintWriter out, String prefix, 11018 PackageParser.ServiceIntentInfo filter) { 11019 out.print(prefix); out.print( 11020 Integer.toHexString(System.identityHashCode(filter.service))); 11021 out.print(' '); 11022 filter.service.printComponentShortName(out); 11023 out.print(" filter "); 11024 out.println(Integer.toHexString(System.identityHashCode(filter))); 11025 } 11026 11027 @Override 11028 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11029 return filter.service; 11030 } 11031 11032 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11033 PackageParser.Service service = (PackageParser.Service)label; 11034 out.print(prefix); out.print( 11035 Integer.toHexString(System.identityHashCode(service))); 11036 out.print(' '); 11037 service.printComponentShortName(out); 11038 if (count > 1) { 11039 out.print(" ("); out.print(count); out.print(" filters)"); 11040 } 11041 out.println(); 11042 } 11043 11044// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11045// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11046// final List<ResolveInfo> retList = Lists.newArrayList(); 11047// while (i.hasNext()) { 11048// final ResolveInfo resolveInfo = (ResolveInfo) i; 11049// if (isEnabledLP(resolveInfo.serviceInfo)) { 11050// retList.add(resolveInfo); 11051// } 11052// } 11053// return retList; 11054// } 11055 11056 // Keys are String (activity class name), values are Activity. 11057 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11058 = new ArrayMap<ComponentName, PackageParser.Service>(); 11059 private int mFlags; 11060 }; 11061 11062 private final class ProviderIntentResolver 11063 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11064 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11065 boolean defaultOnly, int userId) { 11066 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11067 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11068 } 11069 11070 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11071 int userId) { 11072 if (!sUserManager.exists(userId)) 11073 return null; 11074 mFlags = flags; 11075 return super.queryIntent(intent, resolvedType, 11076 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11077 } 11078 11079 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11080 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11081 if (!sUserManager.exists(userId)) 11082 return null; 11083 if (packageProviders == null) { 11084 return null; 11085 } 11086 mFlags = flags; 11087 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11088 final int N = packageProviders.size(); 11089 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11090 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11091 11092 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11093 for (int i = 0; i < N; ++i) { 11094 intentFilters = packageProviders.get(i).intents; 11095 if (intentFilters != null && intentFilters.size() > 0) { 11096 PackageParser.ProviderIntentInfo[] array = 11097 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11098 intentFilters.toArray(array); 11099 listCut.add(array); 11100 } 11101 } 11102 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11103 } 11104 11105 public final void addProvider(PackageParser.Provider p) { 11106 if (mProviders.containsKey(p.getComponentName())) { 11107 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11108 return; 11109 } 11110 11111 mProviders.put(p.getComponentName(), p); 11112 if (DEBUG_SHOW_INFO) { 11113 Log.v(TAG, " " 11114 + (p.info.nonLocalizedLabel != null 11115 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11116 Log.v(TAG, " Class=" + p.info.name); 11117 } 11118 final int NI = p.intents.size(); 11119 int j; 11120 for (j = 0; j < NI; j++) { 11121 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11122 if (DEBUG_SHOW_INFO) { 11123 Log.v(TAG, " IntentFilter:"); 11124 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11125 } 11126 if (!intent.debugCheck()) { 11127 Log.w(TAG, "==> For Provider " + p.info.name); 11128 } 11129 addFilter(intent); 11130 } 11131 } 11132 11133 public final void removeProvider(PackageParser.Provider p) { 11134 mProviders.remove(p.getComponentName()); 11135 if (DEBUG_SHOW_INFO) { 11136 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11137 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11138 Log.v(TAG, " Class=" + p.info.name); 11139 } 11140 final int NI = p.intents.size(); 11141 int j; 11142 for (j = 0; j < NI; j++) { 11143 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11144 if (DEBUG_SHOW_INFO) { 11145 Log.v(TAG, " IntentFilter:"); 11146 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11147 } 11148 removeFilter(intent); 11149 } 11150 } 11151 11152 @Override 11153 protected boolean allowFilterResult( 11154 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11155 ProviderInfo filterPi = filter.provider.info; 11156 for (int i = dest.size() - 1; i >= 0; i--) { 11157 ProviderInfo destPi = dest.get(i).providerInfo; 11158 if (destPi.name == filterPi.name 11159 && destPi.packageName == filterPi.packageName) { 11160 return false; 11161 } 11162 } 11163 return true; 11164 } 11165 11166 @Override 11167 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11168 return new PackageParser.ProviderIntentInfo[size]; 11169 } 11170 11171 @Override 11172 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11173 if (!sUserManager.exists(userId)) 11174 return true; 11175 PackageParser.Package p = filter.provider.owner; 11176 if (p != null) { 11177 PackageSetting ps = (PackageSetting) p.mExtras; 11178 if (ps != null) { 11179 // System apps are never considered stopped for purposes of 11180 // filtering, because there may be no way for the user to 11181 // actually re-launch them. 11182 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11183 && ps.getStopped(userId); 11184 } 11185 } 11186 return false; 11187 } 11188 11189 @Override 11190 protected boolean isPackageForFilter(String packageName, 11191 PackageParser.ProviderIntentInfo info) { 11192 return packageName.equals(info.provider.owner.packageName); 11193 } 11194 11195 @Override 11196 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11197 int match, int userId) { 11198 if (!sUserManager.exists(userId)) 11199 return null; 11200 final PackageParser.ProviderIntentInfo info = filter; 11201 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11202 return null; 11203 } 11204 final PackageParser.Provider provider = info.provider; 11205 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11206 if (ps == null) { 11207 return null; 11208 } 11209 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11210 ps.readUserState(userId), userId); 11211 if (pi == null) { 11212 return null; 11213 } 11214 final ResolveInfo res = new ResolveInfo(); 11215 res.providerInfo = pi; 11216 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11217 res.filter = filter; 11218 } 11219 res.priority = info.getPriority(); 11220 res.preferredOrder = provider.owner.mPreferredOrder; 11221 res.match = match; 11222 res.isDefault = info.hasDefault; 11223 res.labelRes = info.labelRes; 11224 res.nonLocalizedLabel = info.nonLocalizedLabel; 11225 res.icon = info.icon; 11226 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11227 return res; 11228 } 11229 11230 @Override 11231 protected void sortResults(List<ResolveInfo> results) { 11232 Collections.sort(results, mResolvePrioritySorter); 11233 } 11234 11235 @Override 11236 protected void dumpFilter(PrintWriter out, String prefix, 11237 PackageParser.ProviderIntentInfo filter) { 11238 out.print(prefix); 11239 out.print( 11240 Integer.toHexString(System.identityHashCode(filter.provider))); 11241 out.print(' '); 11242 filter.provider.printComponentShortName(out); 11243 out.print(" filter "); 11244 out.println(Integer.toHexString(System.identityHashCode(filter))); 11245 } 11246 11247 @Override 11248 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11249 return filter.provider; 11250 } 11251 11252 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11253 PackageParser.Provider provider = (PackageParser.Provider)label; 11254 out.print(prefix); out.print( 11255 Integer.toHexString(System.identityHashCode(provider))); 11256 out.print(' '); 11257 provider.printComponentShortName(out); 11258 if (count > 1) { 11259 out.print(" ("); out.print(count); out.print(" filters)"); 11260 } 11261 out.println(); 11262 } 11263 11264 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11265 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11266 private int mFlags; 11267 } 11268 11269 private static final class EphemeralIntentResolver 11270 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11271 /** 11272 * The result that has the highest defined order. Ordering applies on a 11273 * per-package basis. Mapping is from package name to Pair of order and 11274 * EphemeralResolveInfo. 11275 * <p> 11276 * NOTE: This is implemented as a field variable for convenience and efficiency. 11277 * By having a field variable, we're able to track filter ordering as soon as 11278 * a non-zero order is defined. Otherwise, multiple loops across the result set 11279 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11280 * this needs to be contained entirely within {@link #filterResults()}. 11281 */ 11282 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11283 11284 @Override 11285 protected EphemeralResolveIntentInfo[] newArray(int size) { 11286 return new EphemeralResolveIntentInfo[size]; 11287 } 11288 11289 @Override 11290 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11291 return true; 11292 } 11293 11294 @Override 11295 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11296 int userId) { 11297 if (!sUserManager.exists(userId)) { 11298 return null; 11299 } 11300 final String packageName = info.getEphemeralResolveInfo().getPackageName(); 11301 final Integer order = info.getOrder(); 11302 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11303 mOrderResult.get(packageName); 11304 // ordering is enabled and this item's order isn't high enough 11305 if (lastOrderResult != null && lastOrderResult.first >= order) { 11306 return null; 11307 } 11308 final EphemeralResolveInfo res = info.getEphemeralResolveInfo(); 11309 if (order > 0) { 11310 // non-zero order, enable ordering 11311 mOrderResult.put(packageName, new Pair<>(order, res)); 11312 } 11313 return res; 11314 } 11315 11316 @Override 11317 protected void filterResults(List<EphemeralResolveInfo> results) { 11318 // only do work if ordering is enabled [most of the time it won't be] 11319 if (mOrderResult.size() == 0) { 11320 return; 11321 } 11322 int resultSize = results.size(); 11323 for (int i = 0; i < resultSize; i++) { 11324 final EphemeralResolveInfo info = results.get(i); 11325 final String packageName = info.getPackageName(); 11326 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11327 if (savedInfo == null) { 11328 // package doesn't having ordering 11329 continue; 11330 } 11331 if (savedInfo.second == info) { 11332 // circled back to the highest ordered item; remove from order list 11333 mOrderResult.remove(savedInfo); 11334 if (mOrderResult.size() == 0) { 11335 // no more ordered items 11336 break; 11337 } 11338 continue; 11339 } 11340 // item has a worse order, remove it from the result list 11341 results.remove(i); 11342 resultSize--; 11343 i--; 11344 } 11345 } 11346 } 11347 11348 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11349 new Comparator<ResolveInfo>() { 11350 public int compare(ResolveInfo r1, ResolveInfo r2) { 11351 int v1 = r1.priority; 11352 int v2 = r2.priority; 11353 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11354 if (v1 != v2) { 11355 return (v1 > v2) ? -1 : 1; 11356 } 11357 v1 = r1.preferredOrder; 11358 v2 = r2.preferredOrder; 11359 if (v1 != v2) { 11360 return (v1 > v2) ? -1 : 1; 11361 } 11362 if (r1.isDefault != r2.isDefault) { 11363 return r1.isDefault ? -1 : 1; 11364 } 11365 v1 = r1.match; 11366 v2 = r2.match; 11367 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11368 if (v1 != v2) { 11369 return (v1 > v2) ? -1 : 1; 11370 } 11371 if (r1.system != r2.system) { 11372 return r1.system ? -1 : 1; 11373 } 11374 if (r1.activityInfo != null) { 11375 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11376 } 11377 if (r1.serviceInfo != null) { 11378 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11379 } 11380 if (r1.providerInfo != null) { 11381 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11382 } 11383 return 0; 11384 } 11385 }; 11386 11387 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11388 new Comparator<ProviderInfo>() { 11389 public int compare(ProviderInfo p1, ProviderInfo p2) { 11390 final int v1 = p1.initOrder; 11391 final int v2 = p2.initOrder; 11392 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11393 } 11394 }; 11395 11396 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11397 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11398 final int[] userIds) { 11399 mHandler.post(new Runnable() { 11400 @Override 11401 public void run() { 11402 try { 11403 final IActivityManager am = ActivityManagerNative.getDefault(); 11404 if (am == null) return; 11405 final int[] resolvedUserIds; 11406 if (userIds == null) { 11407 resolvedUserIds = am.getRunningUserIds(); 11408 } else { 11409 resolvedUserIds = userIds; 11410 } 11411 for (int id : resolvedUserIds) { 11412 final Intent intent = new Intent(action, 11413 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11414 if (extras != null) { 11415 intent.putExtras(extras); 11416 } 11417 if (targetPkg != null) { 11418 intent.setPackage(targetPkg); 11419 } 11420 // Modify the UID when posting to other users 11421 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11422 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11423 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11424 intent.putExtra(Intent.EXTRA_UID, uid); 11425 } 11426 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11427 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11428 if (DEBUG_BROADCASTS) { 11429 RuntimeException here = new RuntimeException("here"); 11430 here.fillInStackTrace(); 11431 Slog.d(TAG, "Sending to user " + id + ": " 11432 + intent.toShortString(false, true, false, false) 11433 + " " + intent.getExtras(), here); 11434 } 11435 am.broadcastIntent(null, intent, null, finishedReceiver, 11436 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11437 null, finishedReceiver != null, false, id); 11438 } 11439 } catch (RemoteException ex) { 11440 } 11441 } 11442 }); 11443 } 11444 11445 /** 11446 * Check if the external storage media is available. This is true if there 11447 * is a mounted external storage medium or if the external storage is 11448 * emulated. 11449 */ 11450 private boolean isExternalMediaAvailable() { 11451 return mMediaMounted || Environment.isExternalStorageEmulated(); 11452 } 11453 11454 @Override 11455 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11456 // writer 11457 synchronized (mPackages) { 11458 if (!isExternalMediaAvailable()) { 11459 // If the external storage is no longer mounted at this point, 11460 // the caller may not have been able to delete all of this 11461 // packages files and can not delete any more. Bail. 11462 return null; 11463 } 11464 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11465 if (lastPackage != null) { 11466 pkgs.remove(lastPackage); 11467 } 11468 if (pkgs.size() > 0) { 11469 return pkgs.get(0); 11470 } 11471 } 11472 return null; 11473 } 11474 11475 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11476 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11477 userId, andCode ? 1 : 0, packageName); 11478 if (mSystemReady) { 11479 msg.sendToTarget(); 11480 } else { 11481 if (mPostSystemReadyMessages == null) { 11482 mPostSystemReadyMessages = new ArrayList<>(); 11483 } 11484 mPostSystemReadyMessages.add(msg); 11485 } 11486 } 11487 11488 void startCleaningPackages() { 11489 // reader 11490 if (!isExternalMediaAvailable()) { 11491 return; 11492 } 11493 synchronized (mPackages) { 11494 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11495 return; 11496 } 11497 } 11498 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11499 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11500 IActivityManager am = ActivityManagerNative.getDefault(); 11501 if (am != null) { 11502 try { 11503 am.startService(null, intent, null, mContext.getOpPackageName(), 11504 UserHandle.USER_SYSTEM); 11505 } catch (RemoteException e) { 11506 } 11507 } 11508 } 11509 11510 @Override 11511 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11512 int installFlags, String installerPackageName, int userId) { 11513 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11514 11515 final int callingUid = Binder.getCallingUid(); 11516 enforceCrossUserPermission(callingUid, userId, 11517 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11518 11519 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11520 try { 11521 if (observer != null) { 11522 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11523 } 11524 } catch (RemoteException re) { 11525 } 11526 return; 11527 } 11528 11529 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11530 installFlags |= PackageManager.INSTALL_FROM_ADB; 11531 11532 } else { 11533 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11534 // about installerPackageName. 11535 11536 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11537 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11538 } 11539 11540 UserHandle user; 11541 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11542 user = UserHandle.ALL; 11543 } else { 11544 user = new UserHandle(userId); 11545 } 11546 11547 // Only system components can circumvent runtime permissions when installing. 11548 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11549 && mContext.checkCallingOrSelfPermission(Manifest.permission 11550 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11551 throw new SecurityException("You need the " 11552 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11553 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11554 } 11555 11556 final File originFile = new File(originPath); 11557 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11558 11559 final Message msg = mHandler.obtainMessage(INIT_COPY); 11560 final VerificationInfo verificationInfo = new VerificationInfo( 11561 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11562 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11563 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11564 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11565 null /*certificates*/); 11566 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11567 msg.obj = params; 11568 11569 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11570 System.identityHashCode(msg.obj)); 11571 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11572 System.identityHashCode(msg.obj)); 11573 11574 mHandler.sendMessage(msg); 11575 } 11576 11577 void installStage(String packageName, File stagedDir, String stagedCid, 11578 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11579 String installerPackageName, int installerUid, UserHandle user, 11580 Certificate[][] certificates) { 11581 if (DEBUG_EPHEMERAL) { 11582 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11583 Slog.d(TAG, "Ephemeral install of " + packageName); 11584 } 11585 } 11586 final VerificationInfo verificationInfo = new VerificationInfo( 11587 sessionParams.originatingUri, sessionParams.referrerUri, 11588 sessionParams.originatingUid, installerUid); 11589 11590 final OriginInfo origin; 11591 if (stagedDir != null) { 11592 origin = OriginInfo.fromStagedFile(stagedDir); 11593 } else { 11594 origin = OriginInfo.fromStagedContainer(stagedCid); 11595 } 11596 11597 final Message msg = mHandler.obtainMessage(INIT_COPY); 11598 final InstallParams params = new InstallParams(origin, null, observer, 11599 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11600 verificationInfo, user, sessionParams.abiOverride, 11601 sessionParams.grantedRuntimePermissions, certificates); 11602 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11603 msg.obj = params; 11604 11605 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11606 System.identityHashCode(msg.obj)); 11607 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11608 System.identityHashCode(msg.obj)); 11609 11610 mHandler.sendMessage(msg); 11611 } 11612 11613 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11614 int userId) { 11615 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11616 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11617 } 11618 11619 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11620 int appId, int userId) { 11621 Bundle extras = new Bundle(1); 11622 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11623 11624 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11625 packageName, extras, 0, null, null, new int[] {userId}); 11626 try { 11627 IActivityManager am = ActivityManagerNative.getDefault(); 11628 if (isSystem && am.isUserRunning(userId, 0)) { 11629 // The just-installed/enabled app is bundled on the system, so presumed 11630 // to be able to run automatically without needing an explicit launch. 11631 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11632 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11633 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11634 .setPackage(packageName); 11635 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11636 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11637 } 11638 } catch (RemoteException e) { 11639 // shouldn't happen 11640 Slog.w(TAG, "Unable to bootstrap installed package", e); 11641 } 11642 } 11643 11644 @Override 11645 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11646 int userId) { 11647 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11648 PackageSetting pkgSetting; 11649 final int uid = Binder.getCallingUid(); 11650 enforceCrossUserPermission(uid, userId, 11651 true /* requireFullPermission */, true /* checkShell */, 11652 "setApplicationHiddenSetting for user " + userId); 11653 11654 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11655 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11656 return false; 11657 } 11658 11659 long callingId = Binder.clearCallingIdentity(); 11660 try { 11661 boolean sendAdded = false; 11662 boolean sendRemoved = false; 11663 // writer 11664 synchronized (mPackages) { 11665 pkgSetting = mSettings.mPackages.get(packageName); 11666 if (pkgSetting == null) { 11667 return false; 11668 } 11669 // Do not allow "android" is being disabled 11670 if ("android".equals(packageName)) { 11671 Slog.w(TAG, "Cannot hide package: android"); 11672 return false; 11673 } 11674 // Only allow protected packages to hide themselves. 11675 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11676 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11677 Slog.w(TAG, "Not hiding protected package: " + packageName); 11678 return false; 11679 } 11680 11681 if (pkgSetting.getHidden(userId) != hidden) { 11682 pkgSetting.setHidden(hidden, userId); 11683 mSettings.writePackageRestrictionsLPr(userId); 11684 if (hidden) { 11685 sendRemoved = true; 11686 } else { 11687 sendAdded = true; 11688 } 11689 } 11690 } 11691 if (sendAdded) { 11692 sendPackageAddedForUser(packageName, pkgSetting, userId); 11693 return true; 11694 } 11695 if (sendRemoved) { 11696 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11697 "hiding pkg"); 11698 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11699 return true; 11700 } 11701 } finally { 11702 Binder.restoreCallingIdentity(callingId); 11703 } 11704 return false; 11705 } 11706 11707 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11708 int userId) { 11709 final PackageRemovedInfo info = new PackageRemovedInfo(); 11710 info.removedPackage = packageName; 11711 info.removedUsers = new int[] {userId}; 11712 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11713 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11714 } 11715 11716 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11717 if (pkgList.length > 0) { 11718 Bundle extras = new Bundle(1); 11719 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11720 11721 sendPackageBroadcast( 11722 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11723 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11724 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11725 new int[] {userId}); 11726 } 11727 } 11728 11729 /** 11730 * Returns true if application is not found or there was an error. Otherwise it returns 11731 * the hidden state of the package for the given user. 11732 */ 11733 @Override 11734 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11735 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11736 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11737 true /* requireFullPermission */, false /* checkShell */, 11738 "getApplicationHidden for user " + userId); 11739 PackageSetting pkgSetting; 11740 long callingId = Binder.clearCallingIdentity(); 11741 try { 11742 // writer 11743 synchronized (mPackages) { 11744 pkgSetting = mSettings.mPackages.get(packageName); 11745 if (pkgSetting == null) { 11746 return true; 11747 } 11748 return pkgSetting.getHidden(userId); 11749 } 11750 } finally { 11751 Binder.restoreCallingIdentity(callingId); 11752 } 11753 } 11754 11755 /** 11756 * @hide 11757 */ 11758 @Override 11759 public int installExistingPackageAsUser(String packageName, int userId) { 11760 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11761 null); 11762 PackageSetting pkgSetting; 11763 final int uid = Binder.getCallingUid(); 11764 enforceCrossUserPermission(uid, userId, 11765 true /* requireFullPermission */, true /* checkShell */, 11766 "installExistingPackage for user " + userId); 11767 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11768 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11769 } 11770 11771 long callingId = Binder.clearCallingIdentity(); 11772 try { 11773 boolean installed = false; 11774 11775 // writer 11776 synchronized (mPackages) { 11777 pkgSetting = mSettings.mPackages.get(packageName); 11778 if (pkgSetting == null) { 11779 return PackageManager.INSTALL_FAILED_INVALID_URI; 11780 } 11781 if (!pkgSetting.getInstalled(userId)) { 11782 pkgSetting.setInstalled(true, userId); 11783 pkgSetting.setHidden(false, userId); 11784 mSettings.writePackageRestrictionsLPr(userId); 11785 installed = true; 11786 } 11787 } 11788 11789 if (installed) { 11790 if (pkgSetting.pkg != null) { 11791 synchronized (mInstallLock) { 11792 // We don't need to freeze for a brand new install 11793 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11794 } 11795 } 11796 sendPackageAddedForUser(packageName, pkgSetting, userId); 11797 } 11798 } finally { 11799 Binder.restoreCallingIdentity(callingId); 11800 } 11801 11802 return PackageManager.INSTALL_SUCCEEDED; 11803 } 11804 11805 boolean isUserRestricted(int userId, String restrictionKey) { 11806 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11807 if (restrictions.getBoolean(restrictionKey, false)) { 11808 Log.w(TAG, "User is restricted: " + restrictionKey); 11809 return true; 11810 } 11811 return false; 11812 } 11813 11814 @Override 11815 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11816 int userId) { 11817 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11818 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11819 true /* requireFullPermission */, true /* checkShell */, 11820 "setPackagesSuspended for user " + userId); 11821 11822 if (ArrayUtils.isEmpty(packageNames)) { 11823 return packageNames; 11824 } 11825 11826 // List of package names for whom the suspended state has changed. 11827 List<String> changedPackages = new ArrayList<>(packageNames.length); 11828 // List of package names for whom the suspended state is not set as requested in this 11829 // method. 11830 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11831 long callingId = Binder.clearCallingIdentity(); 11832 try { 11833 for (int i = 0; i < packageNames.length; i++) { 11834 String packageName = packageNames[i]; 11835 boolean changed = false; 11836 final int appId; 11837 synchronized (mPackages) { 11838 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11839 if (pkgSetting == null) { 11840 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11841 + "\". Skipping suspending/un-suspending."); 11842 unactionedPackages.add(packageName); 11843 continue; 11844 } 11845 appId = pkgSetting.appId; 11846 if (pkgSetting.getSuspended(userId) != suspended) { 11847 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11848 unactionedPackages.add(packageName); 11849 continue; 11850 } 11851 pkgSetting.setSuspended(suspended, userId); 11852 mSettings.writePackageRestrictionsLPr(userId); 11853 changed = true; 11854 changedPackages.add(packageName); 11855 } 11856 } 11857 11858 if (changed && suspended) { 11859 killApplication(packageName, UserHandle.getUid(userId, appId), 11860 "suspending package"); 11861 } 11862 } 11863 } finally { 11864 Binder.restoreCallingIdentity(callingId); 11865 } 11866 11867 if (!changedPackages.isEmpty()) { 11868 sendPackagesSuspendedForUser(changedPackages.toArray( 11869 new String[changedPackages.size()]), userId, suspended); 11870 } 11871 11872 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11873 } 11874 11875 @Override 11876 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11877 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11878 true /* requireFullPermission */, false /* checkShell */, 11879 "isPackageSuspendedForUser for user " + userId); 11880 synchronized (mPackages) { 11881 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11882 if (pkgSetting == null) { 11883 throw new IllegalArgumentException("Unknown target package: " + packageName); 11884 } 11885 return pkgSetting.getSuspended(userId); 11886 } 11887 } 11888 11889 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11890 if (isPackageDeviceAdmin(packageName, userId)) { 11891 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11892 + "\": has an active device admin"); 11893 return false; 11894 } 11895 11896 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11897 if (packageName.equals(activeLauncherPackageName)) { 11898 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11899 + "\": contains the active launcher"); 11900 return false; 11901 } 11902 11903 if (packageName.equals(mRequiredInstallerPackage)) { 11904 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11905 + "\": required for package installation"); 11906 return false; 11907 } 11908 11909 if (packageName.equals(mRequiredUninstallerPackage)) { 11910 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11911 + "\": required for package uninstallation"); 11912 return false; 11913 } 11914 11915 if (packageName.equals(mRequiredVerifierPackage)) { 11916 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11917 + "\": required for package verification"); 11918 return false; 11919 } 11920 11921 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11922 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11923 + "\": is the default dialer"); 11924 return false; 11925 } 11926 11927 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11928 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11929 + "\": protected package"); 11930 return false; 11931 } 11932 11933 return true; 11934 } 11935 11936 private String getActiveLauncherPackageName(int userId) { 11937 Intent intent = new Intent(Intent.ACTION_MAIN); 11938 intent.addCategory(Intent.CATEGORY_HOME); 11939 ResolveInfo resolveInfo = resolveIntent( 11940 intent, 11941 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11942 PackageManager.MATCH_DEFAULT_ONLY, 11943 userId); 11944 11945 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11946 } 11947 11948 private String getDefaultDialerPackageName(int userId) { 11949 synchronized (mPackages) { 11950 return mSettings.getDefaultDialerPackageNameLPw(userId); 11951 } 11952 } 11953 11954 @Override 11955 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11956 mContext.enforceCallingOrSelfPermission( 11957 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11958 "Only package verification agents can verify applications"); 11959 11960 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11961 final PackageVerificationResponse response = new PackageVerificationResponse( 11962 verificationCode, Binder.getCallingUid()); 11963 msg.arg1 = id; 11964 msg.obj = response; 11965 mHandler.sendMessage(msg); 11966 } 11967 11968 @Override 11969 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11970 long millisecondsToDelay) { 11971 mContext.enforceCallingOrSelfPermission( 11972 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11973 "Only package verification agents can extend verification timeouts"); 11974 11975 final PackageVerificationState state = mPendingVerification.get(id); 11976 final PackageVerificationResponse response = new PackageVerificationResponse( 11977 verificationCodeAtTimeout, Binder.getCallingUid()); 11978 11979 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11980 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11981 } 11982 if (millisecondsToDelay < 0) { 11983 millisecondsToDelay = 0; 11984 } 11985 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11986 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11987 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11988 } 11989 11990 if ((state != null) && !state.timeoutExtended()) { 11991 state.extendTimeout(); 11992 11993 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11994 msg.arg1 = id; 11995 msg.obj = response; 11996 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11997 } 11998 } 11999 12000 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12001 int verificationCode, UserHandle user) { 12002 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12003 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12004 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12005 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12006 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12007 12008 mContext.sendBroadcastAsUser(intent, user, 12009 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12010 } 12011 12012 private ComponentName matchComponentForVerifier(String packageName, 12013 List<ResolveInfo> receivers) { 12014 ActivityInfo targetReceiver = null; 12015 12016 final int NR = receivers.size(); 12017 for (int i = 0; i < NR; i++) { 12018 final ResolveInfo info = receivers.get(i); 12019 if (info.activityInfo == null) { 12020 continue; 12021 } 12022 12023 if (packageName.equals(info.activityInfo.packageName)) { 12024 targetReceiver = info.activityInfo; 12025 break; 12026 } 12027 } 12028 12029 if (targetReceiver == null) { 12030 return null; 12031 } 12032 12033 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12034 } 12035 12036 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12037 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12038 if (pkgInfo.verifiers.length == 0) { 12039 return null; 12040 } 12041 12042 final int N = pkgInfo.verifiers.length; 12043 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12044 for (int i = 0; i < N; i++) { 12045 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12046 12047 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12048 receivers); 12049 if (comp == null) { 12050 continue; 12051 } 12052 12053 final int verifierUid = getUidForVerifier(verifierInfo); 12054 if (verifierUid == -1) { 12055 continue; 12056 } 12057 12058 if (DEBUG_VERIFY) { 12059 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12060 + " with the correct signature"); 12061 } 12062 sufficientVerifiers.add(comp); 12063 verificationState.addSufficientVerifier(verifierUid); 12064 } 12065 12066 return sufficientVerifiers; 12067 } 12068 12069 private int getUidForVerifier(VerifierInfo verifierInfo) { 12070 synchronized (mPackages) { 12071 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12072 if (pkg == null) { 12073 return -1; 12074 } else if (pkg.mSignatures.length != 1) { 12075 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12076 + " has more than one signature; ignoring"); 12077 return -1; 12078 } 12079 12080 /* 12081 * If the public key of the package's signature does not match 12082 * our expected public key, then this is a different package and 12083 * we should skip. 12084 */ 12085 12086 final byte[] expectedPublicKey; 12087 try { 12088 final Signature verifierSig = pkg.mSignatures[0]; 12089 final PublicKey publicKey = verifierSig.getPublicKey(); 12090 expectedPublicKey = publicKey.getEncoded(); 12091 } catch (CertificateException e) { 12092 return -1; 12093 } 12094 12095 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12096 12097 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12098 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12099 + " does not have the expected public key; ignoring"); 12100 return -1; 12101 } 12102 12103 return pkg.applicationInfo.uid; 12104 } 12105 } 12106 12107 @Override 12108 public void finishPackageInstall(int token, boolean didLaunch) { 12109 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12110 12111 if (DEBUG_INSTALL) { 12112 Slog.v(TAG, "BM finishing package install for " + token); 12113 } 12114 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12115 12116 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12117 mHandler.sendMessage(msg); 12118 } 12119 12120 /** 12121 * Get the verification agent timeout. 12122 * 12123 * @return verification timeout in milliseconds 12124 */ 12125 private long getVerificationTimeout() { 12126 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12127 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12128 DEFAULT_VERIFICATION_TIMEOUT); 12129 } 12130 12131 /** 12132 * Get the default verification agent response code. 12133 * 12134 * @return default verification response code 12135 */ 12136 private int getDefaultVerificationResponse() { 12137 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12138 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12139 DEFAULT_VERIFICATION_RESPONSE); 12140 } 12141 12142 /** 12143 * Check whether or not package verification has been enabled. 12144 * 12145 * @return true if verification should be performed 12146 */ 12147 private boolean isVerificationEnabled(int userId, int installFlags) { 12148 if (!DEFAULT_VERIFY_ENABLE) { 12149 return false; 12150 } 12151 // Ephemeral apps don't get the full verification treatment 12152 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12153 if (DEBUG_EPHEMERAL) { 12154 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12155 } 12156 return false; 12157 } 12158 12159 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12160 12161 // Check if installing from ADB 12162 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12163 // Do not run verification in a test harness environment 12164 if (ActivityManager.isRunningInTestHarness()) { 12165 return false; 12166 } 12167 if (ensureVerifyAppsEnabled) { 12168 return true; 12169 } 12170 // Check if the developer does not want package verification for ADB installs 12171 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12172 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12173 return false; 12174 } 12175 } 12176 12177 if (ensureVerifyAppsEnabled) { 12178 return true; 12179 } 12180 12181 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12182 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12183 } 12184 12185 @Override 12186 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12187 throws RemoteException { 12188 mContext.enforceCallingOrSelfPermission( 12189 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12190 "Only intentfilter verification agents can verify applications"); 12191 12192 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12193 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12194 Binder.getCallingUid(), verificationCode, failedDomains); 12195 msg.arg1 = id; 12196 msg.obj = response; 12197 mHandler.sendMessage(msg); 12198 } 12199 12200 @Override 12201 public int getIntentVerificationStatus(String packageName, int userId) { 12202 synchronized (mPackages) { 12203 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12204 } 12205 } 12206 12207 @Override 12208 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12209 mContext.enforceCallingOrSelfPermission( 12210 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12211 12212 boolean result = false; 12213 synchronized (mPackages) { 12214 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12215 } 12216 if (result) { 12217 scheduleWritePackageRestrictionsLocked(userId); 12218 } 12219 return result; 12220 } 12221 12222 @Override 12223 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12224 String packageName) { 12225 synchronized (mPackages) { 12226 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12227 } 12228 } 12229 12230 @Override 12231 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12232 if (TextUtils.isEmpty(packageName)) { 12233 return ParceledListSlice.emptyList(); 12234 } 12235 synchronized (mPackages) { 12236 PackageParser.Package pkg = mPackages.get(packageName); 12237 if (pkg == null || pkg.activities == null) { 12238 return ParceledListSlice.emptyList(); 12239 } 12240 final int count = pkg.activities.size(); 12241 ArrayList<IntentFilter> result = new ArrayList<>(); 12242 for (int n=0; n<count; n++) { 12243 PackageParser.Activity activity = pkg.activities.get(n); 12244 if (activity.intents != null && activity.intents.size() > 0) { 12245 result.addAll(activity.intents); 12246 } 12247 } 12248 return new ParceledListSlice<>(result); 12249 } 12250 } 12251 12252 @Override 12253 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12254 mContext.enforceCallingOrSelfPermission( 12255 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12256 12257 synchronized (mPackages) { 12258 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12259 if (packageName != null) { 12260 result |= updateIntentVerificationStatus(packageName, 12261 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12262 userId); 12263 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12264 packageName, userId); 12265 } 12266 return result; 12267 } 12268 } 12269 12270 @Override 12271 public String getDefaultBrowserPackageName(int userId) { 12272 synchronized (mPackages) { 12273 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12274 } 12275 } 12276 12277 /** 12278 * Get the "allow unknown sources" setting. 12279 * 12280 * @return the current "allow unknown sources" setting 12281 */ 12282 private int getUnknownSourcesSettings() { 12283 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12284 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12285 -1); 12286 } 12287 12288 @Override 12289 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12290 final int uid = Binder.getCallingUid(); 12291 // writer 12292 synchronized (mPackages) { 12293 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12294 if (targetPackageSetting == null) { 12295 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12296 } 12297 12298 PackageSetting installerPackageSetting; 12299 if (installerPackageName != null) { 12300 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12301 if (installerPackageSetting == null) { 12302 throw new IllegalArgumentException("Unknown installer package: " 12303 + installerPackageName); 12304 } 12305 } else { 12306 installerPackageSetting = null; 12307 } 12308 12309 Signature[] callerSignature; 12310 Object obj = mSettings.getUserIdLPr(uid); 12311 if (obj != null) { 12312 if (obj instanceof SharedUserSetting) { 12313 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12314 } else if (obj instanceof PackageSetting) { 12315 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12316 } else { 12317 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12318 } 12319 } else { 12320 throw new SecurityException("Unknown calling UID: " + uid); 12321 } 12322 12323 // Verify: can't set installerPackageName to a package that is 12324 // not signed with the same cert as the caller. 12325 if (installerPackageSetting != null) { 12326 if (compareSignatures(callerSignature, 12327 installerPackageSetting.signatures.mSignatures) 12328 != PackageManager.SIGNATURE_MATCH) { 12329 throw new SecurityException( 12330 "Caller does not have same cert as new installer package " 12331 + installerPackageName); 12332 } 12333 } 12334 12335 // Verify: if target already has an installer package, it must 12336 // be signed with the same cert as the caller. 12337 if (targetPackageSetting.installerPackageName != null) { 12338 PackageSetting setting = mSettings.mPackages.get( 12339 targetPackageSetting.installerPackageName); 12340 // If the currently set package isn't valid, then it's always 12341 // okay to change it. 12342 if (setting != null) { 12343 if (compareSignatures(callerSignature, 12344 setting.signatures.mSignatures) 12345 != PackageManager.SIGNATURE_MATCH) { 12346 throw new SecurityException( 12347 "Caller does not have same cert as old installer package " 12348 + targetPackageSetting.installerPackageName); 12349 } 12350 } 12351 } 12352 12353 // Okay! 12354 targetPackageSetting.installerPackageName = installerPackageName; 12355 if (installerPackageName != null) { 12356 mSettings.mInstallerPackages.add(installerPackageName); 12357 } 12358 scheduleWriteSettingsLocked(); 12359 } 12360 } 12361 12362 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12363 // Queue up an async operation since the package installation may take a little while. 12364 mHandler.post(new Runnable() { 12365 public void run() { 12366 mHandler.removeCallbacks(this); 12367 // Result object to be returned 12368 PackageInstalledInfo res = new PackageInstalledInfo(); 12369 res.setReturnCode(currentStatus); 12370 res.uid = -1; 12371 res.pkg = null; 12372 res.removedInfo = null; 12373 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12374 args.doPreInstall(res.returnCode); 12375 synchronized (mInstallLock) { 12376 installPackageTracedLI(args, res); 12377 } 12378 args.doPostInstall(res.returnCode, res.uid); 12379 } 12380 12381 // A restore should be performed at this point if (a) the install 12382 // succeeded, (b) the operation is not an update, and (c) the new 12383 // package has not opted out of backup participation. 12384 final boolean update = res.removedInfo != null 12385 && res.removedInfo.removedPackage != null; 12386 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12387 boolean doRestore = !update 12388 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12389 12390 // Set up the post-install work request bookkeeping. This will be used 12391 // and cleaned up by the post-install event handling regardless of whether 12392 // there's a restore pass performed. Token values are >= 1. 12393 int token; 12394 if (mNextInstallToken < 0) mNextInstallToken = 1; 12395 token = mNextInstallToken++; 12396 12397 PostInstallData data = new PostInstallData(args, res); 12398 mRunningInstalls.put(token, data); 12399 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12400 12401 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12402 // Pass responsibility to the Backup Manager. It will perform a 12403 // restore if appropriate, then pass responsibility back to the 12404 // Package Manager to run the post-install observer callbacks 12405 // and broadcasts. 12406 IBackupManager bm = IBackupManager.Stub.asInterface( 12407 ServiceManager.getService(Context.BACKUP_SERVICE)); 12408 if (bm != null) { 12409 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12410 + " to BM for possible restore"); 12411 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12412 try { 12413 // TODO: http://b/22388012 12414 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12415 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12416 } else { 12417 doRestore = false; 12418 } 12419 } catch (RemoteException e) { 12420 // can't happen; the backup manager is local 12421 } catch (Exception e) { 12422 Slog.e(TAG, "Exception trying to enqueue restore", e); 12423 doRestore = false; 12424 } 12425 } else { 12426 Slog.e(TAG, "Backup Manager not found!"); 12427 doRestore = false; 12428 } 12429 } 12430 12431 if (!doRestore) { 12432 // No restore possible, or the Backup Manager was mysteriously not 12433 // available -- just fire the post-install work request directly. 12434 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12435 12436 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12437 12438 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12439 mHandler.sendMessage(msg); 12440 } 12441 } 12442 }); 12443 } 12444 12445 /** 12446 * Callback from PackageSettings whenever an app is first transitioned out of the 12447 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12448 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12449 * here whether the app is the target of an ongoing install, and only send the 12450 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12451 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12452 * handling. 12453 */ 12454 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12455 // Serialize this with the rest of the install-process message chain. In the 12456 // restore-at-install case, this Runnable will necessarily run before the 12457 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12458 // are coherent. In the non-restore case, the app has already completed install 12459 // and been launched through some other means, so it is not in a problematic 12460 // state for observers to see the FIRST_LAUNCH signal. 12461 mHandler.post(new Runnable() { 12462 @Override 12463 public void run() { 12464 for (int i = 0; i < mRunningInstalls.size(); i++) { 12465 final PostInstallData data = mRunningInstalls.valueAt(i); 12466 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12467 continue; 12468 } 12469 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12470 // right package; but is it for the right user? 12471 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12472 if (userId == data.res.newUsers[uIndex]) { 12473 if (DEBUG_BACKUP) { 12474 Slog.i(TAG, "Package " + pkgName 12475 + " being restored so deferring FIRST_LAUNCH"); 12476 } 12477 return; 12478 } 12479 } 12480 } 12481 } 12482 // didn't find it, so not being restored 12483 if (DEBUG_BACKUP) { 12484 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12485 } 12486 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12487 } 12488 }); 12489 } 12490 12491 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12492 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12493 installerPkg, null, userIds); 12494 } 12495 12496 private abstract class HandlerParams { 12497 private static final int MAX_RETRIES = 4; 12498 12499 /** 12500 * Number of times startCopy() has been attempted and had a non-fatal 12501 * error. 12502 */ 12503 private int mRetries = 0; 12504 12505 /** User handle for the user requesting the information or installation. */ 12506 private final UserHandle mUser; 12507 String traceMethod; 12508 int traceCookie; 12509 12510 HandlerParams(UserHandle user) { 12511 mUser = user; 12512 } 12513 12514 UserHandle getUser() { 12515 return mUser; 12516 } 12517 12518 HandlerParams setTraceMethod(String traceMethod) { 12519 this.traceMethod = traceMethod; 12520 return this; 12521 } 12522 12523 HandlerParams setTraceCookie(int traceCookie) { 12524 this.traceCookie = traceCookie; 12525 return this; 12526 } 12527 12528 final boolean startCopy() { 12529 boolean res; 12530 try { 12531 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12532 12533 if (++mRetries > MAX_RETRIES) { 12534 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12535 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12536 handleServiceError(); 12537 return false; 12538 } else { 12539 handleStartCopy(); 12540 res = true; 12541 } 12542 } catch (RemoteException e) { 12543 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12544 mHandler.sendEmptyMessage(MCS_RECONNECT); 12545 res = false; 12546 } 12547 handleReturnCode(); 12548 return res; 12549 } 12550 12551 final void serviceError() { 12552 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12553 handleServiceError(); 12554 handleReturnCode(); 12555 } 12556 12557 abstract void handleStartCopy() throws RemoteException; 12558 abstract void handleServiceError(); 12559 abstract void handleReturnCode(); 12560 } 12561 12562 class MeasureParams extends HandlerParams { 12563 private final PackageStats mStats; 12564 private boolean mSuccess; 12565 12566 private final IPackageStatsObserver mObserver; 12567 12568 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12569 super(new UserHandle(stats.userHandle)); 12570 mObserver = observer; 12571 mStats = stats; 12572 } 12573 12574 @Override 12575 public String toString() { 12576 return "MeasureParams{" 12577 + Integer.toHexString(System.identityHashCode(this)) 12578 + " " + mStats.packageName + "}"; 12579 } 12580 12581 @Override 12582 void handleStartCopy() throws RemoteException { 12583 synchronized (mInstallLock) { 12584 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12585 } 12586 12587 if (mSuccess) { 12588 boolean mounted = false; 12589 try { 12590 final String status = Environment.getExternalStorageState(); 12591 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12592 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12593 } catch (Exception e) { 12594 } 12595 12596 if (mounted) { 12597 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12598 12599 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12600 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12601 12602 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12603 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12604 12605 // Always subtract cache size, since it's a subdirectory 12606 mStats.externalDataSize -= mStats.externalCacheSize; 12607 12608 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12609 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12610 12611 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12612 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12613 } 12614 } 12615 } 12616 12617 @Override 12618 void handleReturnCode() { 12619 if (mObserver != null) { 12620 try { 12621 mObserver.onGetStatsCompleted(mStats, mSuccess); 12622 } catch (RemoteException e) { 12623 Slog.i(TAG, "Observer no longer exists."); 12624 } 12625 } 12626 } 12627 12628 @Override 12629 void handleServiceError() { 12630 Slog.e(TAG, "Could not measure application " + mStats.packageName 12631 + " external storage"); 12632 } 12633 } 12634 12635 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12636 throws RemoteException { 12637 long result = 0; 12638 for (File path : paths) { 12639 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12640 } 12641 return result; 12642 } 12643 12644 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12645 for (File path : paths) { 12646 try { 12647 mcs.clearDirectory(path.getAbsolutePath()); 12648 } catch (RemoteException e) { 12649 } 12650 } 12651 } 12652 12653 static class OriginInfo { 12654 /** 12655 * Location where install is coming from, before it has been 12656 * copied/renamed into place. This could be a single monolithic APK 12657 * file, or a cluster directory. This location may be untrusted. 12658 */ 12659 final File file; 12660 final String cid; 12661 12662 /** 12663 * Flag indicating that {@link #file} or {@link #cid} has already been 12664 * staged, meaning downstream users don't need to defensively copy the 12665 * contents. 12666 */ 12667 final boolean staged; 12668 12669 /** 12670 * Flag indicating that {@link #file} or {@link #cid} is an already 12671 * installed app that is being moved. 12672 */ 12673 final boolean existing; 12674 12675 final String resolvedPath; 12676 final File resolvedFile; 12677 12678 static OriginInfo fromNothing() { 12679 return new OriginInfo(null, null, false, false); 12680 } 12681 12682 static OriginInfo fromUntrustedFile(File file) { 12683 return new OriginInfo(file, null, false, false); 12684 } 12685 12686 static OriginInfo fromExistingFile(File file) { 12687 return new OriginInfo(file, null, false, true); 12688 } 12689 12690 static OriginInfo fromStagedFile(File file) { 12691 return new OriginInfo(file, null, true, false); 12692 } 12693 12694 static OriginInfo fromStagedContainer(String cid) { 12695 return new OriginInfo(null, cid, true, false); 12696 } 12697 12698 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12699 this.file = file; 12700 this.cid = cid; 12701 this.staged = staged; 12702 this.existing = existing; 12703 12704 if (cid != null) { 12705 resolvedPath = PackageHelper.getSdDir(cid); 12706 resolvedFile = new File(resolvedPath); 12707 } else if (file != null) { 12708 resolvedPath = file.getAbsolutePath(); 12709 resolvedFile = file; 12710 } else { 12711 resolvedPath = null; 12712 resolvedFile = null; 12713 } 12714 } 12715 } 12716 12717 static class MoveInfo { 12718 final int moveId; 12719 final String fromUuid; 12720 final String toUuid; 12721 final String packageName; 12722 final String dataAppName; 12723 final int appId; 12724 final String seinfo; 12725 final int targetSdkVersion; 12726 12727 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12728 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12729 this.moveId = moveId; 12730 this.fromUuid = fromUuid; 12731 this.toUuid = toUuid; 12732 this.packageName = packageName; 12733 this.dataAppName = dataAppName; 12734 this.appId = appId; 12735 this.seinfo = seinfo; 12736 this.targetSdkVersion = targetSdkVersion; 12737 } 12738 } 12739 12740 static class VerificationInfo { 12741 /** A constant used to indicate that a uid value is not present. */ 12742 public static final int NO_UID = -1; 12743 12744 /** URI referencing where the package was downloaded from. */ 12745 final Uri originatingUri; 12746 12747 /** HTTP referrer URI associated with the originatingURI. */ 12748 final Uri referrer; 12749 12750 /** UID of the application that the install request originated from. */ 12751 final int originatingUid; 12752 12753 /** UID of application requesting the install */ 12754 final int installerUid; 12755 12756 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12757 this.originatingUri = originatingUri; 12758 this.referrer = referrer; 12759 this.originatingUid = originatingUid; 12760 this.installerUid = installerUid; 12761 } 12762 } 12763 12764 class InstallParams extends HandlerParams { 12765 final OriginInfo origin; 12766 final MoveInfo move; 12767 final IPackageInstallObserver2 observer; 12768 int installFlags; 12769 final String installerPackageName; 12770 final String volumeUuid; 12771 private InstallArgs mArgs; 12772 private int mRet; 12773 final String packageAbiOverride; 12774 final String[] grantedRuntimePermissions; 12775 final VerificationInfo verificationInfo; 12776 final Certificate[][] certificates; 12777 12778 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12779 int installFlags, String installerPackageName, String volumeUuid, 12780 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12781 String[] grantedPermissions, Certificate[][] certificates) { 12782 super(user); 12783 this.origin = origin; 12784 this.move = move; 12785 this.observer = observer; 12786 this.installFlags = installFlags; 12787 this.installerPackageName = installerPackageName; 12788 this.volumeUuid = volumeUuid; 12789 this.verificationInfo = verificationInfo; 12790 this.packageAbiOverride = packageAbiOverride; 12791 this.grantedRuntimePermissions = grantedPermissions; 12792 this.certificates = certificates; 12793 } 12794 12795 @Override 12796 public String toString() { 12797 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12798 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12799 } 12800 12801 private int installLocationPolicy(PackageInfoLite pkgLite) { 12802 String packageName = pkgLite.packageName; 12803 int installLocation = pkgLite.installLocation; 12804 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12805 // reader 12806 synchronized (mPackages) { 12807 // Currently installed package which the new package is attempting to replace or 12808 // null if no such package is installed. 12809 PackageParser.Package installedPkg = mPackages.get(packageName); 12810 // Package which currently owns the data which the new package will own if installed. 12811 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12812 // will be null whereas dataOwnerPkg will contain information about the package 12813 // which was uninstalled while keeping its data. 12814 PackageParser.Package dataOwnerPkg = installedPkg; 12815 if (dataOwnerPkg == null) { 12816 PackageSetting ps = mSettings.mPackages.get(packageName); 12817 if (ps != null) { 12818 dataOwnerPkg = ps.pkg; 12819 } 12820 } 12821 12822 if (dataOwnerPkg != null) { 12823 // If installed, the package will get access to data left on the device by its 12824 // predecessor. As a security measure, this is permited only if this is not a 12825 // version downgrade or if the predecessor package is marked as debuggable and 12826 // a downgrade is explicitly requested. 12827 // 12828 // On debuggable platform builds, downgrades are permitted even for 12829 // non-debuggable packages to make testing easier. Debuggable platform builds do 12830 // not offer security guarantees and thus it's OK to disable some security 12831 // mechanisms to make debugging/testing easier on those builds. However, even on 12832 // debuggable builds downgrades of packages are permitted only if requested via 12833 // installFlags. This is because we aim to keep the behavior of debuggable 12834 // platform builds as close as possible to the behavior of non-debuggable 12835 // platform builds. 12836 final boolean downgradeRequested = 12837 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12838 final boolean packageDebuggable = 12839 (dataOwnerPkg.applicationInfo.flags 12840 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12841 final boolean downgradePermitted = 12842 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12843 if (!downgradePermitted) { 12844 try { 12845 checkDowngrade(dataOwnerPkg, pkgLite); 12846 } catch (PackageManagerException e) { 12847 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12848 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12849 } 12850 } 12851 } 12852 12853 if (installedPkg != null) { 12854 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12855 // Check for updated system application. 12856 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12857 if (onSd) { 12858 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12859 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12860 } 12861 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12862 } else { 12863 if (onSd) { 12864 // Install flag overrides everything. 12865 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12866 } 12867 // If current upgrade specifies particular preference 12868 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12869 // Application explicitly specified internal. 12870 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12871 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12872 // App explictly prefers external. Let policy decide 12873 } else { 12874 // Prefer previous location 12875 if (isExternal(installedPkg)) { 12876 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12877 } 12878 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12879 } 12880 } 12881 } else { 12882 // Invalid install. Return error code 12883 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12884 } 12885 } 12886 } 12887 // All the special cases have been taken care of. 12888 // Return result based on recommended install location. 12889 if (onSd) { 12890 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12891 } 12892 return pkgLite.recommendedInstallLocation; 12893 } 12894 12895 /* 12896 * Invoke remote method to get package information and install 12897 * location values. Override install location based on default 12898 * policy if needed and then create install arguments based 12899 * on the install location. 12900 */ 12901 public void handleStartCopy() throws RemoteException { 12902 int ret = PackageManager.INSTALL_SUCCEEDED; 12903 12904 // If we're already staged, we've firmly committed to an install location 12905 if (origin.staged) { 12906 if (origin.file != null) { 12907 installFlags |= PackageManager.INSTALL_INTERNAL; 12908 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12909 } else if (origin.cid != null) { 12910 installFlags |= PackageManager.INSTALL_EXTERNAL; 12911 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12912 } else { 12913 throw new IllegalStateException("Invalid stage location"); 12914 } 12915 } 12916 12917 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12918 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12919 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12920 PackageInfoLite pkgLite = null; 12921 12922 if (onInt && onSd) { 12923 // Check if both bits are set. 12924 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12925 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12926 } else if (onSd && ephemeral) { 12927 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12928 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12929 } else { 12930 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12931 packageAbiOverride); 12932 12933 if (DEBUG_EPHEMERAL && ephemeral) { 12934 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12935 } 12936 12937 /* 12938 * If we have too little free space, try to free cache 12939 * before giving up. 12940 */ 12941 if (!origin.staged && pkgLite.recommendedInstallLocation 12942 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12943 // TODO: focus freeing disk space on the target device 12944 final StorageManager storage = StorageManager.from(mContext); 12945 final long lowThreshold = storage.getStorageLowBytes( 12946 Environment.getDataDirectory()); 12947 12948 final long sizeBytes = mContainerService.calculateInstalledSize( 12949 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12950 12951 try { 12952 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 12953 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12954 installFlags, packageAbiOverride); 12955 } catch (InstallerException e) { 12956 Slog.w(TAG, "Failed to free cache", e); 12957 } 12958 12959 /* 12960 * The cache free must have deleted the file we 12961 * downloaded to install. 12962 * 12963 * TODO: fix the "freeCache" call to not delete 12964 * the file we care about. 12965 */ 12966 if (pkgLite.recommendedInstallLocation 12967 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12968 pkgLite.recommendedInstallLocation 12969 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12970 } 12971 } 12972 } 12973 12974 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12975 int loc = pkgLite.recommendedInstallLocation; 12976 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12977 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12978 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12979 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12980 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12981 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12982 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12983 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12984 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12985 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12986 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12987 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12988 } else { 12989 // Override with defaults if needed. 12990 loc = installLocationPolicy(pkgLite); 12991 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12992 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12993 } else if (!onSd && !onInt) { 12994 // Override install location with flags 12995 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12996 // Set the flag to install on external media. 12997 installFlags |= PackageManager.INSTALL_EXTERNAL; 12998 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12999 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13000 if (DEBUG_EPHEMERAL) { 13001 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13002 } 13003 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13004 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13005 |PackageManager.INSTALL_INTERNAL); 13006 } else { 13007 // Make sure the flag for installing on external 13008 // media is unset 13009 installFlags |= PackageManager.INSTALL_INTERNAL; 13010 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13011 } 13012 } 13013 } 13014 } 13015 13016 final InstallArgs args = createInstallArgs(this); 13017 mArgs = args; 13018 13019 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13020 // TODO: http://b/22976637 13021 // Apps installed for "all" users use the device owner to verify the app 13022 UserHandle verifierUser = getUser(); 13023 if (verifierUser == UserHandle.ALL) { 13024 verifierUser = UserHandle.SYSTEM; 13025 } 13026 13027 /* 13028 * Determine if we have any installed package verifiers. If we 13029 * do, then we'll defer to them to verify the packages. 13030 */ 13031 final int requiredUid = mRequiredVerifierPackage == null ? -1 13032 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13033 verifierUser.getIdentifier()); 13034 if (!origin.existing && requiredUid != -1 13035 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13036 final Intent verification = new Intent( 13037 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13038 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13039 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13040 PACKAGE_MIME_TYPE); 13041 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13042 13043 // Query all live verifiers based on current user state 13044 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13045 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13046 13047 if (DEBUG_VERIFY) { 13048 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13049 + verification.toString() + " with " + pkgLite.verifiers.length 13050 + " optional verifiers"); 13051 } 13052 13053 final int verificationId = mPendingVerificationToken++; 13054 13055 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13056 13057 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13058 installerPackageName); 13059 13060 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13061 installFlags); 13062 13063 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13064 pkgLite.packageName); 13065 13066 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13067 pkgLite.versionCode); 13068 13069 if (verificationInfo != null) { 13070 if (verificationInfo.originatingUri != null) { 13071 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13072 verificationInfo.originatingUri); 13073 } 13074 if (verificationInfo.referrer != null) { 13075 verification.putExtra(Intent.EXTRA_REFERRER, 13076 verificationInfo.referrer); 13077 } 13078 if (verificationInfo.originatingUid >= 0) { 13079 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13080 verificationInfo.originatingUid); 13081 } 13082 if (verificationInfo.installerUid >= 0) { 13083 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13084 verificationInfo.installerUid); 13085 } 13086 } 13087 13088 final PackageVerificationState verificationState = new PackageVerificationState( 13089 requiredUid, args); 13090 13091 mPendingVerification.append(verificationId, verificationState); 13092 13093 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13094 receivers, verificationState); 13095 13096 /* 13097 * If any sufficient verifiers were listed in the package 13098 * manifest, attempt to ask them. 13099 */ 13100 if (sufficientVerifiers != null) { 13101 final int N = sufficientVerifiers.size(); 13102 if (N == 0) { 13103 Slog.i(TAG, "Additional verifiers required, but none installed."); 13104 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13105 } else { 13106 for (int i = 0; i < N; i++) { 13107 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13108 13109 final Intent sufficientIntent = new Intent(verification); 13110 sufficientIntent.setComponent(verifierComponent); 13111 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13112 } 13113 } 13114 } 13115 13116 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13117 mRequiredVerifierPackage, receivers); 13118 if (ret == PackageManager.INSTALL_SUCCEEDED 13119 && mRequiredVerifierPackage != null) { 13120 Trace.asyncTraceBegin( 13121 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13122 /* 13123 * Send the intent to the required verification agent, 13124 * but only start the verification timeout after the 13125 * target BroadcastReceivers have run. 13126 */ 13127 verification.setComponent(requiredVerifierComponent); 13128 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13129 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13130 new BroadcastReceiver() { 13131 @Override 13132 public void onReceive(Context context, Intent intent) { 13133 final Message msg = mHandler 13134 .obtainMessage(CHECK_PENDING_VERIFICATION); 13135 msg.arg1 = verificationId; 13136 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13137 } 13138 }, null, 0, null, null); 13139 13140 /* 13141 * We don't want the copy to proceed until verification 13142 * succeeds, so null out this field. 13143 */ 13144 mArgs = null; 13145 } 13146 } else { 13147 /* 13148 * No package verification is enabled, so immediately start 13149 * the remote call to initiate copy using temporary file. 13150 */ 13151 ret = args.copyApk(mContainerService, true); 13152 } 13153 } 13154 13155 mRet = ret; 13156 } 13157 13158 @Override 13159 void handleReturnCode() { 13160 // If mArgs is null, then MCS couldn't be reached. When it 13161 // reconnects, it will try again to install. At that point, this 13162 // will succeed. 13163 if (mArgs != null) { 13164 processPendingInstall(mArgs, mRet); 13165 } 13166 } 13167 13168 @Override 13169 void handleServiceError() { 13170 mArgs = createInstallArgs(this); 13171 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13172 } 13173 13174 public boolean isForwardLocked() { 13175 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13176 } 13177 } 13178 13179 /** 13180 * Used during creation of InstallArgs 13181 * 13182 * @param installFlags package installation flags 13183 * @return true if should be installed on external storage 13184 */ 13185 private static boolean installOnExternalAsec(int installFlags) { 13186 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13187 return false; 13188 } 13189 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13190 return true; 13191 } 13192 return false; 13193 } 13194 13195 /** 13196 * Used during creation of InstallArgs 13197 * 13198 * @param installFlags package installation flags 13199 * @return true if should be installed as forward locked 13200 */ 13201 private static boolean installForwardLocked(int installFlags) { 13202 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13203 } 13204 13205 private InstallArgs createInstallArgs(InstallParams params) { 13206 if (params.move != null) { 13207 return new MoveInstallArgs(params); 13208 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13209 return new AsecInstallArgs(params); 13210 } else { 13211 return new FileInstallArgs(params); 13212 } 13213 } 13214 13215 /** 13216 * Create args that describe an existing installed package. Typically used 13217 * when cleaning up old installs, or used as a move source. 13218 */ 13219 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13220 String resourcePath, String[] instructionSets) { 13221 final boolean isInAsec; 13222 if (installOnExternalAsec(installFlags)) { 13223 /* Apps on SD card are always in ASEC containers. */ 13224 isInAsec = true; 13225 } else if (installForwardLocked(installFlags) 13226 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13227 /* 13228 * Forward-locked apps are only in ASEC containers if they're the 13229 * new style 13230 */ 13231 isInAsec = true; 13232 } else { 13233 isInAsec = false; 13234 } 13235 13236 if (isInAsec) { 13237 return new AsecInstallArgs(codePath, instructionSets, 13238 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13239 } else { 13240 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13241 } 13242 } 13243 13244 static abstract class InstallArgs { 13245 /** @see InstallParams#origin */ 13246 final OriginInfo origin; 13247 /** @see InstallParams#move */ 13248 final MoveInfo move; 13249 13250 final IPackageInstallObserver2 observer; 13251 // Always refers to PackageManager flags only 13252 final int installFlags; 13253 final String installerPackageName; 13254 final String volumeUuid; 13255 final UserHandle user; 13256 final String abiOverride; 13257 final String[] installGrantPermissions; 13258 /** If non-null, drop an async trace when the install completes */ 13259 final String traceMethod; 13260 final int traceCookie; 13261 final Certificate[][] certificates; 13262 13263 // The list of instruction sets supported by this app. This is currently 13264 // only used during the rmdex() phase to clean up resources. We can get rid of this 13265 // if we move dex files under the common app path. 13266 /* nullable */ String[] instructionSets; 13267 13268 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13269 int installFlags, String installerPackageName, String volumeUuid, 13270 UserHandle user, String[] instructionSets, 13271 String abiOverride, String[] installGrantPermissions, 13272 String traceMethod, int traceCookie, Certificate[][] certificates) { 13273 this.origin = origin; 13274 this.move = move; 13275 this.installFlags = installFlags; 13276 this.observer = observer; 13277 this.installerPackageName = installerPackageName; 13278 this.volumeUuid = volumeUuid; 13279 this.user = user; 13280 this.instructionSets = instructionSets; 13281 this.abiOverride = abiOverride; 13282 this.installGrantPermissions = installGrantPermissions; 13283 this.traceMethod = traceMethod; 13284 this.traceCookie = traceCookie; 13285 this.certificates = certificates; 13286 } 13287 13288 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13289 abstract int doPreInstall(int status); 13290 13291 /** 13292 * Rename package into final resting place. All paths on the given 13293 * scanned package should be updated to reflect the rename. 13294 */ 13295 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13296 abstract int doPostInstall(int status, int uid); 13297 13298 /** @see PackageSettingBase#codePathString */ 13299 abstract String getCodePath(); 13300 /** @see PackageSettingBase#resourcePathString */ 13301 abstract String getResourcePath(); 13302 13303 // Need installer lock especially for dex file removal. 13304 abstract void cleanUpResourcesLI(); 13305 abstract boolean doPostDeleteLI(boolean delete); 13306 13307 /** 13308 * Called before the source arguments are copied. This is used mostly 13309 * for MoveParams when it needs to read the source file to put it in the 13310 * destination. 13311 */ 13312 int doPreCopy() { 13313 return PackageManager.INSTALL_SUCCEEDED; 13314 } 13315 13316 /** 13317 * Called after the source arguments are copied. This is used mostly for 13318 * MoveParams when it needs to read the source file to put it in the 13319 * destination. 13320 */ 13321 int doPostCopy(int uid) { 13322 return PackageManager.INSTALL_SUCCEEDED; 13323 } 13324 13325 protected boolean isFwdLocked() { 13326 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13327 } 13328 13329 protected boolean isExternalAsec() { 13330 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13331 } 13332 13333 protected boolean isEphemeral() { 13334 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13335 } 13336 13337 UserHandle getUser() { 13338 return user; 13339 } 13340 } 13341 13342 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13343 if (!allCodePaths.isEmpty()) { 13344 if (instructionSets == null) { 13345 throw new IllegalStateException("instructionSet == null"); 13346 } 13347 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13348 for (String codePath : allCodePaths) { 13349 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13350 try { 13351 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13352 } catch (InstallerException ignored) { 13353 } 13354 } 13355 } 13356 } 13357 } 13358 13359 /** 13360 * Logic to handle installation of non-ASEC applications, including copying 13361 * and renaming logic. 13362 */ 13363 class FileInstallArgs extends InstallArgs { 13364 private File codeFile; 13365 private File resourceFile; 13366 13367 // Example topology: 13368 // /data/app/com.example/base.apk 13369 // /data/app/com.example/split_foo.apk 13370 // /data/app/com.example/lib/arm/libfoo.so 13371 // /data/app/com.example/lib/arm64/libfoo.so 13372 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13373 13374 /** New install */ 13375 FileInstallArgs(InstallParams params) { 13376 super(params.origin, params.move, params.observer, params.installFlags, 13377 params.installerPackageName, params.volumeUuid, 13378 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13379 params.grantedRuntimePermissions, 13380 params.traceMethod, params.traceCookie, params.certificates); 13381 if (isFwdLocked()) { 13382 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13383 } 13384 } 13385 13386 /** Existing install */ 13387 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13388 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13389 null, null, null, 0, null /*certificates*/); 13390 this.codeFile = (codePath != null) ? new File(codePath) : null; 13391 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13392 } 13393 13394 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13395 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13396 try { 13397 return doCopyApk(imcs, temp); 13398 } finally { 13399 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13400 } 13401 } 13402 13403 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13404 if (origin.staged) { 13405 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13406 codeFile = origin.file; 13407 resourceFile = origin.file; 13408 return PackageManager.INSTALL_SUCCEEDED; 13409 } 13410 13411 try { 13412 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13413 final File tempDir = 13414 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13415 codeFile = tempDir; 13416 resourceFile = tempDir; 13417 } catch (IOException e) { 13418 Slog.w(TAG, "Failed to create copy file: " + e); 13419 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13420 } 13421 13422 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13423 @Override 13424 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13425 if (!FileUtils.isValidExtFilename(name)) { 13426 throw new IllegalArgumentException("Invalid filename: " + name); 13427 } 13428 try { 13429 final File file = new File(codeFile, name); 13430 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13431 O_RDWR | O_CREAT, 0644); 13432 Os.chmod(file.getAbsolutePath(), 0644); 13433 return new ParcelFileDescriptor(fd); 13434 } catch (ErrnoException e) { 13435 throw new RemoteException("Failed to open: " + e.getMessage()); 13436 } 13437 } 13438 }; 13439 13440 int ret = PackageManager.INSTALL_SUCCEEDED; 13441 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13442 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13443 Slog.e(TAG, "Failed to copy package"); 13444 return ret; 13445 } 13446 13447 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13448 NativeLibraryHelper.Handle handle = null; 13449 try { 13450 handle = NativeLibraryHelper.Handle.create(codeFile); 13451 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13452 abiOverride); 13453 } catch (IOException e) { 13454 Slog.e(TAG, "Copying native libraries failed", e); 13455 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13456 } finally { 13457 IoUtils.closeQuietly(handle); 13458 } 13459 13460 return ret; 13461 } 13462 13463 int doPreInstall(int status) { 13464 if (status != PackageManager.INSTALL_SUCCEEDED) { 13465 cleanUp(); 13466 } 13467 return status; 13468 } 13469 13470 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13471 if (status != PackageManager.INSTALL_SUCCEEDED) { 13472 cleanUp(); 13473 return false; 13474 } 13475 13476 final File targetDir = codeFile.getParentFile(); 13477 final File beforeCodeFile = codeFile; 13478 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13479 13480 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13481 try { 13482 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13483 } catch (ErrnoException e) { 13484 Slog.w(TAG, "Failed to rename", e); 13485 return false; 13486 } 13487 13488 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13489 Slog.w(TAG, "Failed to restorecon"); 13490 return false; 13491 } 13492 13493 // Reflect the rename internally 13494 codeFile = afterCodeFile; 13495 resourceFile = afterCodeFile; 13496 13497 // Reflect the rename in scanned details 13498 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13499 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13500 afterCodeFile, pkg.baseCodePath)); 13501 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13502 afterCodeFile, pkg.splitCodePaths)); 13503 13504 // Reflect the rename in app info 13505 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13506 pkg.setApplicationInfoCodePath(pkg.codePath); 13507 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13508 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13509 pkg.setApplicationInfoResourcePath(pkg.codePath); 13510 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13511 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13512 13513 return true; 13514 } 13515 13516 int doPostInstall(int status, int uid) { 13517 if (status != PackageManager.INSTALL_SUCCEEDED) { 13518 cleanUp(); 13519 } 13520 return status; 13521 } 13522 13523 @Override 13524 String getCodePath() { 13525 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13526 } 13527 13528 @Override 13529 String getResourcePath() { 13530 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13531 } 13532 13533 private boolean cleanUp() { 13534 if (codeFile == null || !codeFile.exists()) { 13535 return false; 13536 } 13537 13538 removeCodePathLI(codeFile); 13539 13540 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13541 resourceFile.delete(); 13542 } 13543 13544 return true; 13545 } 13546 13547 void cleanUpResourcesLI() { 13548 // Try enumerating all code paths before deleting 13549 List<String> allCodePaths = Collections.EMPTY_LIST; 13550 if (codeFile != null && codeFile.exists()) { 13551 try { 13552 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13553 allCodePaths = pkg.getAllCodePaths(); 13554 } catch (PackageParserException e) { 13555 // Ignored; we tried our best 13556 } 13557 } 13558 13559 cleanUp(); 13560 removeDexFiles(allCodePaths, instructionSets); 13561 } 13562 13563 boolean doPostDeleteLI(boolean delete) { 13564 // XXX err, shouldn't we respect the delete flag? 13565 cleanUpResourcesLI(); 13566 return true; 13567 } 13568 } 13569 13570 private boolean isAsecExternal(String cid) { 13571 final String asecPath = PackageHelper.getSdFilesystem(cid); 13572 return !asecPath.startsWith(mAsecInternalPath); 13573 } 13574 13575 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13576 PackageManagerException { 13577 if (copyRet < 0) { 13578 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13579 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13580 throw new PackageManagerException(copyRet, message); 13581 } 13582 } 13583 } 13584 13585 /** 13586 * Extract the MountService "container ID" from the full code path of an 13587 * .apk. 13588 */ 13589 static String cidFromCodePath(String fullCodePath) { 13590 int eidx = fullCodePath.lastIndexOf("/"); 13591 String subStr1 = fullCodePath.substring(0, eidx); 13592 int sidx = subStr1.lastIndexOf("/"); 13593 return subStr1.substring(sidx+1, eidx); 13594 } 13595 13596 /** 13597 * Logic to handle installation of ASEC applications, including copying and 13598 * renaming logic. 13599 */ 13600 class AsecInstallArgs extends InstallArgs { 13601 static final String RES_FILE_NAME = "pkg.apk"; 13602 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13603 13604 String cid; 13605 String packagePath; 13606 String resourcePath; 13607 13608 /** New install */ 13609 AsecInstallArgs(InstallParams params) { 13610 super(params.origin, params.move, params.observer, params.installFlags, 13611 params.installerPackageName, params.volumeUuid, 13612 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13613 params.grantedRuntimePermissions, 13614 params.traceMethod, params.traceCookie, params.certificates); 13615 } 13616 13617 /** Existing install */ 13618 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13619 boolean isExternal, boolean isForwardLocked) { 13620 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13621 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13622 instructionSets, null, null, null, 0, null /*certificates*/); 13623 // Hackily pretend we're still looking at a full code path 13624 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13625 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13626 } 13627 13628 // Extract cid from fullCodePath 13629 int eidx = fullCodePath.lastIndexOf("/"); 13630 String subStr1 = fullCodePath.substring(0, eidx); 13631 int sidx = subStr1.lastIndexOf("/"); 13632 cid = subStr1.substring(sidx+1, eidx); 13633 setMountPath(subStr1); 13634 } 13635 13636 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13637 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13638 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13639 instructionSets, null, null, null, 0, null /*certificates*/); 13640 this.cid = cid; 13641 setMountPath(PackageHelper.getSdDir(cid)); 13642 } 13643 13644 void createCopyFile() { 13645 cid = mInstallerService.allocateExternalStageCidLegacy(); 13646 } 13647 13648 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13649 if (origin.staged && origin.cid != null) { 13650 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13651 cid = origin.cid; 13652 setMountPath(PackageHelper.getSdDir(cid)); 13653 return PackageManager.INSTALL_SUCCEEDED; 13654 } 13655 13656 if (temp) { 13657 createCopyFile(); 13658 } else { 13659 /* 13660 * Pre-emptively destroy the container since it's destroyed if 13661 * copying fails due to it existing anyway. 13662 */ 13663 PackageHelper.destroySdDir(cid); 13664 } 13665 13666 final String newMountPath = imcs.copyPackageToContainer( 13667 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13668 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13669 13670 if (newMountPath != null) { 13671 setMountPath(newMountPath); 13672 return PackageManager.INSTALL_SUCCEEDED; 13673 } else { 13674 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13675 } 13676 } 13677 13678 @Override 13679 String getCodePath() { 13680 return packagePath; 13681 } 13682 13683 @Override 13684 String getResourcePath() { 13685 return resourcePath; 13686 } 13687 13688 int doPreInstall(int status) { 13689 if (status != PackageManager.INSTALL_SUCCEEDED) { 13690 // Destroy container 13691 PackageHelper.destroySdDir(cid); 13692 } else { 13693 boolean mounted = PackageHelper.isContainerMounted(cid); 13694 if (!mounted) { 13695 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13696 Process.SYSTEM_UID); 13697 if (newMountPath != null) { 13698 setMountPath(newMountPath); 13699 } else { 13700 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13701 } 13702 } 13703 } 13704 return status; 13705 } 13706 13707 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13708 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13709 String newMountPath = null; 13710 if (PackageHelper.isContainerMounted(cid)) { 13711 // Unmount the container 13712 if (!PackageHelper.unMountSdDir(cid)) { 13713 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13714 return false; 13715 } 13716 } 13717 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13718 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13719 " which might be stale. Will try to clean up."); 13720 // Clean up the stale container and proceed to recreate. 13721 if (!PackageHelper.destroySdDir(newCacheId)) { 13722 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13723 return false; 13724 } 13725 // Successfully cleaned up stale container. Try to rename again. 13726 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13727 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13728 + " inspite of cleaning it up."); 13729 return false; 13730 } 13731 } 13732 if (!PackageHelper.isContainerMounted(newCacheId)) { 13733 Slog.w(TAG, "Mounting container " + newCacheId); 13734 newMountPath = PackageHelper.mountSdDir(newCacheId, 13735 getEncryptKey(), Process.SYSTEM_UID); 13736 } else { 13737 newMountPath = PackageHelper.getSdDir(newCacheId); 13738 } 13739 if (newMountPath == null) { 13740 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13741 return false; 13742 } 13743 Log.i(TAG, "Succesfully renamed " + cid + 13744 " to " + newCacheId + 13745 " at new path: " + newMountPath); 13746 cid = newCacheId; 13747 13748 final File beforeCodeFile = new File(packagePath); 13749 setMountPath(newMountPath); 13750 final File afterCodeFile = new File(packagePath); 13751 13752 // Reflect the rename in scanned details 13753 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13754 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13755 afterCodeFile, pkg.baseCodePath)); 13756 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13757 afterCodeFile, pkg.splitCodePaths)); 13758 13759 // Reflect the rename in app info 13760 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13761 pkg.setApplicationInfoCodePath(pkg.codePath); 13762 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13763 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13764 pkg.setApplicationInfoResourcePath(pkg.codePath); 13765 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13766 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13767 13768 return true; 13769 } 13770 13771 private void setMountPath(String mountPath) { 13772 final File mountFile = new File(mountPath); 13773 13774 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13775 if (monolithicFile.exists()) { 13776 packagePath = monolithicFile.getAbsolutePath(); 13777 if (isFwdLocked()) { 13778 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13779 } else { 13780 resourcePath = packagePath; 13781 } 13782 } else { 13783 packagePath = mountFile.getAbsolutePath(); 13784 resourcePath = packagePath; 13785 } 13786 } 13787 13788 int doPostInstall(int status, int uid) { 13789 if (status != PackageManager.INSTALL_SUCCEEDED) { 13790 cleanUp(); 13791 } else { 13792 final int groupOwner; 13793 final String protectedFile; 13794 if (isFwdLocked()) { 13795 groupOwner = UserHandle.getSharedAppGid(uid); 13796 protectedFile = RES_FILE_NAME; 13797 } else { 13798 groupOwner = -1; 13799 protectedFile = null; 13800 } 13801 13802 if (uid < Process.FIRST_APPLICATION_UID 13803 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13804 Slog.e(TAG, "Failed to finalize " + cid); 13805 PackageHelper.destroySdDir(cid); 13806 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13807 } 13808 13809 boolean mounted = PackageHelper.isContainerMounted(cid); 13810 if (!mounted) { 13811 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13812 } 13813 } 13814 return status; 13815 } 13816 13817 private void cleanUp() { 13818 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13819 13820 // Destroy secure container 13821 PackageHelper.destroySdDir(cid); 13822 } 13823 13824 private List<String> getAllCodePaths() { 13825 final File codeFile = new File(getCodePath()); 13826 if (codeFile != null && codeFile.exists()) { 13827 try { 13828 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13829 return pkg.getAllCodePaths(); 13830 } catch (PackageParserException e) { 13831 // Ignored; we tried our best 13832 } 13833 } 13834 return Collections.EMPTY_LIST; 13835 } 13836 13837 void cleanUpResourcesLI() { 13838 // Enumerate all code paths before deleting 13839 cleanUpResourcesLI(getAllCodePaths()); 13840 } 13841 13842 private void cleanUpResourcesLI(List<String> allCodePaths) { 13843 cleanUp(); 13844 removeDexFiles(allCodePaths, instructionSets); 13845 } 13846 13847 String getPackageName() { 13848 return getAsecPackageName(cid); 13849 } 13850 13851 boolean doPostDeleteLI(boolean delete) { 13852 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13853 final List<String> allCodePaths = getAllCodePaths(); 13854 boolean mounted = PackageHelper.isContainerMounted(cid); 13855 if (mounted) { 13856 // Unmount first 13857 if (PackageHelper.unMountSdDir(cid)) { 13858 mounted = false; 13859 } 13860 } 13861 if (!mounted && delete) { 13862 cleanUpResourcesLI(allCodePaths); 13863 } 13864 return !mounted; 13865 } 13866 13867 @Override 13868 int doPreCopy() { 13869 if (isFwdLocked()) { 13870 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13871 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13872 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13873 } 13874 } 13875 13876 return PackageManager.INSTALL_SUCCEEDED; 13877 } 13878 13879 @Override 13880 int doPostCopy(int uid) { 13881 if (isFwdLocked()) { 13882 if (uid < Process.FIRST_APPLICATION_UID 13883 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13884 RES_FILE_NAME)) { 13885 Slog.e(TAG, "Failed to finalize " + cid); 13886 PackageHelper.destroySdDir(cid); 13887 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13888 } 13889 } 13890 13891 return PackageManager.INSTALL_SUCCEEDED; 13892 } 13893 } 13894 13895 /** 13896 * Logic to handle movement of existing installed applications. 13897 */ 13898 class MoveInstallArgs extends InstallArgs { 13899 private File codeFile; 13900 private File resourceFile; 13901 13902 /** New install */ 13903 MoveInstallArgs(InstallParams params) { 13904 super(params.origin, params.move, params.observer, params.installFlags, 13905 params.installerPackageName, params.volumeUuid, 13906 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13907 params.grantedRuntimePermissions, 13908 params.traceMethod, params.traceCookie, params.certificates); 13909 } 13910 13911 int copyApk(IMediaContainerService imcs, boolean temp) { 13912 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13913 + move.fromUuid + " to " + move.toUuid); 13914 synchronized (mInstaller) { 13915 try { 13916 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13917 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13918 } catch (InstallerException e) { 13919 Slog.w(TAG, "Failed to move app", e); 13920 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13921 } 13922 } 13923 13924 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13925 resourceFile = codeFile; 13926 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13927 13928 return PackageManager.INSTALL_SUCCEEDED; 13929 } 13930 13931 int doPreInstall(int status) { 13932 if (status != PackageManager.INSTALL_SUCCEEDED) { 13933 cleanUp(move.toUuid); 13934 } 13935 return status; 13936 } 13937 13938 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13939 if (status != PackageManager.INSTALL_SUCCEEDED) { 13940 cleanUp(move.toUuid); 13941 return false; 13942 } 13943 13944 // Reflect the move in app info 13945 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13946 pkg.setApplicationInfoCodePath(pkg.codePath); 13947 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13948 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13949 pkg.setApplicationInfoResourcePath(pkg.codePath); 13950 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13951 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13952 13953 return true; 13954 } 13955 13956 int doPostInstall(int status, int uid) { 13957 if (status == PackageManager.INSTALL_SUCCEEDED) { 13958 cleanUp(move.fromUuid); 13959 } else { 13960 cleanUp(move.toUuid); 13961 } 13962 return status; 13963 } 13964 13965 @Override 13966 String getCodePath() { 13967 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13968 } 13969 13970 @Override 13971 String getResourcePath() { 13972 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13973 } 13974 13975 private boolean cleanUp(String volumeUuid) { 13976 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13977 move.dataAppName); 13978 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13979 final int[] userIds = sUserManager.getUserIds(); 13980 synchronized (mInstallLock) { 13981 // Clean up both app data and code 13982 // All package moves are frozen until finished 13983 for (int userId : userIds) { 13984 try { 13985 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13986 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13987 } catch (InstallerException e) { 13988 Slog.w(TAG, String.valueOf(e)); 13989 } 13990 } 13991 removeCodePathLI(codeFile); 13992 } 13993 return true; 13994 } 13995 13996 void cleanUpResourcesLI() { 13997 throw new UnsupportedOperationException(); 13998 } 13999 14000 boolean doPostDeleteLI(boolean delete) { 14001 throw new UnsupportedOperationException(); 14002 } 14003 } 14004 14005 static String getAsecPackageName(String packageCid) { 14006 int idx = packageCid.lastIndexOf("-"); 14007 if (idx == -1) { 14008 return packageCid; 14009 } 14010 return packageCid.substring(0, idx); 14011 } 14012 14013 // Utility method used to create code paths based on package name and available index. 14014 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14015 String idxStr = ""; 14016 int idx = 1; 14017 // Fall back to default value of idx=1 if prefix is not 14018 // part of oldCodePath 14019 if (oldCodePath != null) { 14020 String subStr = oldCodePath; 14021 // Drop the suffix right away 14022 if (suffix != null && subStr.endsWith(suffix)) { 14023 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14024 } 14025 // If oldCodePath already contains prefix find out the 14026 // ending index to either increment or decrement. 14027 int sidx = subStr.lastIndexOf(prefix); 14028 if (sidx != -1) { 14029 subStr = subStr.substring(sidx + prefix.length()); 14030 if (subStr != null) { 14031 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14032 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14033 } 14034 try { 14035 idx = Integer.parseInt(subStr); 14036 if (idx <= 1) { 14037 idx++; 14038 } else { 14039 idx--; 14040 } 14041 } catch(NumberFormatException e) { 14042 } 14043 } 14044 } 14045 } 14046 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14047 return prefix + idxStr; 14048 } 14049 14050 private File getNextCodePath(File targetDir, String packageName) { 14051 int suffix = 1; 14052 File result; 14053 do { 14054 result = new File(targetDir, packageName + "-" + suffix); 14055 suffix++; 14056 } while (result.exists()); 14057 return result; 14058 } 14059 14060 // Utility method that returns the relative package path with respect 14061 // to the installation directory. Like say for /data/data/com.test-1.apk 14062 // string com.test-1 is returned. 14063 static String deriveCodePathName(String codePath) { 14064 if (codePath == null) { 14065 return null; 14066 } 14067 final File codeFile = new File(codePath); 14068 final String name = codeFile.getName(); 14069 if (codeFile.isDirectory()) { 14070 return name; 14071 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14072 final int lastDot = name.lastIndexOf('.'); 14073 return name.substring(0, lastDot); 14074 } else { 14075 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14076 return null; 14077 } 14078 } 14079 14080 static class PackageInstalledInfo { 14081 String name; 14082 int uid; 14083 // The set of users that originally had this package installed. 14084 int[] origUsers; 14085 // The set of users that now have this package installed. 14086 int[] newUsers; 14087 PackageParser.Package pkg; 14088 int returnCode; 14089 String returnMsg; 14090 PackageRemovedInfo removedInfo; 14091 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14092 14093 public void setError(int code, String msg) { 14094 setReturnCode(code); 14095 setReturnMessage(msg); 14096 Slog.w(TAG, msg); 14097 } 14098 14099 public void setError(String msg, PackageParserException e) { 14100 setReturnCode(e.error); 14101 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14102 Slog.w(TAG, msg, e); 14103 } 14104 14105 public void setError(String msg, PackageManagerException e) { 14106 returnCode = e.error; 14107 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14108 Slog.w(TAG, msg, e); 14109 } 14110 14111 public void setReturnCode(int returnCode) { 14112 this.returnCode = returnCode; 14113 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14114 for (int i = 0; i < childCount; i++) { 14115 addedChildPackages.valueAt(i).returnCode = returnCode; 14116 } 14117 } 14118 14119 private void setReturnMessage(String returnMsg) { 14120 this.returnMsg = returnMsg; 14121 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14122 for (int i = 0; i < childCount; i++) { 14123 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14124 } 14125 } 14126 14127 // In some error cases we want to convey more info back to the observer 14128 String origPackage; 14129 String origPermission; 14130 } 14131 14132 /* 14133 * Install a non-existing package. 14134 */ 14135 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14136 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14137 PackageInstalledInfo res) { 14138 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14139 14140 // Remember this for later, in case we need to rollback this install 14141 String pkgName = pkg.packageName; 14142 14143 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14144 14145 synchronized(mPackages) { 14146 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14147 // A package with the same name is already installed, though 14148 // it has been renamed to an older name. The package we 14149 // are trying to install should be installed as an update to 14150 // the existing one, but that has not been requested, so bail. 14151 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14152 + " without first uninstalling package running as " 14153 + mSettings.mRenamedPackages.get(pkgName)); 14154 return; 14155 } 14156 if (mPackages.containsKey(pkgName)) { 14157 // Don't allow installation over an existing package with the same name. 14158 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14159 + " without first uninstalling."); 14160 return; 14161 } 14162 } 14163 14164 try { 14165 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14166 System.currentTimeMillis(), user); 14167 14168 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14169 14170 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14171 prepareAppDataAfterInstallLIF(newPackage); 14172 14173 } else { 14174 // Remove package from internal structures, but keep around any 14175 // data that might have already existed 14176 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14177 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14178 } 14179 } catch (PackageManagerException e) { 14180 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14181 } 14182 14183 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14184 } 14185 14186 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14187 // Can't rotate keys during boot or if sharedUser. 14188 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14189 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14190 return false; 14191 } 14192 // app is using upgradeKeySets; make sure all are valid 14193 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14194 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14195 for (int i = 0; i < upgradeKeySets.length; i++) { 14196 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14197 Slog.wtf(TAG, "Package " 14198 + (oldPs.name != null ? oldPs.name : "<null>") 14199 + " contains upgrade-key-set reference to unknown key-set: " 14200 + upgradeKeySets[i] 14201 + " reverting to signatures check."); 14202 return false; 14203 } 14204 } 14205 return true; 14206 } 14207 14208 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14209 // Upgrade keysets are being used. Determine if new package has a superset of the 14210 // required keys. 14211 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14212 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14213 for (int i = 0; i < upgradeKeySets.length; i++) { 14214 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14215 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14216 return true; 14217 } 14218 } 14219 return false; 14220 } 14221 14222 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14223 try (DigestInputStream digestStream = 14224 new DigestInputStream(new FileInputStream(file), digest)) { 14225 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14226 } 14227 } 14228 14229 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14230 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14231 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14232 14233 final PackageParser.Package oldPackage; 14234 final String pkgName = pkg.packageName; 14235 final int[] allUsers; 14236 final int[] installedUsers; 14237 14238 synchronized(mPackages) { 14239 oldPackage = mPackages.get(pkgName); 14240 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14241 14242 // don't allow upgrade to target a release SDK from a pre-release SDK 14243 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14244 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14245 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14246 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14247 if (oldTargetsPreRelease 14248 && !newTargetsPreRelease 14249 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14250 Slog.w(TAG, "Can't install package targeting released sdk"); 14251 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14252 return; 14253 } 14254 14255 // don't allow an upgrade from full to ephemeral 14256 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14257 if (isEphemeral && !oldIsEphemeral) { 14258 // can't downgrade from full to ephemeral 14259 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14260 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14261 return; 14262 } 14263 14264 // verify signatures are valid 14265 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14266 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14267 if (!checkUpgradeKeySetLP(ps, pkg)) { 14268 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14269 "New package not signed by keys specified by upgrade-keysets: " 14270 + pkgName); 14271 return; 14272 } 14273 } else { 14274 // default to original signature matching 14275 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14276 != PackageManager.SIGNATURE_MATCH) { 14277 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14278 "New package has a different signature: " + pkgName); 14279 return; 14280 } 14281 } 14282 14283 // don't allow a system upgrade unless the upgrade hash matches 14284 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14285 byte[] digestBytes = null; 14286 try { 14287 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14288 updateDigest(digest, new File(pkg.baseCodePath)); 14289 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14290 for (String path : pkg.splitCodePaths) { 14291 updateDigest(digest, new File(path)); 14292 } 14293 } 14294 digestBytes = digest.digest(); 14295 } catch (NoSuchAlgorithmException | IOException e) { 14296 res.setError(INSTALL_FAILED_INVALID_APK, 14297 "Could not compute hash: " + pkgName); 14298 return; 14299 } 14300 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14301 res.setError(INSTALL_FAILED_INVALID_APK, 14302 "New package fails restrict-update check: " + pkgName); 14303 return; 14304 } 14305 // retain upgrade restriction 14306 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14307 } 14308 14309 // Check for shared user id changes 14310 String invalidPackageName = 14311 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14312 if (invalidPackageName != null) { 14313 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14314 "Package " + invalidPackageName + " tried to change user " 14315 + oldPackage.mSharedUserId); 14316 return; 14317 } 14318 14319 // In case of rollback, remember per-user/profile install state 14320 allUsers = sUserManager.getUserIds(); 14321 installedUsers = ps.queryInstalledUsers(allUsers, true); 14322 } 14323 14324 // Update what is removed 14325 res.removedInfo = new PackageRemovedInfo(); 14326 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14327 res.removedInfo.removedPackage = oldPackage.packageName; 14328 res.removedInfo.isUpdate = true; 14329 res.removedInfo.origUsers = installedUsers; 14330 final int childCount = (oldPackage.childPackages != null) 14331 ? oldPackage.childPackages.size() : 0; 14332 for (int i = 0; i < childCount; i++) { 14333 boolean childPackageUpdated = false; 14334 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14335 if (res.addedChildPackages != null) { 14336 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14337 if (childRes != null) { 14338 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14339 childRes.removedInfo.removedPackage = childPkg.packageName; 14340 childRes.removedInfo.isUpdate = true; 14341 childPackageUpdated = true; 14342 } 14343 } 14344 if (!childPackageUpdated) { 14345 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14346 childRemovedRes.removedPackage = childPkg.packageName; 14347 childRemovedRes.isUpdate = false; 14348 childRemovedRes.dataRemoved = true; 14349 synchronized (mPackages) { 14350 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14351 if (childPs != null) { 14352 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14353 } 14354 } 14355 if (res.removedInfo.removedChildPackages == null) { 14356 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14357 } 14358 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14359 } 14360 } 14361 14362 boolean sysPkg = (isSystemApp(oldPackage)); 14363 if (sysPkg) { 14364 // Set the system/privileged flags as needed 14365 final boolean privileged = 14366 (oldPackage.applicationInfo.privateFlags 14367 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14368 final int systemPolicyFlags = policyFlags 14369 | PackageParser.PARSE_IS_SYSTEM 14370 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14371 14372 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14373 user, allUsers, installerPackageName, res); 14374 } else { 14375 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14376 user, allUsers, installerPackageName, res); 14377 } 14378 } 14379 14380 public List<String> getPreviousCodePaths(String packageName) { 14381 final PackageSetting ps = mSettings.mPackages.get(packageName); 14382 final List<String> result = new ArrayList<String>(); 14383 if (ps != null && ps.oldCodePaths != null) { 14384 result.addAll(ps.oldCodePaths); 14385 } 14386 return result; 14387 } 14388 14389 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14390 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14391 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14392 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14393 + deletedPackage); 14394 14395 String pkgName = deletedPackage.packageName; 14396 boolean deletedPkg = true; 14397 boolean addedPkg = false; 14398 boolean updatedSettings = false; 14399 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14400 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14401 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14402 14403 final long origUpdateTime = (pkg.mExtras != null) 14404 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14405 14406 // First delete the existing package while retaining the data directory 14407 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14408 res.removedInfo, true, pkg)) { 14409 // If the existing package wasn't successfully deleted 14410 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14411 deletedPkg = false; 14412 } else { 14413 // Successfully deleted the old package; proceed with replace. 14414 14415 // If deleted package lived in a container, give users a chance to 14416 // relinquish resources before killing. 14417 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14418 if (DEBUG_INSTALL) { 14419 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14420 } 14421 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14422 final ArrayList<String> pkgList = new ArrayList<String>(1); 14423 pkgList.add(deletedPackage.applicationInfo.packageName); 14424 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14425 } 14426 14427 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14428 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14429 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14430 14431 try { 14432 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14433 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14434 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14435 14436 // Update the in-memory copy of the previous code paths. 14437 PackageSetting ps = mSettings.mPackages.get(pkgName); 14438 if (!killApp) { 14439 if (ps.oldCodePaths == null) { 14440 ps.oldCodePaths = new ArraySet<>(); 14441 } 14442 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14443 if (deletedPackage.splitCodePaths != null) { 14444 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14445 } 14446 } else { 14447 ps.oldCodePaths = null; 14448 } 14449 if (ps.childPackageNames != null) { 14450 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14451 final String childPkgName = ps.childPackageNames.get(i); 14452 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14453 childPs.oldCodePaths = ps.oldCodePaths; 14454 } 14455 } 14456 prepareAppDataAfterInstallLIF(newPackage); 14457 addedPkg = true; 14458 mDexManager.notifyPackageUpdated(newPackage.packageName, 14459 newPackage.baseCodePath, newPackage.splitCodePaths); 14460 } catch (PackageManagerException e) { 14461 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14462 } 14463 } 14464 14465 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14466 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14467 14468 // Revert all internal state mutations and added folders for the failed install 14469 if (addedPkg) { 14470 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14471 res.removedInfo, true, null); 14472 } 14473 14474 // Restore the old package 14475 if (deletedPkg) { 14476 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14477 File restoreFile = new File(deletedPackage.codePath); 14478 // Parse old package 14479 boolean oldExternal = isExternal(deletedPackage); 14480 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14481 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14482 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14483 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14484 try { 14485 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14486 null); 14487 } catch (PackageManagerException e) { 14488 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14489 + e.getMessage()); 14490 return; 14491 } 14492 14493 synchronized (mPackages) { 14494 // Ensure the installer package name up to date 14495 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14496 14497 // Update permissions for restored package 14498 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14499 14500 mSettings.writeLPr(); 14501 } 14502 14503 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14504 } 14505 } else { 14506 synchronized (mPackages) { 14507 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14508 if (ps != null) { 14509 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14510 if (res.removedInfo.removedChildPackages != null) { 14511 final int childCount = res.removedInfo.removedChildPackages.size(); 14512 // Iterate in reverse as we may modify the collection 14513 for (int i = childCount - 1; i >= 0; i--) { 14514 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14515 if (res.addedChildPackages.containsKey(childPackageName)) { 14516 res.removedInfo.removedChildPackages.removeAt(i); 14517 } else { 14518 PackageRemovedInfo childInfo = res.removedInfo 14519 .removedChildPackages.valueAt(i); 14520 childInfo.removedForAllUsers = mPackages.get( 14521 childInfo.removedPackage) == null; 14522 } 14523 } 14524 } 14525 } 14526 } 14527 } 14528 } 14529 14530 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14531 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14532 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14533 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14534 + ", old=" + deletedPackage); 14535 14536 final boolean disabledSystem; 14537 14538 // Remove existing system package 14539 removePackageLI(deletedPackage, true); 14540 14541 synchronized (mPackages) { 14542 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14543 } 14544 if (!disabledSystem) { 14545 // We didn't need to disable the .apk as a current system package, 14546 // which means we are replacing another update that is already 14547 // installed. We need to make sure to delete the older one's .apk. 14548 res.removedInfo.args = createInstallArgsForExisting(0, 14549 deletedPackage.applicationInfo.getCodePath(), 14550 deletedPackage.applicationInfo.getResourcePath(), 14551 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14552 } else { 14553 res.removedInfo.args = null; 14554 } 14555 14556 // Successfully disabled the old package. Now proceed with re-installation 14557 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14558 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14559 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14560 14561 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14562 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14563 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14564 14565 PackageParser.Package newPackage = null; 14566 try { 14567 // Add the package to the internal data structures 14568 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14569 14570 // Set the update and install times 14571 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14572 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14573 System.currentTimeMillis()); 14574 14575 // Update the package dynamic state if succeeded 14576 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14577 // Now that the install succeeded make sure we remove data 14578 // directories for any child package the update removed. 14579 final int deletedChildCount = (deletedPackage.childPackages != null) 14580 ? deletedPackage.childPackages.size() : 0; 14581 final int newChildCount = (newPackage.childPackages != null) 14582 ? newPackage.childPackages.size() : 0; 14583 for (int i = 0; i < deletedChildCount; i++) { 14584 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14585 boolean childPackageDeleted = true; 14586 for (int j = 0; j < newChildCount; j++) { 14587 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14588 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14589 childPackageDeleted = false; 14590 break; 14591 } 14592 } 14593 if (childPackageDeleted) { 14594 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14595 deletedChildPkg.packageName); 14596 if (ps != null && res.removedInfo.removedChildPackages != null) { 14597 PackageRemovedInfo removedChildRes = res.removedInfo 14598 .removedChildPackages.get(deletedChildPkg.packageName); 14599 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14600 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14601 } 14602 } 14603 } 14604 14605 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14606 prepareAppDataAfterInstallLIF(newPackage); 14607 14608 mDexManager.notifyPackageUpdated(newPackage.packageName, 14609 newPackage.baseCodePath, newPackage.splitCodePaths); 14610 } 14611 } catch (PackageManagerException e) { 14612 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14613 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14614 } 14615 14616 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14617 // Re installation failed. Restore old information 14618 // Remove new pkg information 14619 if (newPackage != null) { 14620 removeInstalledPackageLI(newPackage, true); 14621 } 14622 // Add back the old system package 14623 try { 14624 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14625 } catch (PackageManagerException e) { 14626 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14627 } 14628 14629 synchronized (mPackages) { 14630 if (disabledSystem) { 14631 enableSystemPackageLPw(deletedPackage); 14632 } 14633 14634 // Ensure the installer package name up to date 14635 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14636 14637 // Update permissions for restored package 14638 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14639 14640 mSettings.writeLPr(); 14641 } 14642 14643 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14644 + " after failed upgrade"); 14645 } 14646 } 14647 14648 /** 14649 * Checks whether the parent or any of the child packages have a change shared 14650 * user. For a package to be a valid update the shred users of the parent and 14651 * the children should match. We may later support changing child shared users. 14652 * @param oldPkg The updated package. 14653 * @param newPkg The update package. 14654 * @return The shared user that change between the versions. 14655 */ 14656 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14657 PackageParser.Package newPkg) { 14658 // Check parent shared user 14659 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14660 return newPkg.packageName; 14661 } 14662 // Check child shared users 14663 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14664 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14665 for (int i = 0; i < newChildCount; i++) { 14666 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14667 // If this child was present, did it have the same shared user? 14668 for (int j = 0; j < oldChildCount; j++) { 14669 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14670 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14671 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14672 return newChildPkg.packageName; 14673 } 14674 } 14675 } 14676 return null; 14677 } 14678 14679 private void removeNativeBinariesLI(PackageSetting ps) { 14680 // Remove the lib path for the parent package 14681 if (ps != null) { 14682 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14683 // Remove the lib path for the child packages 14684 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14685 for (int i = 0; i < childCount; i++) { 14686 PackageSetting childPs = null; 14687 synchronized (mPackages) { 14688 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14689 } 14690 if (childPs != null) { 14691 NativeLibraryHelper.removeNativeBinariesLI(childPs 14692 .legacyNativeLibraryPathString); 14693 } 14694 } 14695 } 14696 } 14697 14698 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14699 // Enable the parent package 14700 mSettings.enableSystemPackageLPw(pkg.packageName); 14701 // Enable the child packages 14702 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14703 for (int i = 0; i < childCount; i++) { 14704 PackageParser.Package childPkg = pkg.childPackages.get(i); 14705 mSettings.enableSystemPackageLPw(childPkg.packageName); 14706 } 14707 } 14708 14709 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14710 PackageParser.Package newPkg) { 14711 // Disable the parent package (parent always replaced) 14712 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14713 // Disable the child packages 14714 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14715 for (int i = 0; i < childCount; i++) { 14716 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14717 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14718 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14719 } 14720 return disabled; 14721 } 14722 14723 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14724 String installerPackageName) { 14725 // Enable the parent package 14726 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14727 // Enable the child packages 14728 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14729 for (int i = 0; i < childCount; i++) { 14730 PackageParser.Package childPkg = pkg.childPackages.get(i); 14731 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14732 } 14733 } 14734 14735 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14736 // Collect all used permissions in the UID 14737 ArraySet<String> usedPermissions = new ArraySet<>(); 14738 final int packageCount = su.packages.size(); 14739 for (int i = 0; i < packageCount; i++) { 14740 PackageSetting ps = su.packages.valueAt(i); 14741 if (ps.pkg == null) { 14742 continue; 14743 } 14744 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14745 for (int j = 0; j < requestedPermCount; j++) { 14746 String permission = ps.pkg.requestedPermissions.get(j); 14747 BasePermission bp = mSettings.mPermissions.get(permission); 14748 if (bp != null) { 14749 usedPermissions.add(permission); 14750 } 14751 } 14752 } 14753 14754 PermissionsState permissionsState = su.getPermissionsState(); 14755 // Prune install permissions 14756 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14757 final int installPermCount = installPermStates.size(); 14758 for (int i = installPermCount - 1; i >= 0; i--) { 14759 PermissionState permissionState = installPermStates.get(i); 14760 if (!usedPermissions.contains(permissionState.getName())) { 14761 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14762 if (bp != null) { 14763 permissionsState.revokeInstallPermission(bp); 14764 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14765 PackageManager.MASK_PERMISSION_FLAGS, 0); 14766 } 14767 } 14768 } 14769 14770 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14771 14772 // Prune runtime permissions 14773 for (int userId : allUserIds) { 14774 List<PermissionState> runtimePermStates = permissionsState 14775 .getRuntimePermissionStates(userId); 14776 final int runtimePermCount = runtimePermStates.size(); 14777 for (int i = runtimePermCount - 1; i >= 0; i--) { 14778 PermissionState permissionState = runtimePermStates.get(i); 14779 if (!usedPermissions.contains(permissionState.getName())) { 14780 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14781 if (bp != null) { 14782 permissionsState.revokeRuntimePermission(bp, userId); 14783 permissionsState.updatePermissionFlags(bp, userId, 14784 PackageManager.MASK_PERMISSION_FLAGS, 0); 14785 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14786 runtimePermissionChangedUserIds, userId); 14787 } 14788 } 14789 } 14790 } 14791 14792 return runtimePermissionChangedUserIds; 14793 } 14794 14795 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14796 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14797 // Update the parent package setting 14798 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14799 res, user); 14800 // Update the child packages setting 14801 final int childCount = (newPackage.childPackages != null) 14802 ? newPackage.childPackages.size() : 0; 14803 for (int i = 0; i < childCount; i++) { 14804 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14805 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14806 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14807 childRes.origUsers, childRes, user); 14808 } 14809 } 14810 14811 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14812 String installerPackageName, int[] allUsers, int[] installedForUsers, 14813 PackageInstalledInfo res, UserHandle user) { 14814 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14815 14816 String pkgName = newPackage.packageName; 14817 synchronized (mPackages) { 14818 //write settings. the installStatus will be incomplete at this stage. 14819 //note that the new package setting would have already been 14820 //added to mPackages. It hasn't been persisted yet. 14821 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14822 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14823 mSettings.writeLPr(); 14824 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14825 } 14826 14827 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14828 synchronized (mPackages) { 14829 updatePermissionsLPw(newPackage.packageName, newPackage, 14830 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14831 ? UPDATE_PERMISSIONS_ALL : 0)); 14832 // For system-bundled packages, we assume that installing an upgraded version 14833 // of the package implies that the user actually wants to run that new code, 14834 // so we enable the package. 14835 PackageSetting ps = mSettings.mPackages.get(pkgName); 14836 final int userId = user.getIdentifier(); 14837 if (ps != null) { 14838 if (isSystemApp(newPackage)) { 14839 if (DEBUG_INSTALL) { 14840 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14841 } 14842 // Enable system package for requested users 14843 if (res.origUsers != null) { 14844 for (int origUserId : res.origUsers) { 14845 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14846 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14847 origUserId, installerPackageName); 14848 } 14849 } 14850 } 14851 // Also convey the prior install/uninstall state 14852 if (allUsers != null && installedForUsers != null) { 14853 for (int currentUserId : allUsers) { 14854 final boolean installed = ArrayUtils.contains( 14855 installedForUsers, currentUserId); 14856 if (DEBUG_INSTALL) { 14857 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14858 } 14859 ps.setInstalled(installed, currentUserId); 14860 } 14861 // these install state changes will be persisted in the 14862 // upcoming call to mSettings.writeLPr(). 14863 } 14864 } 14865 // It's implied that when a user requests installation, they want the app to be 14866 // installed and enabled. 14867 if (userId != UserHandle.USER_ALL) { 14868 ps.setInstalled(true, userId); 14869 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14870 } 14871 } 14872 res.name = pkgName; 14873 res.uid = newPackage.applicationInfo.uid; 14874 res.pkg = newPackage; 14875 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14876 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14877 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14878 //to update install status 14879 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14880 mSettings.writeLPr(); 14881 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14882 } 14883 14884 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14885 } 14886 14887 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14888 try { 14889 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14890 installPackageLI(args, res); 14891 } finally { 14892 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14893 } 14894 } 14895 14896 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14897 final int installFlags = args.installFlags; 14898 final String installerPackageName = args.installerPackageName; 14899 final String volumeUuid = args.volumeUuid; 14900 final File tmpPackageFile = new File(args.getCodePath()); 14901 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14902 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14903 || (args.volumeUuid != null)); 14904 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14905 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14906 boolean replace = false; 14907 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14908 if (args.move != null) { 14909 // moving a complete application; perform an initial scan on the new install location 14910 scanFlags |= SCAN_INITIAL; 14911 } 14912 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14913 scanFlags |= SCAN_DONT_KILL_APP; 14914 } 14915 14916 // Result object to be returned 14917 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14918 14919 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14920 14921 // Sanity check 14922 if (ephemeral && (forwardLocked || onExternal)) { 14923 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14924 + " external=" + onExternal); 14925 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14926 return; 14927 } 14928 14929 // Retrieve PackageSettings and parse package 14930 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14931 | PackageParser.PARSE_ENFORCE_CODE 14932 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14933 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14934 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14935 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14936 PackageParser pp = new PackageParser(); 14937 pp.setSeparateProcesses(mSeparateProcesses); 14938 pp.setDisplayMetrics(mMetrics); 14939 14940 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14941 final PackageParser.Package pkg; 14942 try { 14943 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14944 } catch (PackageParserException e) { 14945 res.setError("Failed parse during installPackageLI", e); 14946 return; 14947 } finally { 14948 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14949 } 14950 14951 // If we are installing a clustered package add results for the children 14952 if (pkg.childPackages != null) { 14953 synchronized (mPackages) { 14954 final int childCount = pkg.childPackages.size(); 14955 for (int i = 0; i < childCount; i++) { 14956 PackageParser.Package childPkg = pkg.childPackages.get(i); 14957 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14958 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14959 childRes.pkg = childPkg; 14960 childRes.name = childPkg.packageName; 14961 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14962 if (childPs != null) { 14963 childRes.origUsers = childPs.queryInstalledUsers( 14964 sUserManager.getUserIds(), true); 14965 } 14966 if ((mPackages.containsKey(childPkg.packageName))) { 14967 childRes.removedInfo = new PackageRemovedInfo(); 14968 childRes.removedInfo.removedPackage = childPkg.packageName; 14969 } 14970 if (res.addedChildPackages == null) { 14971 res.addedChildPackages = new ArrayMap<>(); 14972 } 14973 res.addedChildPackages.put(childPkg.packageName, childRes); 14974 } 14975 } 14976 } 14977 14978 // If package doesn't declare API override, mark that we have an install 14979 // time CPU ABI override. 14980 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14981 pkg.cpuAbiOverride = args.abiOverride; 14982 } 14983 14984 String pkgName = res.name = pkg.packageName; 14985 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14986 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14987 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14988 return; 14989 } 14990 } 14991 14992 try { 14993 // either use what we've been given or parse directly from the APK 14994 if (args.certificates != null) { 14995 try { 14996 PackageParser.populateCertificates(pkg, args.certificates); 14997 } catch (PackageParserException e) { 14998 // there was something wrong with the certificates we were given; 14999 // try to pull them from the APK 15000 PackageParser.collectCertificates(pkg, parseFlags); 15001 } 15002 } else { 15003 PackageParser.collectCertificates(pkg, parseFlags); 15004 } 15005 } catch (PackageParserException e) { 15006 res.setError("Failed collect during installPackageLI", e); 15007 return; 15008 } 15009 15010 // Get rid of all references to package scan path via parser. 15011 pp = null; 15012 String oldCodePath = null; 15013 boolean systemApp = false; 15014 synchronized (mPackages) { 15015 // Check if installing already existing package 15016 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15017 String oldName = mSettings.mRenamedPackages.get(pkgName); 15018 if (pkg.mOriginalPackages != null 15019 && pkg.mOriginalPackages.contains(oldName) 15020 && mPackages.containsKey(oldName)) { 15021 // This package is derived from an original package, 15022 // and this device has been updating from that original 15023 // name. We must continue using the original name, so 15024 // rename the new package here. 15025 pkg.setPackageName(oldName); 15026 pkgName = pkg.packageName; 15027 replace = true; 15028 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15029 + oldName + " pkgName=" + pkgName); 15030 } else if (mPackages.containsKey(pkgName)) { 15031 // This package, under its official name, already exists 15032 // on the device; we should replace it. 15033 replace = true; 15034 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15035 } 15036 15037 // Child packages are installed through the parent package 15038 if (pkg.parentPackage != null) { 15039 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15040 "Package " + pkg.packageName + " is child of package " 15041 + pkg.parentPackage.parentPackage + ". Child packages " 15042 + "can be updated only through the parent package."); 15043 return; 15044 } 15045 15046 if (replace) { 15047 // Prevent apps opting out from runtime permissions 15048 PackageParser.Package oldPackage = mPackages.get(pkgName); 15049 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15050 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15051 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15052 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15053 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15054 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15055 + " doesn't support runtime permissions but the old" 15056 + " target SDK " + oldTargetSdk + " does."); 15057 return; 15058 } 15059 15060 // Prevent installing of child packages 15061 if (oldPackage.parentPackage != null) { 15062 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15063 "Package " + pkg.packageName + " is child of package " 15064 + oldPackage.parentPackage + ". Child packages " 15065 + "can be updated only through the parent package."); 15066 return; 15067 } 15068 } 15069 } 15070 15071 PackageSetting ps = mSettings.mPackages.get(pkgName); 15072 if (ps != null) { 15073 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15074 15075 // Quick sanity check that we're signed correctly if updating; 15076 // we'll check this again later when scanning, but we want to 15077 // bail early here before tripping over redefined permissions. 15078 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15079 if (!checkUpgradeKeySetLP(ps, pkg)) { 15080 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15081 + pkg.packageName + " upgrade keys do not match the " 15082 + "previously installed version"); 15083 return; 15084 } 15085 } else { 15086 try { 15087 verifySignaturesLP(ps, pkg); 15088 } catch (PackageManagerException e) { 15089 res.setError(e.error, e.getMessage()); 15090 return; 15091 } 15092 } 15093 15094 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15095 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15096 systemApp = (ps.pkg.applicationInfo.flags & 15097 ApplicationInfo.FLAG_SYSTEM) != 0; 15098 } 15099 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15100 } 15101 15102 // Check whether the newly-scanned package wants to define an already-defined perm 15103 int N = pkg.permissions.size(); 15104 for (int i = N-1; i >= 0; i--) { 15105 PackageParser.Permission perm = pkg.permissions.get(i); 15106 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15107 if (bp != null) { 15108 // If the defining package is signed with our cert, it's okay. This 15109 // also includes the "updating the same package" case, of course. 15110 // "updating same package" could also involve key-rotation. 15111 final boolean sigsOk; 15112 if (bp.sourcePackage.equals(pkg.packageName) 15113 && (bp.packageSetting instanceof PackageSetting) 15114 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15115 scanFlags))) { 15116 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15117 } else { 15118 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15119 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15120 } 15121 if (!sigsOk) { 15122 // If the owning package is the system itself, we log but allow 15123 // install to proceed; we fail the install on all other permission 15124 // redefinitions. 15125 if (!bp.sourcePackage.equals("android")) { 15126 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15127 + pkg.packageName + " attempting to redeclare permission " 15128 + perm.info.name + " already owned by " + bp.sourcePackage); 15129 res.origPermission = perm.info.name; 15130 res.origPackage = bp.sourcePackage; 15131 return; 15132 } else { 15133 Slog.w(TAG, "Package " + pkg.packageName 15134 + " attempting to redeclare system permission " 15135 + perm.info.name + "; ignoring new declaration"); 15136 pkg.permissions.remove(i); 15137 } 15138 } 15139 } 15140 } 15141 } 15142 15143 if (systemApp) { 15144 if (onExternal) { 15145 // Abort update; system app can't be replaced with app on sdcard 15146 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15147 "Cannot install updates to system apps on sdcard"); 15148 return; 15149 } else if (ephemeral) { 15150 // Abort update; system app can't be replaced with an ephemeral app 15151 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15152 "Cannot update a system app with an ephemeral app"); 15153 return; 15154 } 15155 } 15156 15157 if (args.move != null) { 15158 // We did an in-place move, so dex is ready to roll 15159 scanFlags |= SCAN_NO_DEX; 15160 scanFlags |= SCAN_MOVE; 15161 15162 synchronized (mPackages) { 15163 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15164 if (ps == null) { 15165 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15166 "Missing settings for moved package " + pkgName); 15167 } 15168 15169 // We moved the entire application as-is, so bring over the 15170 // previously derived ABI information. 15171 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15172 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15173 } 15174 15175 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15176 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15177 scanFlags |= SCAN_NO_DEX; 15178 15179 try { 15180 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15181 args.abiOverride : pkg.cpuAbiOverride); 15182 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15183 true /* extract libs */); 15184 } catch (PackageManagerException pme) { 15185 Slog.e(TAG, "Error deriving application ABI", pme); 15186 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15187 return; 15188 } 15189 15190 // Shared libraries for the package need to be updated. 15191 synchronized (mPackages) { 15192 try { 15193 updateSharedLibrariesLPw(pkg, null); 15194 } catch (PackageManagerException e) { 15195 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15196 } 15197 } 15198 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15199 // Do not run PackageDexOptimizer through the local performDexOpt 15200 // method because `pkg` may not be in `mPackages` yet. 15201 // 15202 // Also, don't fail application installs if the dexopt step fails. 15203 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15204 null /* instructionSets */, false /* checkProfiles */, 15205 getCompilerFilterForReason(REASON_INSTALL), 15206 getOrCreateCompilerPackageStats(pkg), 15207 mDexManager.isUsedByOtherApps(pkg.packageName)); 15208 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15209 15210 // Notify BackgroundDexOptService that the package has been changed. 15211 // If this is an update of a package which used to fail to compile, 15212 // BDOS will remove it from its blacklist. 15213 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15214 } 15215 15216 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15217 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15218 return; 15219 } 15220 15221 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15222 15223 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15224 "installPackageLI")) { 15225 if (replace) { 15226 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15227 installerPackageName, res); 15228 } else { 15229 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15230 args.user, installerPackageName, volumeUuid, res); 15231 } 15232 } 15233 synchronized (mPackages) { 15234 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15235 if (ps != null) { 15236 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15237 } 15238 15239 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15240 for (int i = 0; i < childCount; i++) { 15241 PackageParser.Package childPkg = pkg.childPackages.get(i); 15242 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15243 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15244 if (childPs != null) { 15245 childRes.newUsers = childPs.queryInstalledUsers( 15246 sUserManager.getUserIds(), true); 15247 } 15248 } 15249 } 15250 } 15251 15252 private void startIntentFilterVerifications(int userId, boolean replacing, 15253 PackageParser.Package pkg) { 15254 if (mIntentFilterVerifierComponent == null) { 15255 Slog.w(TAG, "No IntentFilter verification will not be done as " 15256 + "there is no IntentFilterVerifier available!"); 15257 return; 15258 } 15259 15260 final int verifierUid = getPackageUid( 15261 mIntentFilterVerifierComponent.getPackageName(), 15262 MATCH_DEBUG_TRIAGED_MISSING, 15263 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15264 15265 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15266 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15267 mHandler.sendMessage(msg); 15268 15269 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15270 for (int i = 0; i < childCount; i++) { 15271 PackageParser.Package childPkg = pkg.childPackages.get(i); 15272 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15273 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15274 mHandler.sendMessage(msg); 15275 } 15276 } 15277 15278 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15279 PackageParser.Package pkg) { 15280 int size = pkg.activities.size(); 15281 if (size == 0) { 15282 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15283 "No activity, so no need to verify any IntentFilter!"); 15284 return; 15285 } 15286 15287 final boolean hasDomainURLs = hasDomainURLs(pkg); 15288 if (!hasDomainURLs) { 15289 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15290 "No domain URLs, so no need to verify any IntentFilter!"); 15291 return; 15292 } 15293 15294 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15295 + " if any IntentFilter from the " + size 15296 + " Activities needs verification ..."); 15297 15298 int count = 0; 15299 final String packageName = pkg.packageName; 15300 15301 synchronized (mPackages) { 15302 // If this is a new install and we see that we've already run verification for this 15303 // package, we have nothing to do: it means the state was restored from backup. 15304 if (!replacing) { 15305 IntentFilterVerificationInfo ivi = 15306 mSettings.getIntentFilterVerificationLPr(packageName); 15307 if (ivi != null) { 15308 if (DEBUG_DOMAIN_VERIFICATION) { 15309 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15310 + ivi.getStatusString()); 15311 } 15312 return; 15313 } 15314 } 15315 15316 // If any filters need to be verified, then all need to be. 15317 boolean needToVerify = false; 15318 for (PackageParser.Activity a : pkg.activities) { 15319 for (ActivityIntentInfo filter : a.intents) { 15320 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15321 if (DEBUG_DOMAIN_VERIFICATION) { 15322 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15323 } 15324 needToVerify = true; 15325 break; 15326 } 15327 } 15328 } 15329 15330 if (needToVerify) { 15331 final int verificationId = mIntentFilterVerificationToken++; 15332 for (PackageParser.Activity a : pkg.activities) { 15333 for (ActivityIntentInfo filter : a.intents) { 15334 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15335 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15336 "Verification needed for IntentFilter:" + filter.toString()); 15337 mIntentFilterVerifier.addOneIntentFilterVerification( 15338 verifierUid, userId, verificationId, filter, packageName); 15339 count++; 15340 } 15341 } 15342 } 15343 } 15344 } 15345 15346 if (count > 0) { 15347 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15348 + " IntentFilter verification" + (count > 1 ? "s" : "") 15349 + " for userId:" + userId); 15350 mIntentFilterVerifier.startVerifications(userId); 15351 } else { 15352 if (DEBUG_DOMAIN_VERIFICATION) { 15353 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15354 } 15355 } 15356 } 15357 15358 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15359 final ComponentName cn = filter.activity.getComponentName(); 15360 final String packageName = cn.getPackageName(); 15361 15362 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15363 packageName); 15364 if (ivi == null) { 15365 return true; 15366 } 15367 int status = ivi.getStatus(); 15368 switch (status) { 15369 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15370 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15371 return true; 15372 15373 default: 15374 // Nothing to do 15375 return false; 15376 } 15377 } 15378 15379 private static boolean isMultiArch(ApplicationInfo info) { 15380 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15381 } 15382 15383 private static boolean isExternal(PackageParser.Package pkg) { 15384 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15385 } 15386 15387 private static boolean isExternal(PackageSetting ps) { 15388 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15389 } 15390 15391 private static boolean isEphemeral(PackageParser.Package pkg) { 15392 return pkg.applicationInfo.isEphemeralApp(); 15393 } 15394 15395 private static boolean isEphemeral(PackageSetting ps) { 15396 return ps.pkg != null && isEphemeral(ps.pkg); 15397 } 15398 15399 private static boolean isSystemApp(PackageParser.Package pkg) { 15400 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15401 } 15402 15403 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15404 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15405 } 15406 15407 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15408 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15409 } 15410 15411 private static boolean isSystemApp(PackageSetting ps) { 15412 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15413 } 15414 15415 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15416 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15417 } 15418 15419 private int packageFlagsToInstallFlags(PackageSetting ps) { 15420 int installFlags = 0; 15421 if (isEphemeral(ps)) { 15422 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15423 } 15424 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15425 // This existing package was an external ASEC install when we have 15426 // the external flag without a UUID 15427 installFlags |= PackageManager.INSTALL_EXTERNAL; 15428 } 15429 if (ps.isForwardLocked()) { 15430 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15431 } 15432 return installFlags; 15433 } 15434 15435 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15436 if (isExternal(pkg)) { 15437 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15438 return StorageManager.UUID_PRIMARY_PHYSICAL; 15439 } else { 15440 return pkg.volumeUuid; 15441 } 15442 } else { 15443 return StorageManager.UUID_PRIVATE_INTERNAL; 15444 } 15445 } 15446 15447 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15448 if (isExternal(pkg)) { 15449 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15450 return mSettings.getExternalVersion(); 15451 } else { 15452 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15453 } 15454 } else { 15455 return mSettings.getInternalVersion(); 15456 } 15457 } 15458 15459 private void deleteTempPackageFiles() { 15460 final FilenameFilter filter = new FilenameFilter() { 15461 public boolean accept(File dir, String name) { 15462 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15463 } 15464 }; 15465 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15466 file.delete(); 15467 } 15468 } 15469 15470 @Override 15471 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15472 int flags) { 15473 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15474 flags); 15475 } 15476 15477 @Override 15478 public void deletePackage(final String packageName, 15479 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15480 mContext.enforceCallingOrSelfPermission( 15481 android.Manifest.permission.DELETE_PACKAGES, null); 15482 Preconditions.checkNotNull(packageName); 15483 Preconditions.checkNotNull(observer); 15484 final int uid = Binder.getCallingUid(); 15485 if (!isOrphaned(packageName) 15486 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 15487 try { 15488 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 15489 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 15490 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 15491 observer.onUserActionRequired(intent); 15492 } catch (RemoteException re) { 15493 } 15494 return; 15495 } 15496 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15497 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15498 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15499 mContext.enforceCallingOrSelfPermission( 15500 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15501 "deletePackage for user " + userId); 15502 } 15503 15504 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15505 try { 15506 observer.onPackageDeleted(packageName, 15507 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15508 } catch (RemoteException re) { 15509 } 15510 return; 15511 } 15512 15513 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15514 try { 15515 observer.onPackageDeleted(packageName, 15516 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15517 } catch (RemoteException re) { 15518 } 15519 return; 15520 } 15521 15522 if (DEBUG_REMOVE) { 15523 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15524 + " deleteAllUsers: " + deleteAllUsers ); 15525 } 15526 // Queue up an async operation since the package deletion may take a little while. 15527 mHandler.post(new Runnable() { 15528 public void run() { 15529 mHandler.removeCallbacks(this); 15530 int returnCode; 15531 if (!deleteAllUsers) { 15532 returnCode = deletePackageX(packageName, userId, deleteFlags); 15533 } else { 15534 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15535 // If nobody is blocking uninstall, proceed with delete for all users 15536 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15537 returnCode = deletePackageX(packageName, userId, deleteFlags); 15538 } else { 15539 // Otherwise uninstall individually for users with blockUninstalls=false 15540 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15541 for (int userId : users) { 15542 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15543 returnCode = deletePackageX(packageName, userId, userFlags); 15544 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15545 Slog.w(TAG, "Package delete failed for user " + userId 15546 + ", returnCode " + returnCode); 15547 } 15548 } 15549 } 15550 // The app has only been marked uninstalled for certain users. 15551 // We still need to report that delete was blocked 15552 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15553 } 15554 } 15555 try { 15556 observer.onPackageDeleted(packageName, returnCode, null); 15557 } catch (RemoteException e) { 15558 Log.i(TAG, "Observer no longer exists."); 15559 } //end catch 15560 } //end run 15561 }); 15562 } 15563 15564 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 15565 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 15566 || callingUid == Process.SYSTEM_UID) { 15567 return true; 15568 } 15569 final int callingUserId = UserHandle.getUserId(callingUid); 15570 // If the caller installed the pkgName, then allow it to silently uninstall. 15571 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 15572 return true; 15573 } 15574 15575 // Allow package verifier to silently uninstall. 15576 if (mRequiredVerifierPackage != null && 15577 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 15578 return true; 15579 } 15580 15581 // Allow package uninstaller to silently uninstall. 15582 if (mRequiredUninstallerPackage != null && 15583 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 15584 return true; 15585 } 15586 15587 // Allow storage manager to silently uninstall. 15588 if (mStorageManagerPackage != null && 15589 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 15590 return true; 15591 } 15592 return false; 15593 } 15594 15595 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15596 int[] result = EMPTY_INT_ARRAY; 15597 for (int userId : userIds) { 15598 if (getBlockUninstallForUser(packageName, userId)) { 15599 result = ArrayUtils.appendInt(result, userId); 15600 } 15601 } 15602 return result; 15603 } 15604 15605 @Override 15606 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15607 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15608 } 15609 15610 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15611 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15612 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15613 try { 15614 if (dpm != null) { 15615 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15616 /* callingUserOnly =*/ false); 15617 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15618 : deviceOwnerComponentName.getPackageName(); 15619 // Does the package contains the device owner? 15620 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15621 // this check is probably not needed, since DO should be registered as a device 15622 // admin on some user too. (Original bug for this: b/17657954) 15623 if (packageName.equals(deviceOwnerPackageName)) { 15624 return true; 15625 } 15626 // Does it contain a device admin for any user? 15627 int[] users; 15628 if (userId == UserHandle.USER_ALL) { 15629 users = sUserManager.getUserIds(); 15630 } else { 15631 users = new int[]{userId}; 15632 } 15633 for (int i = 0; i < users.length; ++i) { 15634 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15635 return true; 15636 } 15637 } 15638 } 15639 } catch (RemoteException e) { 15640 } 15641 return false; 15642 } 15643 15644 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15645 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15646 } 15647 15648 /** 15649 * This method is an internal method that could be get invoked either 15650 * to delete an installed package or to clean up a failed installation. 15651 * After deleting an installed package, a broadcast is sent to notify any 15652 * listeners that the package has been removed. For cleaning up a failed 15653 * installation, the broadcast is not necessary since the package's 15654 * installation wouldn't have sent the initial broadcast either 15655 * The key steps in deleting a package are 15656 * deleting the package information in internal structures like mPackages, 15657 * deleting the packages base directories through installd 15658 * updating mSettings to reflect current status 15659 * persisting settings for later use 15660 * sending a broadcast if necessary 15661 */ 15662 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15663 final PackageRemovedInfo info = new PackageRemovedInfo(); 15664 final boolean res; 15665 15666 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15667 ? UserHandle.USER_ALL : userId; 15668 15669 if (isPackageDeviceAdmin(packageName, removeUser)) { 15670 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15671 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15672 } 15673 15674 PackageSetting uninstalledPs = null; 15675 15676 // for the uninstall-updates case and restricted profiles, remember the per- 15677 // user handle installed state 15678 int[] allUsers; 15679 synchronized (mPackages) { 15680 uninstalledPs = mSettings.mPackages.get(packageName); 15681 if (uninstalledPs == null) { 15682 Slog.w(TAG, "Not removing non-existent package " + packageName); 15683 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15684 } 15685 allUsers = sUserManager.getUserIds(); 15686 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15687 } 15688 15689 final int freezeUser; 15690 if (isUpdatedSystemApp(uninstalledPs) 15691 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15692 // We're downgrading a system app, which will apply to all users, so 15693 // freeze them all during the downgrade 15694 freezeUser = UserHandle.USER_ALL; 15695 } else { 15696 freezeUser = removeUser; 15697 } 15698 15699 synchronized (mInstallLock) { 15700 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15701 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15702 deleteFlags, "deletePackageX")) { 15703 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15704 deleteFlags | REMOVE_CHATTY, info, true, null); 15705 } 15706 synchronized (mPackages) { 15707 if (res) { 15708 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15709 } 15710 } 15711 } 15712 15713 if (res) { 15714 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15715 info.sendPackageRemovedBroadcasts(killApp); 15716 info.sendSystemPackageUpdatedBroadcasts(); 15717 info.sendSystemPackageAppearedBroadcasts(); 15718 } 15719 // Force a gc here. 15720 Runtime.getRuntime().gc(); 15721 // Delete the resources here after sending the broadcast to let 15722 // other processes clean up before deleting resources. 15723 if (info.args != null) { 15724 synchronized (mInstallLock) { 15725 info.args.doPostDeleteLI(true); 15726 } 15727 } 15728 15729 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15730 } 15731 15732 class PackageRemovedInfo { 15733 String removedPackage; 15734 int uid = -1; 15735 int removedAppId = -1; 15736 int[] origUsers; 15737 int[] removedUsers = null; 15738 boolean isRemovedPackageSystemUpdate = false; 15739 boolean isUpdate; 15740 boolean dataRemoved; 15741 boolean removedForAllUsers; 15742 // Clean up resources deleted packages. 15743 InstallArgs args = null; 15744 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15745 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15746 15747 void sendPackageRemovedBroadcasts(boolean killApp) { 15748 sendPackageRemovedBroadcastInternal(killApp); 15749 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15750 for (int i = 0; i < childCount; i++) { 15751 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15752 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15753 } 15754 } 15755 15756 void sendSystemPackageUpdatedBroadcasts() { 15757 if (isRemovedPackageSystemUpdate) { 15758 sendSystemPackageUpdatedBroadcastsInternal(); 15759 final int childCount = (removedChildPackages != null) 15760 ? removedChildPackages.size() : 0; 15761 for (int i = 0; i < childCount; i++) { 15762 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15763 if (childInfo.isRemovedPackageSystemUpdate) { 15764 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15765 } 15766 } 15767 } 15768 } 15769 15770 void sendSystemPackageAppearedBroadcasts() { 15771 final int packageCount = (appearedChildPackages != null) 15772 ? appearedChildPackages.size() : 0; 15773 for (int i = 0; i < packageCount; i++) { 15774 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15775 for (int userId : installedInfo.newUsers) { 15776 sendPackageAddedForUser(installedInfo.name, true, 15777 UserHandle.getAppId(installedInfo.uid), userId); 15778 } 15779 } 15780 } 15781 15782 private void sendSystemPackageUpdatedBroadcastsInternal() { 15783 Bundle extras = new Bundle(2); 15784 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15785 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15786 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15787 extras, 0, null, null, null); 15788 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15789 extras, 0, null, null, null); 15790 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15791 null, 0, removedPackage, null, null); 15792 } 15793 15794 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15795 Bundle extras = new Bundle(2); 15796 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15797 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15798 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15799 if (isUpdate || isRemovedPackageSystemUpdate) { 15800 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15801 } 15802 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15803 if (removedPackage != null) { 15804 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15805 extras, 0, null, null, removedUsers); 15806 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15807 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15808 removedPackage, extras, 0, null, null, removedUsers); 15809 } 15810 } 15811 if (removedAppId >= 0) { 15812 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15813 removedUsers); 15814 } 15815 } 15816 } 15817 15818 /* 15819 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15820 * flag is not set, the data directory is removed as well. 15821 * make sure this flag is set for partially installed apps. If not its meaningless to 15822 * delete a partially installed application. 15823 */ 15824 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15825 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15826 String packageName = ps.name; 15827 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15828 // Retrieve object to delete permissions for shared user later on 15829 final PackageParser.Package deletedPkg; 15830 final PackageSetting deletedPs; 15831 // reader 15832 synchronized (mPackages) { 15833 deletedPkg = mPackages.get(packageName); 15834 deletedPs = mSettings.mPackages.get(packageName); 15835 if (outInfo != null) { 15836 outInfo.removedPackage = packageName; 15837 outInfo.removedUsers = deletedPs != null 15838 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15839 : null; 15840 } 15841 } 15842 15843 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15844 15845 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15846 final PackageParser.Package resolvedPkg; 15847 if (deletedPkg != null) { 15848 resolvedPkg = deletedPkg; 15849 } else { 15850 // We don't have a parsed package when it lives on an ejected 15851 // adopted storage device, so fake something together 15852 resolvedPkg = new PackageParser.Package(ps.name); 15853 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15854 } 15855 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15856 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15857 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15858 if (outInfo != null) { 15859 outInfo.dataRemoved = true; 15860 } 15861 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15862 } 15863 15864 // writer 15865 synchronized (mPackages) { 15866 if (deletedPs != null) { 15867 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15868 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15869 clearDefaultBrowserIfNeeded(packageName); 15870 if (outInfo != null) { 15871 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15872 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15873 } 15874 updatePermissionsLPw(deletedPs.name, null, 0); 15875 if (deletedPs.sharedUser != null) { 15876 // Remove permissions associated with package. Since runtime 15877 // permissions are per user we have to kill the removed package 15878 // or packages running under the shared user of the removed 15879 // package if revoking the permissions requested only by the removed 15880 // package is successful and this causes a change in gids. 15881 for (int userId : UserManagerService.getInstance().getUserIds()) { 15882 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15883 userId); 15884 if (userIdToKill == UserHandle.USER_ALL 15885 || userIdToKill >= UserHandle.USER_SYSTEM) { 15886 // If gids changed for this user, kill all affected packages. 15887 mHandler.post(new Runnable() { 15888 @Override 15889 public void run() { 15890 // This has to happen with no lock held. 15891 killApplication(deletedPs.name, deletedPs.appId, 15892 KILL_APP_REASON_GIDS_CHANGED); 15893 } 15894 }); 15895 break; 15896 } 15897 } 15898 } 15899 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15900 } 15901 // make sure to preserve per-user disabled state if this removal was just 15902 // a downgrade of a system app to the factory package 15903 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15904 if (DEBUG_REMOVE) { 15905 Slog.d(TAG, "Propagating install state across downgrade"); 15906 } 15907 for (int userId : allUserHandles) { 15908 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15909 if (DEBUG_REMOVE) { 15910 Slog.d(TAG, " user " + userId + " => " + installed); 15911 } 15912 ps.setInstalled(installed, userId); 15913 } 15914 } 15915 } 15916 // can downgrade to reader 15917 if (writeSettings) { 15918 // Save settings now 15919 mSettings.writeLPr(); 15920 } 15921 } 15922 if (outInfo != null) { 15923 // A user ID was deleted here. Go through all users and remove it 15924 // from KeyStore. 15925 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15926 } 15927 } 15928 15929 static boolean locationIsPrivileged(File path) { 15930 try { 15931 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15932 .getCanonicalPath(); 15933 return path.getCanonicalPath().startsWith(privilegedAppDir); 15934 } catch (IOException e) { 15935 Slog.e(TAG, "Unable to access code path " + path); 15936 } 15937 return false; 15938 } 15939 15940 /* 15941 * Tries to delete system package. 15942 */ 15943 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15944 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15945 boolean writeSettings) { 15946 if (deletedPs.parentPackageName != null) { 15947 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15948 return false; 15949 } 15950 15951 final boolean applyUserRestrictions 15952 = (allUserHandles != null) && (outInfo.origUsers != null); 15953 final PackageSetting disabledPs; 15954 // Confirm if the system package has been updated 15955 // An updated system app can be deleted. This will also have to restore 15956 // the system pkg from system partition 15957 // reader 15958 synchronized (mPackages) { 15959 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15960 } 15961 15962 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15963 + " disabledPs=" + disabledPs); 15964 15965 if (disabledPs == null) { 15966 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15967 return false; 15968 } else if (DEBUG_REMOVE) { 15969 Slog.d(TAG, "Deleting system pkg from data partition"); 15970 } 15971 15972 if (DEBUG_REMOVE) { 15973 if (applyUserRestrictions) { 15974 Slog.d(TAG, "Remembering install states:"); 15975 for (int userId : allUserHandles) { 15976 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15977 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15978 } 15979 } 15980 } 15981 15982 // Delete the updated package 15983 outInfo.isRemovedPackageSystemUpdate = true; 15984 if (outInfo.removedChildPackages != null) { 15985 final int childCount = (deletedPs.childPackageNames != null) 15986 ? deletedPs.childPackageNames.size() : 0; 15987 for (int i = 0; i < childCount; i++) { 15988 String childPackageName = deletedPs.childPackageNames.get(i); 15989 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15990 .contains(childPackageName)) { 15991 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15992 childPackageName); 15993 if (childInfo != null) { 15994 childInfo.isRemovedPackageSystemUpdate = true; 15995 } 15996 } 15997 } 15998 } 15999 16000 if (disabledPs.versionCode < deletedPs.versionCode) { 16001 // Delete data for downgrades 16002 flags &= ~PackageManager.DELETE_KEEP_DATA; 16003 } else { 16004 // Preserve data by setting flag 16005 flags |= PackageManager.DELETE_KEEP_DATA; 16006 } 16007 16008 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16009 outInfo, writeSettings, disabledPs.pkg); 16010 if (!ret) { 16011 return false; 16012 } 16013 16014 // writer 16015 synchronized (mPackages) { 16016 // Reinstate the old system package 16017 enableSystemPackageLPw(disabledPs.pkg); 16018 // Remove any native libraries from the upgraded package. 16019 removeNativeBinariesLI(deletedPs); 16020 } 16021 16022 // Install the system package 16023 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16024 int parseFlags = mDefParseFlags 16025 | PackageParser.PARSE_MUST_BE_APK 16026 | PackageParser.PARSE_IS_SYSTEM 16027 | PackageParser.PARSE_IS_SYSTEM_DIR; 16028 if (locationIsPrivileged(disabledPs.codePath)) { 16029 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16030 } 16031 16032 final PackageParser.Package newPkg; 16033 try { 16034 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 16035 } catch (PackageManagerException e) { 16036 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16037 + e.getMessage()); 16038 return false; 16039 } 16040 try { 16041 // update shared libraries for the newly re-installed system package 16042 updateSharedLibrariesLPw(newPkg, null); 16043 } catch (PackageManagerException e) { 16044 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16045 } 16046 16047 prepareAppDataAfterInstallLIF(newPkg); 16048 16049 // writer 16050 synchronized (mPackages) { 16051 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16052 16053 // Propagate the permissions state as we do not want to drop on the floor 16054 // runtime permissions. The update permissions method below will take 16055 // care of removing obsolete permissions and grant install permissions. 16056 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16057 updatePermissionsLPw(newPkg.packageName, newPkg, 16058 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16059 16060 if (applyUserRestrictions) { 16061 if (DEBUG_REMOVE) { 16062 Slog.d(TAG, "Propagating install state across reinstall"); 16063 } 16064 for (int userId : allUserHandles) { 16065 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16066 if (DEBUG_REMOVE) { 16067 Slog.d(TAG, " user " + userId + " => " + installed); 16068 } 16069 ps.setInstalled(installed, userId); 16070 16071 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16072 } 16073 // Regardless of writeSettings we need to ensure that this restriction 16074 // state propagation is persisted 16075 mSettings.writeAllUsersPackageRestrictionsLPr(); 16076 } 16077 // can downgrade to reader here 16078 if (writeSettings) { 16079 mSettings.writeLPr(); 16080 } 16081 } 16082 return true; 16083 } 16084 16085 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16086 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16087 PackageRemovedInfo outInfo, boolean writeSettings, 16088 PackageParser.Package replacingPackage) { 16089 synchronized (mPackages) { 16090 if (outInfo != null) { 16091 outInfo.uid = ps.appId; 16092 } 16093 16094 if (outInfo != null && outInfo.removedChildPackages != null) { 16095 final int childCount = (ps.childPackageNames != null) 16096 ? ps.childPackageNames.size() : 0; 16097 for (int i = 0; i < childCount; i++) { 16098 String childPackageName = ps.childPackageNames.get(i); 16099 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16100 if (childPs == null) { 16101 return false; 16102 } 16103 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16104 childPackageName); 16105 if (childInfo != null) { 16106 childInfo.uid = childPs.appId; 16107 } 16108 } 16109 } 16110 } 16111 16112 // Delete package data from internal structures and also remove data if flag is set 16113 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16114 16115 // Delete the child packages data 16116 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16117 for (int i = 0; i < childCount; i++) { 16118 PackageSetting childPs; 16119 synchronized (mPackages) { 16120 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16121 } 16122 if (childPs != null) { 16123 PackageRemovedInfo childOutInfo = (outInfo != null 16124 && outInfo.removedChildPackages != null) 16125 ? outInfo.removedChildPackages.get(childPs.name) : null; 16126 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16127 && (replacingPackage != null 16128 && !replacingPackage.hasChildPackage(childPs.name)) 16129 ? flags & ~DELETE_KEEP_DATA : flags; 16130 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16131 deleteFlags, writeSettings); 16132 } 16133 } 16134 16135 // Delete application code and resources only for parent packages 16136 if (ps.parentPackageName == null) { 16137 if (deleteCodeAndResources && (outInfo != null)) { 16138 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16139 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16140 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16141 } 16142 } 16143 16144 return true; 16145 } 16146 16147 @Override 16148 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16149 int userId) { 16150 mContext.enforceCallingOrSelfPermission( 16151 android.Manifest.permission.DELETE_PACKAGES, null); 16152 synchronized (mPackages) { 16153 PackageSetting ps = mSettings.mPackages.get(packageName); 16154 if (ps == null) { 16155 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16156 return false; 16157 } 16158 if (!ps.getInstalled(userId)) { 16159 // Can't block uninstall for an app that is not installed or enabled. 16160 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16161 return false; 16162 } 16163 ps.setBlockUninstall(blockUninstall, userId); 16164 mSettings.writePackageRestrictionsLPr(userId); 16165 } 16166 return true; 16167 } 16168 16169 @Override 16170 public boolean getBlockUninstallForUser(String packageName, int userId) { 16171 synchronized (mPackages) { 16172 PackageSetting ps = mSettings.mPackages.get(packageName); 16173 if (ps == null) { 16174 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16175 return false; 16176 } 16177 return ps.getBlockUninstall(userId); 16178 } 16179 } 16180 16181 @Override 16182 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16183 int callingUid = Binder.getCallingUid(); 16184 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16185 throw new SecurityException( 16186 "setRequiredForSystemUser can only be run by the system or root"); 16187 } 16188 synchronized (mPackages) { 16189 PackageSetting ps = mSettings.mPackages.get(packageName); 16190 if (ps == null) { 16191 Log.w(TAG, "Package doesn't exist: " + packageName); 16192 return false; 16193 } 16194 if (systemUserApp) { 16195 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16196 } else { 16197 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16198 } 16199 mSettings.writeLPr(); 16200 } 16201 return true; 16202 } 16203 16204 /* 16205 * This method handles package deletion in general 16206 */ 16207 private boolean deletePackageLIF(String packageName, UserHandle user, 16208 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16209 PackageRemovedInfo outInfo, boolean writeSettings, 16210 PackageParser.Package replacingPackage) { 16211 if (packageName == null) { 16212 Slog.w(TAG, "Attempt to delete null packageName."); 16213 return false; 16214 } 16215 16216 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16217 16218 PackageSetting ps; 16219 16220 synchronized (mPackages) { 16221 ps = mSettings.mPackages.get(packageName); 16222 if (ps == null) { 16223 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16224 return false; 16225 } 16226 16227 if (ps.parentPackageName != null && (!isSystemApp(ps) 16228 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16229 if (DEBUG_REMOVE) { 16230 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16231 + ((user == null) ? UserHandle.USER_ALL : user)); 16232 } 16233 final int removedUserId = (user != null) ? user.getIdentifier() 16234 : UserHandle.USER_ALL; 16235 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16236 return false; 16237 } 16238 markPackageUninstalledForUserLPw(ps, user); 16239 scheduleWritePackageRestrictionsLocked(user); 16240 return true; 16241 } 16242 } 16243 16244 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16245 && user.getIdentifier() != UserHandle.USER_ALL)) { 16246 // The caller is asking that the package only be deleted for a single 16247 // user. To do this, we just mark its uninstalled state and delete 16248 // its data. If this is a system app, we only allow this to happen if 16249 // they have set the special DELETE_SYSTEM_APP which requests different 16250 // semantics than normal for uninstalling system apps. 16251 markPackageUninstalledForUserLPw(ps, user); 16252 16253 if (!isSystemApp(ps)) { 16254 // Do not uninstall the APK if an app should be cached 16255 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16256 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16257 // Other user still have this package installed, so all 16258 // we need to do is clear this user's data and save that 16259 // it is uninstalled. 16260 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16261 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16262 return false; 16263 } 16264 scheduleWritePackageRestrictionsLocked(user); 16265 return true; 16266 } else { 16267 // We need to set it back to 'installed' so the uninstall 16268 // broadcasts will be sent correctly. 16269 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16270 ps.setInstalled(true, user.getIdentifier()); 16271 } 16272 } else { 16273 // This is a system app, so we assume that the 16274 // other users still have this package installed, so all 16275 // we need to do is clear this user's data and save that 16276 // it is uninstalled. 16277 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16278 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16279 return false; 16280 } 16281 scheduleWritePackageRestrictionsLocked(user); 16282 return true; 16283 } 16284 } 16285 16286 // If we are deleting a composite package for all users, keep track 16287 // of result for each child. 16288 if (ps.childPackageNames != null && outInfo != null) { 16289 synchronized (mPackages) { 16290 final int childCount = ps.childPackageNames.size(); 16291 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16292 for (int i = 0; i < childCount; i++) { 16293 String childPackageName = ps.childPackageNames.get(i); 16294 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16295 childInfo.removedPackage = childPackageName; 16296 outInfo.removedChildPackages.put(childPackageName, childInfo); 16297 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16298 if (childPs != null) { 16299 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16300 } 16301 } 16302 } 16303 } 16304 16305 boolean ret = false; 16306 if (isSystemApp(ps)) { 16307 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16308 // When an updated system application is deleted we delete the existing resources 16309 // as well and fall back to existing code in system partition 16310 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16311 } else { 16312 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16313 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16314 outInfo, writeSettings, replacingPackage); 16315 } 16316 16317 // Take a note whether we deleted the package for all users 16318 if (outInfo != null) { 16319 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16320 if (outInfo.removedChildPackages != null) { 16321 synchronized (mPackages) { 16322 final int childCount = outInfo.removedChildPackages.size(); 16323 for (int i = 0; i < childCount; i++) { 16324 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16325 if (childInfo != null) { 16326 childInfo.removedForAllUsers = mPackages.get( 16327 childInfo.removedPackage) == null; 16328 } 16329 } 16330 } 16331 } 16332 // If we uninstalled an update to a system app there may be some 16333 // child packages that appeared as they are declared in the system 16334 // app but were not declared in the update. 16335 if (isSystemApp(ps)) { 16336 synchronized (mPackages) { 16337 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16338 final int childCount = (updatedPs.childPackageNames != null) 16339 ? updatedPs.childPackageNames.size() : 0; 16340 for (int i = 0; i < childCount; i++) { 16341 String childPackageName = updatedPs.childPackageNames.get(i); 16342 if (outInfo.removedChildPackages == null 16343 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16344 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16345 if (childPs == null) { 16346 continue; 16347 } 16348 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16349 installRes.name = childPackageName; 16350 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16351 installRes.pkg = mPackages.get(childPackageName); 16352 installRes.uid = childPs.pkg.applicationInfo.uid; 16353 if (outInfo.appearedChildPackages == null) { 16354 outInfo.appearedChildPackages = new ArrayMap<>(); 16355 } 16356 outInfo.appearedChildPackages.put(childPackageName, installRes); 16357 } 16358 } 16359 } 16360 } 16361 } 16362 16363 return ret; 16364 } 16365 16366 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16367 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16368 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16369 for (int nextUserId : userIds) { 16370 if (DEBUG_REMOVE) { 16371 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16372 } 16373 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16374 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16375 false /*hidden*/, false /*suspended*/, null, null, null, 16376 false /*blockUninstall*/, 16377 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16378 } 16379 } 16380 16381 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16382 PackageRemovedInfo outInfo) { 16383 final PackageParser.Package pkg; 16384 synchronized (mPackages) { 16385 pkg = mPackages.get(ps.name); 16386 } 16387 16388 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16389 : new int[] {userId}; 16390 for (int nextUserId : userIds) { 16391 if (DEBUG_REMOVE) { 16392 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16393 + nextUserId); 16394 } 16395 16396 destroyAppDataLIF(pkg, userId, 16397 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16398 destroyAppProfilesLIF(pkg, userId); 16399 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16400 schedulePackageCleaning(ps.name, nextUserId, false); 16401 synchronized (mPackages) { 16402 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16403 scheduleWritePackageRestrictionsLocked(nextUserId); 16404 } 16405 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16406 } 16407 } 16408 16409 if (outInfo != null) { 16410 outInfo.removedPackage = ps.name; 16411 outInfo.removedAppId = ps.appId; 16412 outInfo.removedUsers = userIds; 16413 } 16414 16415 return true; 16416 } 16417 16418 private final class ClearStorageConnection implements ServiceConnection { 16419 IMediaContainerService mContainerService; 16420 16421 @Override 16422 public void onServiceConnected(ComponentName name, IBinder service) { 16423 synchronized (this) { 16424 mContainerService = IMediaContainerService.Stub.asInterface(service); 16425 notifyAll(); 16426 } 16427 } 16428 16429 @Override 16430 public void onServiceDisconnected(ComponentName name) { 16431 } 16432 } 16433 16434 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16435 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16436 16437 final boolean mounted; 16438 if (Environment.isExternalStorageEmulated()) { 16439 mounted = true; 16440 } else { 16441 final String status = Environment.getExternalStorageState(); 16442 16443 mounted = status.equals(Environment.MEDIA_MOUNTED) 16444 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16445 } 16446 16447 if (!mounted) { 16448 return; 16449 } 16450 16451 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16452 int[] users; 16453 if (userId == UserHandle.USER_ALL) { 16454 users = sUserManager.getUserIds(); 16455 } else { 16456 users = new int[] { userId }; 16457 } 16458 final ClearStorageConnection conn = new ClearStorageConnection(); 16459 if (mContext.bindServiceAsUser( 16460 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16461 try { 16462 for (int curUser : users) { 16463 long timeout = SystemClock.uptimeMillis() + 5000; 16464 synchronized (conn) { 16465 long now; 16466 while (conn.mContainerService == null && 16467 (now = SystemClock.uptimeMillis()) < timeout) { 16468 try { 16469 conn.wait(timeout - now); 16470 } catch (InterruptedException e) { 16471 } 16472 } 16473 } 16474 if (conn.mContainerService == null) { 16475 return; 16476 } 16477 16478 final UserEnvironment userEnv = new UserEnvironment(curUser); 16479 clearDirectory(conn.mContainerService, 16480 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16481 if (allData) { 16482 clearDirectory(conn.mContainerService, 16483 userEnv.buildExternalStorageAppDataDirs(packageName)); 16484 clearDirectory(conn.mContainerService, 16485 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16486 } 16487 } 16488 } finally { 16489 mContext.unbindService(conn); 16490 } 16491 } 16492 } 16493 16494 @Override 16495 public void clearApplicationProfileData(String packageName) { 16496 enforceSystemOrRoot("Only the system can clear all profile data"); 16497 16498 final PackageParser.Package pkg; 16499 synchronized (mPackages) { 16500 pkg = mPackages.get(packageName); 16501 } 16502 16503 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16504 synchronized (mInstallLock) { 16505 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16506 } 16507 } 16508 } 16509 16510 @Override 16511 public void clearApplicationUserData(final String packageName, 16512 final IPackageDataObserver observer, final int userId) { 16513 mContext.enforceCallingOrSelfPermission( 16514 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16515 16516 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16517 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16518 16519 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16520 throw new SecurityException("Cannot clear data for a protected package: " 16521 + packageName); 16522 } 16523 // Queue up an async operation since the package deletion may take a little while. 16524 mHandler.post(new Runnable() { 16525 public void run() { 16526 mHandler.removeCallbacks(this); 16527 final boolean succeeded; 16528 try (PackageFreezer freezer = freezePackage(packageName, 16529 "clearApplicationUserData")) { 16530 synchronized (mInstallLock) { 16531 succeeded = clearApplicationUserDataLIF(packageName, userId); 16532 } 16533 clearExternalStorageDataSync(packageName, userId, true); 16534 } 16535 if (succeeded) { 16536 // invoke DeviceStorageMonitor's update method to clear any notifications 16537 DeviceStorageMonitorInternal dsm = LocalServices 16538 .getService(DeviceStorageMonitorInternal.class); 16539 if (dsm != null) { 16540 dsm.checkMemory(); 16541 } 16542 } 16543 if(observer != null) { 16544 try { 16545 observer.onRemoveCompleted(packageName, succeeded); 16546 } catch (RemoteException e) { 16547 Log.i(TAG, "Observer no longer exists."); 16548 } 16549 } //end if observer 16550 } //end run 16551 }); 16552 } 16553 16554 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16555 if (packageName == null) { 16556 Slog.w(TAG, "Attempt to delete null packageName."); 16557 return false; 16558 } 16559 16560 // Try finding details about the requested package 16561 PackageParser.Package pkg; 16562 synchronized (mPackages) { 16563 pkg = mPackages.get(packageName); 16564 if (pkg == null) { 16565 final PackageSetting ps = mSettings.mPackages.get(packageName); 16566 if (ps != null) { 16567 pkg = ps.pkg; 16568 } 16569 } 16570 16571 if (pkg == null) { 16572 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16573 return false; 16574 } 16575 16576 PackageSetting ps = (PackageSetting) pkg.mExtras; 16577 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16578 } 16579 16580 clearAppDataLIF(pkg, userId, 16581 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16582 16583 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16584 removeKeystoreDataIfNeeded(userId, appId); 16585 16586 UserManagerInternal umInternal = getUserManagerInternal(); 16587 final int flags; 16588 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16589 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16590 } else if (umInternal.isUserRunning(userId)) { 16591 flags = StorageManager.FLAG_STORAGE_DE; 16592 } else { 16593 flags = 0; 16594 } 16595 prepareAppDataContentsLIF(pkg, userId, flags); 16596 16597 return true; 16598 } 16599 16600 /** 16601 * Reverts user permission state changes (permissions and flags) in 16602 * all packages for a given user. 16603 * 16604 * @param userId The device user for which to do a reset. 16605 */ 16606 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16607 final int packageCount = mPackages.size(); 16608 for (int i = 0; i < packageCount; i++) { 16609 PackageParser.Package pkg = mPackages.valueAt(i); 16610 PackageSetting ps = (PackageSetting) pkg.mExtras; 16611 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16612 } 16613 } 16614 16615 private void resetNetworkPolicies(int userId) { 16616 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16617 } 16618 16619 /** 16620 * Reverts user permission state changes (permissions and flags). 16621 * 16622 * @param ps The package for which to reset. 16623 * @param userId The device user for which to do a reset. 16624 */ 16625 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16626 final PackageSetting ps, final int userId) { 16627 if (ps.pkg == null) { 16628 return; 16629 } 16630 16631 // These are flags that can change base on user actions. 16632 final int userSettableMask = FLAG_PERMISSION_USER_SET 16633 | FLAG_PERMISSION_USER_FIXED 16634 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16635 | FLAG_PERMISSION_REVIEW_REQUIRED; 16636 16637 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16638 | FLAG_PERMISSION_POLICY_FIXED; 16639 16640 boolean writeInstallPermissions = false; 16641 boolean writeRuntimePermissions = false; 16642 16643 final int permissionCount = ps.pkg.requestedPermissions.size(); 16644 for (int i = 0; i < permissionCount; i++) { 16645 String permission = ps.pkg.requestedPermissions.get(i); 16646 16647 BasePermission bp = mSettings.mPermissions.get(permission); 16648 if (bp == null) { 16649 continue; 16650 } 16651 16652 // If shared user we just reset the state to which only this app contributed. 16653 if (ps.sharedUser != null) { 16654 boolean used = false; 16655 final int packageCount = ps.sharedUser.packages.size(); 16656 for (int j = 0; j < packageCount; j++) { 16657 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16658 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16659 && pkg.pkg.requestedPermissions.contains(permission)) { 16660 used = true; 16661 break; 16662 } 16663 } 16664 if (used) { 16665 continue; 16666 } 16667 } 16668 16669 PermissionsState permissionsState = ps.getPermissionsState(); 16670 16671 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16672 16673 // Always clear the user settable flags. 16674 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16675 bp.name) != null; 16676 // If permission review is enabled and this is a legacy app, mark the 16677 // permission as requiring a review as this is the initial state. 16678 int flags = 0; 16679 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) 16680 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16681 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16682 } 16683 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16684 if (hasInstallState) { 16685 writeInstallPermissions = true; 16686 } else { 16687 writeRuntimePermissions = true; 16688 } 16689 } 16690 16691 // Below is only runtime permission handling. 16692 if (!bp.isRuntime()) { 16693 continue; 16694 } 16695 16696 // Never clobber system or policy. 16697 if ((oldFlags & policyOrSystemFlags) != 0) { 16698 continue; 16699 } 16700 16701 // If this permission was granted by default, make sure it is. 16702 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16703 if (permissionsState.grantRuntimePermission(bp, userId) 16704 != PERMISSION_OPERATION_FAILURE) { 16705 writeRuntimePermissions = true; 16706 } 16707 // If permission review is enabled the permissions for a legacy apps 16708 // are represented as constantly granted runtime ones, so don't revoke. 16709 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16710 // Otherwise, reset the permission. 16711 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16712 switch (revokeResult) { 16713 case PERMISSION_OPERATION_SUCCESS: 16714 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16715 writeRuntimePermissions = true; 16716 final int appId = ps.appId; 16717 mHandler.post(new Runnable() { 16718 @Override 16719 public void run() { 16720 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16721 } 16722 }); 16723 } break; 16724 } 16725 } 16726 } 16727 16728 // Synchronously write as we are taking permissions away. 16729 if (writeRuntimePermissions) { 16730 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16731 } 16732 16733 // Synchronously write as we are taking permissions away. 16734 if (writeInstallPermissions) { 16735 mSettings.writeLPr(); 16736 } 16737 } 16738 16739 /** 16740 * Remove entries from the keystore daemon. Will only remove it if the 16741 * {@code appId} is valid. 16742 */ 16743 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16744 if (appId < 0) { 16745 return; 16746 } 16747 16748 final KeyStore keyStore = KeyStore.getInstance(); 16749 if (keyStore != null) { 16750 if (userId == UserHandle.USER_ALL) { 16751 for (final int individual : sUserManager.getUserIds()) { 16752 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16753 } 16754 } else { 16755 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16756 } 16757 } else { 16758 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16759 } 16760 } 16761 16762 @Override 16763 public void deleteApplicationCacheFiles(final String packageName, 16764 final IPackageDataObserver observer) { 16765 final int userId = UserHandle.getCallingUserId(); 16766 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16767 } 16768 16769 @Override 16770 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16771 final IPackageDataObserver observer) { 16772 mContext.enforceCallingOrSelfPermission( 16773 android.Manifest.permission.DELETE_CACHE_FILES, null); 16774 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16775 /* requireFullPermission= */ true, /* checkShell= */ false, 16776 "delete application cache files"); 16777 16778 final PackageParser.Package pkg; 16779 synchronized (mPackages) { 16780 pkg = mPackages.get(packageName); 16781 } 16782 16783 // Queue up an async operation since the package deletion may take a little while. 16784 mHandler.post(new Runnable() { 16785 public void run() { 16786 synchronized (mInstallLock) { 16787 final int flags = StorageManager.FLAG_STORAGE_DE 16788 | StorageManager.FLAG_STORAGE_CE; 16789 // We're only clearing cache files, so we don't care if the 16790 // app is unfrozen and still able to run 16791 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16792 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16793 } 16794 clearExternalStorageDataSync(packageName, userId, false); 16795 if (observer != null) { 16796 try { 16797 observer.onRemoveCompleted(packageName, true); 16798 } catch (RemoteException e) { 16799 Log.i(TAG, "Observer no longer exists."); 16800 } 16801 } 16802 } 16803 }); 16804 } 16805 16806 @Override 16807 public void getPackageSizeInfo(final String packageName, int userHandle, 16808 final IPackageStatsObserver observer) { 16809 mContext.enforceCallingOrSelfPermission( 16810 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16811 if (packageName == null) { 16812 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16813 } 16814 16815 PackageStats stats = new PackageStats(packageName, userHandle); 16816 16817 /* 16818 * Queue up an async operation since the package measurement may take a 16819 * little while. 16820 */ 16821 Message msg = mHandler.obtainMessage(INIT_COPY); 16822 msg.obj = new MeasureParams(stats, observer); 16823 mHandler.sendMessage(msg); 16824 } 16825 16826 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16827 final PackageSetting ps; 16828 synchronized (mPackages) { 16829 ps = mSettings.mPackages.get(packageName); 16830 if (ps == null) { 16831 Slog.w(TAG, "Failed to find settings for " + packageName); 16832 return false; 16833 } 16834 } 16835 16836 final String[] packageNames = { packageName }; 16837 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 16838 final String[] codePaths = { ps.codePathString }; 16839 16840 try { 16841 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 16842 ps.appId, ceDataInodes, codePaths, stats); 16843 16844 // For now, ignore code size of packages on system partition 16845 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16846 stats.codeSize = 0; 16847 } 16848 16849 // External clients expect these to be tracked separately 16850 stats.dataSize -= stats.cacheSize; 16851 16852 } catch (InstallerException e) { 16853 Slog.w(TAG, String.valueOf(e)); 16854 return false; 16855 } 16856 16857 return true; 16858 } 16859 16860 private int getUidTargetSdkVersionLockedLPr(int uid) { 16861 Object obj = mSettings.getUserIdLPr(uid); 16862 if (obj instanceof SharedUserSetting) { 16863 final SharedUserSetting sus = (SharedUserSetting) obj; 16864 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16865 final Iterator<PackageSetting> it = sus.packages.iterator(); 16866 while (it.hasNext()) { 16867 final PackageSetting ps = it.next(); 16868 if (ps.pkg != null) { 16869 int v = ps.pkg.applicationInfo.targetSdkVersion; 16870 if (v < vers) vers = v; 16871 } 16872 } 16873 return vers; 16874 } else if (obj instanceof PackageSetting) { 16875 final PackageSetting ps = (PackageSetting) obj; 16876 if (ps.pkg != null) { 16877 return ps.pkg.applicationInfo.targetSdkVersion; 16878 } 16879 } 16880 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16881 } 16882 16883 @Override 16884 public void addPreferredActivity(IntentFilter filter, int match, 16885 ComponentName[] set, ComponentName activity, int userId) { 16886 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16887 "Adding preferred"); 16888 } 16889 16890 private void addPreferredActivityInternal(IntentFilter filter, int match, 16891 ComponentName[] set, ComponentName activity, boolean always, int userId, 16892 String opname) { 16893 // writer 16894 int callingUid = Binder.getCallingUid(); 16895 enforceCrossUserPermission(callingUid, userId, 16896 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16897 if (filter.countActions() == 0) { 16898 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16899 return; 16900 } 16901 synchronized (mPackages) { 16902 if (mContext.checkCallingOrSelfPermission( 16903 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16904 != PackageManager.PERMISSION_GRANTED) { 16905 if (getUidTargetSdkVersionLockedLPr(callingUid) 16906 < Build.VERSION_CODES.FROYO) { 16907 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16908 + callingUid); 16909 return; 16910 } 16911 mContext.enforceCallingOrSelfPermission( 16912 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16913 } 16914 16915 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16916 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16917 + userId + ":"); 16918 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16919 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16920 scheduleWritePackageRestrictionsLocked(userId); 16921 postPreferredActivityChangedBroadcast(userId); 16922 } 16923 } 16924 16925 private void postPreferredActivityChangedBroadcast(int userId) { 16926 mHandler.post(() -> { 16927 final IActivityManager am = ActivityManagerNative.getDefault(); 16928 if (am == null) { 16929 return; 16930 } 16931 16932 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 16933 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 16934 try { 16935 am.broadcastIntent(null, intent, null, null, 16936 0, null, null, null, android.app.AppOpsManager.OP_NONE, 16937 null, false, false, userId); 16938 } catch (RemoteException e) { 16939 } 16940 }); 16941 } 16942 16943 @Override 16944 public void replacePreferredActivity(IntentFilter filter, int match, 16945 ComponentName[] set, ComponentName activity, int userId) { 16946 if (filter.countActions() != 1) { 16947 throw new IllegalArgumentException( 16948 "replacePreferredActivity expects filter to have only 1 action."); 16949 } 16950 if (filter.countDataAuthorities() != 0 16951 || filter.countDataPaths() != 0 16952 || filter.countDataSchemes() > 1 16953 || filter.countDataTypes() != 0) { 16954 throw new IllegalArgumentException( 16955 "replacePreferredActivity expects filter to have no data authorities, " + 16956 "paths, or types; and at most one scheme."); 16957 } 16958 16959 final int callingUid = Binder.getCallingUid(); 16960 enforceCrossUserPermission(callingUid, userId, 16961 true /* requireFullPermission */, false /* checkShell */, 16962 "replace preferred activity"); 16963 synchronized (mPackages) { 16964 if (mContext.checkCallingOrSelfPermission( 16965 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16966 != PackageManager.PERMISSION_GRANTED) { 16967 if (getUidTargetSdkVersionLockedLPr(callingUid) 16968 < Build.VERSION_CODES.FROYO) { 16969 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16970 + Binder.getCallingUid()); 16971 return; 16972 } 16973 mContext.enforceCallingOrSelfPermission( 16974 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16975 } 16976 16977 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16978 if (pir != null) { 16979 // Get all of the existing entries that exactly match this filter. 16980 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16981 if (existing != null && existing.size() == 1) { 16982 PreferredActivity cur = existing.get(0); 16983 if (DEBUG_PREFERRED) { 16984 Slog.i(TAG, "Checking replace of preferred:"); 16985 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16986 if (!cur.mPref.mAlways) { 16987 Slog.i(TAG, " -- CUR; not mAlways!"); 16988 } else { 16989 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16990 Slog.i(TAG, " -- CUR: mSet=" 16991 + Arrays.toString(cur.mPref.mSetComponents)); 16992 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16993 Slog.i(TAG, " -- NEW: mMatch=" 16994 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16995 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16996 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16997 } 16998 } 16999 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17000 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17001 && cur.mPref.sameSet(set)) { 17002 // Setting the preferred activity to what it happens to be already 17003 if (DEBUG_PREFERRED) { 17004 Slog.i(TAG, "Replacing with same preferred activity " 17005 + cur.mPref.mShortComponent + " for user " 17006 + userId + ":"); 17007 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17008 } 17009 return; 17010 } 17011 } 17012 17013 if (existing != null) { 17014 if (DEBUG_PREFERRED) { 17015 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17016 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17017 } 17018 for (int i = 0; i < existing.size(); i++) { 17019 PreferredActivity pa = existing.get(i); 17020 if (DEBUG_PREFERRED) { 17021 Slog.i(TAG, "Removing existing preferred activity " 17022 + pa.mPref.mComponent + ":"); 17023 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17024 } 17025 pir.removeFilter(pa); 17026 } 17027 } 17028 } 17029 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17030 "Replacing preferred"); 17031 } 17032 } 17033 17034 @Override 17035 public void clearPackagePreferredActivities(String packageName) { 17036 final int uid = Binder.getCallingUid(); 17037 // writer 17038 synchronized (mPackages) { 17039 PackageParser.Package pkg = mPackages.get(packageName); 17040 if (pkg == null || pkg.applicationInfo.uid != uid) { 17041 if (mContext.checkCallingOrSelfPermission( 17042 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17043 != PackageManager.PERMISSION_GRANTED) { 17044 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17045 < Build.VERSION_CODES.FROYO) { 17046 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17047 + Binder.getCallingUid()); 17048 return; 17049 } 17050 mContext.enforceCallingOrSelfPermission( 17051 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17052 } 17053 } 17054 17055 int user = UserHandle.getCallingUserId(); 17056 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17057 scheduleWritePackageRestrictionsLocked(user); 17058 } 17059 } 17060 } 17061 17062 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17063 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17064 ArrayList<PreferredActivity> removed = null; 17065 boolean changed = false; 17066 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17067 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17068 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17069 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17070 continue; 17071 } 17072 Iterator<PreferredActivity> it = pir.filterIterator(); 17073 while (it.hasNext()) { 17074 PreferredActivity pa = it.next(); 17075 // Mark entry for removal only if it matches the package name 17076 // and the entry is of type "always". 17077 if (packageName == null || 17078 (pa.mPref.mComponent.getPackageName().equals(packageName) 17079 && pa.mPref.mAlways)) { 17080 if (removed == null) { 17081 removed = new ArrayList<PreferredActivity>(); 17082 } 17083 removed.add(pa); 17084 } 17085 } 17086 if (removed != null) { 17087 for (int j=0; j<removed.size(); j++) { 17088 PreferredActivity pa = removed.get(j); 17089 pir.removeFilter(pa); 17090 } 17091 changed = true; 17092 } 17093 } 17094 if (changed) { 17095 postPreferredActivityChangedBroadcast(userId); 17096 } 17097 return changed; 17098 } 17099 17100 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17101 private void clearIntentFilterVerificationsLPw(int userId) { 17102 final int packageCount = mPackages.size(); 17103 for (int i = 0; i < packageCount; i++) { 17104 PackageParser.Package pkg = mPackages.valueAt(i); 17105 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17106 } 17107 } 17108 17109 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17110 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17111 if (userId == UserHandle.USER_ALL) { 17112 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17113 sUserManager.getUserIds())) { 17114 for (int oneUserId : sUserManager.getUserIds()) { 17115 scheduleWritePackageRestrictionsLocked(oneUserId); 17116 } 17117 } 17118 } else { 17119 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17120 scheduleWritePackageRestrictionsLocked(userId); 17121 } 17122 } 17123 } 17124 17125 void clearDefaultBrowserIfNeeded(String packageName) { 17126 for (int oneUserId : sUserManager.getUserIds()) { 17127 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17128 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17129 if (packageName.equals(defaultBrowserPackageName)) { 17130 setDefaultBrowserPackageName(null, oneUserId); 17131 } 17132 } 17133 } 17134 17135 @Override 17136 public void resetApplicationPreferences(int userId) { 17137 mContext.enforceCallingOrSelfPermission( 17138 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17139 final long identity = Binder.clearCallingIdentity(); 17140 // writer 17141 try { 17142 synchronized (mPackages) { 17143 clearPackagePreferredActivitiesLPw(null, userId); 17144 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17145 // TODO: We have to reset the default SMS and Phone. This requires 17146 // significant refactoring to keep all default apps in the package 17147 // manager (cleaner but more work) or have the services provide 17148 // callbacks to the package manager to request a default app reset. 17149 applyFactoryDefaultBrowserLPw(userId); 17150 clearIntentFilterVerificationsLPw(userId); 17151 primeDomainVerificationsLPw(userId); 17152 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17153 scheduleWritePackageRestrictionsLocked(userId); 17154 } 17155 resetNetworkPolicies(userId); 17156 } finally { 17157 Binder.restoreCallingIdentity(identity); 17158 } 17159 } 17160 17161 @Override 17162 public int getPreferredActivities(List<IntentFilter> outFilters, 17163 List<ComponentName> outActivities, String packageName) { 17164 17165 int num = 0; 17166 final int userId = UserHandle.getCallingUserId(); 17167 // reader 17168 synchronized (mPackages) { 17169 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17170 if (pir != null) { 17171 final Iterator<PreferredActivity> it = pir.filterIterator(); 17172 while (it.hasNext()) { 17173 final PreferredActivity pa = it.next(); 17174 if (packageName == null 17175 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17176 && pa.mPref.mAlways)) { 17177 if (outFilters != null) { 17178 outFilters.add(new IntentFilter(pa)); 17179 } 17180 if (outActivities != null) { 17181 outActivities.add(pa.mPref.mComponent); 17182 } 17183 } 17184 } 17185 } 17186 } 17187 17188 return num; 17189 } 17190 17191 @Override 17192 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17193 int userId) { 17194 int callingUid = Binder.getCallingUid(); 17195 if (callingUid != Process.SYSTEM_UID) { 17196 throw new SecurityException( 17197 "addPersistentPreferredActivity can only be run by the system"); 17198 } 17199 if (filter.countActions() == 0) { 17200 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17201 return; 17202 } 17203 synchronized (mPackages) { 17204 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17205 ":"); 17206 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17207 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17208 new PersistentPreferredActivity(filter, activity)); 17209 scheduleWritePackageRestrictionsLocked(userId); 17210 postPreferredActivityChangedBroadcast(userId); 17211 } 17212 } 17213 17214 @Override 17215 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17216 int callingUid = Binder.getCallingUid(); 17217 if (callingUid != Process.SYSTEM_UID) { 17218 throw new SecurityException( 17219 "clearPackagePersistentPreferredActivities can only be run by the system"); 17220 } 17221 ArrayList<PersistentPreferredActivity> removed = null; 17222 boolean changed = false; 17223 synchronized (mPackages) { 17224 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17225 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17226 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17227 .valueAt(i); 17228 if (userId != thisUserId) { 17229 continue; 17230 } 17231 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17232 while (it.hasNext()) { 17233 PersistentPreferredActivity ppa = it.next(); 17234 // Mark entry for removal only if it matches the package name. 17235 if (ppa.mComponent.getPackageName().equals(packageName)) { 17236 if (removed == null) { 17237 removed = new ArrayList<PersistentPreferredActivity>(); 17238 } 17239 removed.add(ppa); 17240 } 17241 } 17242 if (removed != null) { 17243 for (int j=0; j<removed.size(); j++) { 17244 PersistentPreferredActivity ppa = removed.get(j); 17245 ppir.removeFilter(ppa); 17246 } 17247 changed = true; 17248 } 17249 } 17250 17251 if (changed) { 17252 scheduleWritePackageRestrictionsLocked(userId); 17253 postPreferredActivityChangedBroadcast(userId); 17254 } 17255 } 17256 } 17257 17258 /** 17259 * Common machinery for picking apart a restored XML blob and passing 17260 * it to a caller-supplied functor to be applied to the running system. 17261 */ 17262 private void restoreFromXml(XmlPullParser parser, int userId, 17263 String expectedStartTag, BlobXmlRestorer functor) 17264 throws IOException, XmlPullParserException { 17265 int type; 17266 while ((type = parser.next()) != XmlPullParser.START_TAG 17267 && type != XmlPullParser.END_DOCUMENT) { 17268 } 17269 if (type != XmlPullParser.START_TAG) { 17270 // oops didn't find a start tag?! 17271 if (DEBUG_BACKUP) { 17272 Slog.e(TAG, "Didn't find start tag during restore"); 17273 } 17274 return; 17275 } 17276Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17277 // this is supposed to be TAG_PREFERRED_BACKUP 17278 if (!expectedStartTag.equals(parser.getName())) { 17279 if (DEBUG_BACKUP) { 17280 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17281 } 17282 return; 17283 } 17284 17285 // skip interfering stuff, then we're aligned with the backing implementation 17286 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17287Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17288 functor.apply(parser, userId); 17289 } 17290 17291 private interface BlobXmlRestorer { 17292 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17293 } 17294 17295 /** 17296 * Non-Binder method, support for the backup/restore mechanism: write the 17297 * full set of preferred activities in its canonical XML format. Returns the 17298 * XML output as a byte array, or null if there is none. 17299 */ 17300 @Override 17301 public byte[] getPreferredActivityBackup(int userId) { 17302 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17303 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17304 } 17305 17306 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17307 try { 17308 final XmlSerializer serializer = new FastXmlSerializer(); 17309 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17310 serializer.startDocument(null, true); 17311 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17312 17313 synchronized (mPackages) { 17314 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17315 } 17316 17317 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17318 serializer.endDocument(); 17319 serializer.flush(); 17320 } catch (Exception e) { 17321 if (DEBUG_BACKUP) { 17322 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17323 } 17324 return null; 17325 } 17326 17327 return dataStream.toByteArray(); 17328 } 17329 17330 @Override 17331 public void restorePreferredActivities(byte[] backup, int userId) { 17332 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17333 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17334 } 17335 17336 try { 17337 final XmlPullParser parser = Xml.newPullParser(); 17338 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17339 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17340 new BlobXmlRestorer() { 17341 @Override 17342 public void apply(XmlPullParser parser, int userId) 17343 throws XmlPullParserException, IOException { 17344 synchronized (mPackages) { 17345 mSettings.readPreferredActivitiesLPw(parser, userId); 17346 } 17347 } 17348 } ); 17349 } catch (Exception e) { 17350 if (DEBUG_BACKUP) { 17351 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17352 } 17353 } 17354 } 17355 17356 /** 17357 * Non-Binder method, support for the backup/restore mechanism: write the 17358 * default browser (etc) settings in its canonical XML format. Returns the default 17359 * browser XML representation as a byte array, or null if there is none. 17360 */ 17361 @Override 17362 public byte[] getDefaultAppsBackup(int userId) { 17363 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17364 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17365 } 17366 17367 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17368 try { 17369 final XmlSerializer serializer = new FastXmlSerializer(); 17370 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17371 serializer.startDocument(null, true); 17372 serializer.startTag(null, TAG_DEFAULT_APPS); 17373 17374 synchronized (mPackages) { 17375 mSettings.writeDefaultAppsLPr(serializer, userId); 17376 } 17377 17378 serializer.endTag(null, TAG_DEFAULT_APPS); 17379 serializer.endDocument(); 17380 serializer.flush(); 17381 } catch (Exception e) { 17382 if (DEBUG_BACKUP) { 17383 Slog.e(TAG, "Unable to write default apps for backup", e); 17384 } 17385 return null; 17386 } 17387 17388 return dataStream.toByteArray(); 17389 } 17390 17391 @Override 17392 public void restoreDefaultApps(byte[] backup, int userId) { 17393 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17394 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17395 } 17396 17397 try { 17398 final XmlPullParser parser = Xml.newPullParser(); 17399 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17400 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17401 new BlobXmlRestorer() { 17402 @Override 17403 public void apply(XmlPullParser parser, int userId) 17404 throws XmlPullParserException, IOException { 17405 synchronized (mPackages) { 17406 mSettings.readDefaultAppsLPw(parser, userId); 17407 } 17408 } 17409 } ); 17410 } catch (Exception e) { 17411 if (DEBUG_BACKUP) { 17412 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17413 } 17414 } 17415 } 17416 17417 @Override 17418 public byte[] getIntentFilterVerificationBackup(int userId) { 17419 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17420 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17421 } 17422 17423 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17424 try { 17425 final XmlSerializer serializer = new FastXmlSerializer(); 17426 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17427 serializer.startDocument(null, true); 17428 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17429 17430 synchronized (mPackages) { 17431 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17432 } 17433 17434 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17435 serializer.endDocument(); 17436 serializer.flush(); 17437 } catch (Exception e) { 17438 if (DEBUG_BACKUP) { 17439 Slog.e(TAG, "Unable to write default apps for backup", e); 17440 } 17441 return null; 17442 } 17443 17444 return dataStream.toByteArray(); 17445 } 17446 17447 @Override 17448 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17449 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17450 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17451 } 17452 17453 try { 17454 final XmlPullParser parser = Xml.newPullParser(); 17455 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17456 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17457 new BlobXmlRestorer() { 17458 @Override 17459 public void apply(XmlPullParser parser, int userId) 17460 throws XmlPullParserException, IOException { 17461 synchronized (mPackages) { 17462 mSettings.readAllDomainVerificationsLPr(parser, userId); 17463 mSettings.writeLPr(); 17464 } 17465 } 17466 } ); 17467 } catch (Exception e) { 17468 if (DEBUG_BACKUP) { 17469 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17470 } 17471 } 17472 } 17473 17474 @Override 17475 public byte[] getPermissionGrantBackup(int userId) { 17476 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17477 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17478 } 17479 17480 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17481 try { 17482 final XmlSerializer serializer = new FastXmlSerializer(); 17483 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17484 serializer.startDocument(null, true); 17485 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17486 17487 synchronized (mPackages) { 17488 serializeRuntimePermissionGrantsLPr(serializer, userId); 17489 } 17490 17491 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17492 serializer.endDocument(); 17493 serializer.flush(); 17494 } catch (Exception e) { 17495 if (DEBUG_BACKUP) { 17496 Slog.e(TAG, "Unable to write default apps for backup", e); 17497 } 17498 return null; 17499 } 17500 17501 return dataStream.toByteArray(); 17502 } 17503 17504 @Override 17505 public void restorePermissionGrants(byte[] backup, int userId) { 17506 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17507 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17508 } 17509 17510 try { 17511 final XmlPullParser parser = Xml.newPullParser(); 17512 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17513 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17514 new BlobXmlRestorer() { 17515 @Override 17516 public void apply(XmlPullParser parser, int userId) 17517 throws XmlPullParserException, IOException { 17518 synchronized (mPackages) { 17519 processRestoredPermissionGrantsLPr(parser, userId); 17520 } 17521 } 17522 } ); 17523 } catch (Exception e) { 17524 if (DEBUG_BACKUP) { 17525 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17526 } 17527 } 17528 } 17529 17530 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17531 throws IOException { 17532 serializer.startTag(null, TAG_ALL_GRANTS); 17533 17534 final int N = mSettings.mPackages.size(); 17535 for (int i = 0; i < N; i++) { 17536 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17537 boolean pkgGrantsKnown = false; 17538 17539 PermissionsState packagePerms = ps.getPermissionsState(); 17540 17541 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17542 final int grantFlags = state.getFlags(); 17543 // only look at grants that are not system/policy fixed 17544 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17545 final boolean isGranted = state.isGranted(); 17546 // And only back up the user-twiddled state bits 17547 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17548 final String packageName = mSettings.mPackages.keyAt(i); 17549 if (!pkgGrantsKnown) { 17550 serializer.startTag(null, TAG_GRANT); 17551 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17552 pkgGrantsKnown = true; 17553 } 17554 17555 final boolean userSet = 17556 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17557 final boolean userFixed = 17558 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17559 final boolean revoke = 17560 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17561 17562 serializer.startTag(null, TAG_PERMISSION); 17563 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17564 if (isGranted) { 17565 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17566 } 17567 if (userSet) { 17568 serializer.attribute(null, ATTR_USER_SET, "true"); 17569 } 17570 if (userFixed) { 17571 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17572 } 17573 if (revoke) { 17574 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17575 } 17576 serializer.endTag(null, TAG_PERMISSION); 17577 } 17578 } 17579 } 17580 17581 if (pkgGrantsKnown) { 17582 serializer.endTag(null, TAG_GRANT); 17583 } 17584 } 17585 17586 serializer.endTag(null, TAG_ALL_GRANTS); 17587 } 17588 17589 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17590 throws XmlPullParserException, IOException { 17591 String pkgName = null; 17592 int outerDepth = parser.getDepth(); 17593 int type; 17594 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17595 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17596 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17597 continue; 17598 } 17599 17600 final String tagName = parser.getName(); 17601 if (tagName.equals(TAG_GRANT)) { 17602 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17603 if (DEBUG_BACKUP) { 17604 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17605 } 17606 } else if (tagName.equals(TAG_PERMISSION)) { 17607 17608 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17609 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17610 17611 int newFlagSet = 0; 17612 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17613 newFlagSet |= FLAG_PERMISSION_USER_SET; 17614 } 17615 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17616 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17617 } 17618 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17619 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17620 } 17621 if (DEBUG_BACKUP) { 17622 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17623 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17624 } 17625 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17626 if (ps != null) { 17627 // Already installed so we apply the grant immediately 17628 if (DEBUG_BACKUP) { 17629 Slog.v(TAG, " + already installed; applying"); 17630 } 17631 PermissionsState perms = ps.getPermissionsState(); 17632 BasePermission bp = mSettings.mPermissions.get(permName); 17633 if (bp != null) { 17634 if (isGranted) { 17635 perms.grantRuntimePermission(bp, userId); 17636 } 17637 if (newFlagSet != 0) { 17638 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17639 } 17640 } 17641 } else { 17642 // Need to wait for post-restore install to apply the grant 17643 if (DEBUG_BACKUP) { 17644 Slog.v(TAG, " - not yet installed; saving for later"); 17645 } 17646 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17647 isGranted, newFlagSet, userId); 17648 } 17649 } else { 17650 PackageManagerService.reportSettingsProblem(Log.WARN, 17651 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17652 XmlUtils.skipCurrentTag(parser); 17653 } 17654 } 17655 17656 scheduleWriteSettingsLocked(); 17657 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17658 } 17659 17660 @Override 17661 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17662 int sourceUserId, int targetUserId, int flags) { 17663 mContext.enforceCallingOrSelfPermission( 17664 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17665 int callingUid = Binder.getCallingUid(); 17666 enforceOwnerRights(ownerPackage, callingUid); 17667 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17668 if (intentFilter.countActions() == 0) { 17669 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17670 return; 17671 } 17672 synchronized (mPackages) { 17673 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17674 ownerPackage, targetUserId, flags); 17675 CrossProfileIntentResolver resolver = 17676 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17677 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17678 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17679 if (existing != null) { 17680 int size = existing.size(); 17681 for (int i = 0; i < size; i++) { 17682 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17683 return; 17684 } 17685 } 17686 } 17687 resolver.addFilter(newFilter); 17688 scheduleWritePackageRestrictionsLocked(sourceUserId); 17689 } 17690 } 17691 17692 @Override 17693 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17694 mContext.enforceCallingOrSelfPermission( 17695 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17696 int callingUid = Binder.getCallingUid(); 17697 enforceOwnerRights(ownerPackage, callingUid); 17698 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17699 synchronized (mPackages) { 17700 CrossProfileIntentResolver resolver = 17701 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17702 ArraySet<CrossProfileIntentFilter> set = 17703 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17704 for (CrossProfileIntentFilter filter : set) { 17705 if (filter.getOwnerPackage().equals(ownerPackage)) { 17706 resolver.removeFilter(filter); 17707 } 17708 } 17709 scheduleWritePackageRestrictionsLocked(sourceUserId); 17710 } 17711 } 17712 17713 // Enforcing that callingUid is owning pkg on userId 17714 private void enforceOwnerRights(String pkg, int callingUid) { 17715 // The system owns everything. 17716 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17717 return; 17718 } 17719 int callingUserId = UserHandle.getUserId(callingUid); 17720 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17721 if (pi == null) { 17722 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17723 + callingUserId); 17724 } 17725 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17726 throw new SecurityException("Calling uid " + callingUid 17727 + " does not own package " + pkg); 17728 } 17729 } 17730 17731 @Override 17732 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17733 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17734 } 17735 17736 private Intent getHomeIntent() { 17737 Intent intent = new Intent(Intent.ACTION_MAIN); 17738 intent.addCategory(Intent.CATEGORY_HOME); 17739 intent.addCategory(Intent.CATEGORY_DEFAULT); 17740 return intent; 17741 } 17742 17743 private IntentFilter getHomeFilter() { 17744 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17745 filter.addCategory(Intent.CATEGORY_HOME); 17746 filter.addCategory(Intent.CATEGORY_DEFAULT); 17747 return filter; 17748 } 17749 17750 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17751 int userId) { 17752 Intent intent = getHomeIntent(); 17753 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17754 PackageManager.GET_META_DATA, userId); 17755 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17756 true, false, false, userId); 17757 17758 allHomeCandidates.clear(); 17759 if (list != null) { 17760 for (ResolveInfo ri : list) { 17761 allHomeCandidates.add(ri); 17762 } 17763 } 17764 return (preferred == null || preferred.activityInfo == null) 17765 ? null 17766 : new ComponentName(preferred.activityInfo.packageName, 17767 preferred.activityInfo.name); 17768 } 17769 17770 @Override 17771 public void setHomeActivity(ComponentName comp, int userId) { 17772 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17773 getHomeActivitiesAsUser(homeActivities, userId); 17774 17775 boolean found = false; 17776 17777 final int size = homeActivities.size(); 17778 final ComponentName[] set = new ComponentName[size]; 17779 for (int i = 0; i < size; i++) { 17780 final ResolveInfo candidate = homeActivities.get(i); 17781 final ActivityInfo info = candidate.activityInfo; 17782 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17783 set[i] = activityName; 17784 if (!found && activityName.equals(comp)) { 17785 found = true; 17786 } 17787 } 17788 if (!found) { 17789 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17790 + userId); 17791 } 17792 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17793 set, comp, userId); 17794 } 17795 17796 private @Nullable String getSetupWizardPackageName() { 17797 final Intent intent = new Intent(Intent.ACTION_MAIN); 17798 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17799 17800 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17801 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17802 | MATCH_DISABLED_COMPONENTS, 17803 UserHandle.myUserId()); 17804 if (matches.size() == 1) { 17805 return matches.get(0).getComponentInfo().packageName; 17806 } else { 17807 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17808 + ": matches=" + matches); 17809 return null; 17810 } 17811 } 17812 17813 private @Nullable String getStorageManagerPackageName() { 17814 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 17815 17816 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17817 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17818 | MATCH_DISABLED_COMPONENTS, 17819 UserHandle.myUserId()); 17820 if (matches.size() == 1) { 17821 return matches.get(0).getComponentInfo().packageName; 17822 } else { 17823 Slog.e(TAG, "There should probably be exactly one storage manager; found " 17824 + matches.size() + ": matches=" + matches); 17825 return null; 17826 } 17827 } 17828 17829 @Override 17830 public void setApplicationEnabledSetting(String appPackageName, 17831 int newState, int flags, int userId, String callingPackage) { 17832 if (!sUserManager.exists(userId)) return; 17833 if (callingPackage == null) { 17834 callingPackage = Integer.toString(Binder.getCallingUid()); 17835 } 17836 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17837 } 17838 17839 @Override 17840 public void setComponentEnabledSetting(ComponentName componentName, 17841 int newState, int flags, int userId) { 17842 if (!sUserManager.exists(userId)) return; 17843 setEnabledSetting(componentName.getPackageName(), 17844 componentName.getClassName(), newState, flags, userId, null); 17845 } 17846 17847 private void setEnabledSetting(final String packageName, String className, int newState, 17848 final int flags, int userId, String callingPackage) { 17849 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17850 || newState == COMPONENT_ENABLED_STATE_ENABLED 17851 || newState == COMPONENT_ENABLED_STATE_DISABLED 17852 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17853 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17854 throw new IllegalArgumentException("Invalid new component state: " 17855 + newState); 17856 } 17857 PackageSetting pkgSetting; 17858 final int uid = Binder.getCallingUid(); 17859 final int permission; 17860 if (uid == Process.SYSTEM_UID) { 17861 permission = PackageManager.PERMISSION_GRANTED; 17862 } else { 17863 permission = mContext.checkCallingOrSelfPermission( 17864 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17865 } 17866 enforceCrossUserPermission(uid, userId, 17867 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17868 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17869 boolean sendNow = false; 17870 boolean isApp = (className == null); 17871 String componentName = isApp ? packageName : className; 17872 int packageUid = -1; 17873 ArrayList<String> components; 17874 17875 // writer 17876 synchronized (mPackages) { 17877 pkgSetting = mSettings.mPackages.get(packageName); 17878 if (pkgSetting == null) { 17879 if (className == null) { 17880 throw new IllegalArgumentException("Unknown package: " + packageName); 17881 } 17882 throw new IllegalArgumentException( 17883 "Unknown component: " + packageName + "/" + className); 17884 } 17885 } 17886 17887 // Limit who can change which apps 17888 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17889 // Don't allow apps that don't have permission to modify other apps 17890 if (!allowedByPermission) { 17891 throw new SecurityException( 17892 "Permission Denial: attempt to change component state from pid=" 17893 + Binder.getCallingPid() 17894 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17895 } 17896 // Don't allow changing protected packages. 17897 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17898 throw new SecurityException("Cannot disable a protected package: " + packageName); 17899 } 17900 } 17901 17902 synchronized (mPackages) { 17903 if (uid == Process.SHELL_UID) { 17904 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17905 int oldState = pkgSetting.getEnabled(userId); 17906 if (className == null 17907 && 17908 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17909 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17910 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17911 && 17912 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17913 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17914 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17915 // ok 17916 } else { 17917 throw new SecurityException( 17918 "Shell cannot change component state for " + packageName + "/" 17919 + className + " to " + newState); 17920 } 17921 } 17922 if (className == null) { 17923 // We're dealing with an application/package level state change 17924 if (pkgSetting.getEnabled(userId) == newState) { 17925 // Nothing to do 17926 return; 17927 } 17928 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17929 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17930 // Don't care about who enables an app. 17931 callingPackage = null; 17932 } 17933 pkgSetting.setEnabled(newState, userId, callingPackage); 17934 // pkgSetting.pkg.mSetEnabled = newState; 17935 } else { 17936 // We're dealing with a component level state change 17937 // First, verify that this is a valid class name. 17938 PackageParser.Package pkg = pkgSetting.pkg; 17939 if (pkg == null || !pkg.hasComponentClassName(className)) { 17940 if (pkg != null && 17941 pkg.applicationInfo.targetSdkVersion >= 17942 Build.VERSION_CODES.JELLY_BEAN) { 17943 throw new IllegalArgumentException("Component class " + className 17944 + " does not exist in " + packageName); 17945 } else { 17946 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17947 + className + " does not exist in " + packageName); 17948 } 17949 } 17950 switch (newState) { 17951 case COMPONENT_ENABLED_STATE_ENABLED: 17952 if (!pkgSetting.enableComponentLPw(className, userId)) { 17953 return; 17954 } 17955 break; 17956 case COMPONENT_ENABLED_STATE_DISABLED: 17957 if (!pkgSetting.disableComponentLPw(className, userId)) { 17958 return; 17959 } 17960 break; 17961 case COMPONENT_ENABLED_STATE_DEFAULT: 17962 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17963 return; 17964 } 17965 break; 17966 default: 17967 Slog.e(TAG, "Invalid new component state: " + newState); 17968 return; 17969 } 17970 } 17971 scheduleWritePackageRestrictionsLocked(userId); 17972 components = mPendingBroadcasts.get(userId, packageName); 17973 final boolean newPackage = components == null; 17974 if (newPackage) { 17975 components = new ArrayList<String>(); 17976 } 17977 if (!components.contains(componentName)) { 17978 components.add(componentName); 17979 } 17980 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17981 sendNow = true; 17982 // Purge entry from pending broadcast list if another one exists already 17983 // since we are sending one right away. 17984 mPendingBroadcasts.remove(userId, packageName); 17985 } else { 17986 if (newPackage) { 17987 mPendingBroadcasts.put(userId, packageName, components); 17988 } 17989 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17990 // Schedule a message 17991 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17992 } 17993 } 17994 } 17995 17996 long callingId = Binder.clearCallingIdentity(); 17997 try { 17998 if (sendNow) { 17999 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18000 sendPackageChangedBroadcast(packageName, 18001 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18002 } 18003 } finally { 18004 Binder.restoreCallingIdentity(callingId); 18005 } 18006 } 18007 18008 @Override 18009 public void flushPackageRestrictionsAsUser(int userId) { 18010 if (!sUserManager.exists(userId)) { 18011 return; 18012 } 18013 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18014 false /* checkShell */, "flushPackageRestrictions"); 18015 synchronized (mPackages) { 18016 mSettings.writePackageRestrictionsLPr(userId); 18017 mDirtyUsers.remove(userId); 18018 if (mDirtyUsers.isEmpty()) { 18019 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18020 } 18021 } 18022 } 18023 18024 private void sendPackageChangedBroadcast(String packageName, 18025 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18026 if (DEBUG_INSTALL) 18027 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18028 + componentNames); 18029 Bundle extras = new Bundle(4); 18030 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18031 String nameList[] = new String[componentNames.size()]; 18032 componentNames.toArray(nameList); 18033 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18034 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18035 extras.putInt(Intent.EXTRA_UID, packageUid); 18036 // If this is not reporting a change of the overall package, then only send it 18037 // to registered receivers. We don't want to launch a swath of apps for every 18038 // little component state change. 18039 final int flags = !componentNames.contains(packageName) 18040 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18041 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18042 new int[] {UserHandle.getUserId(packageUid)}); 18043 } 18044 18045 @Override 18046 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18047 if (!sUserManager.exists(userId)) return; 18048 final int uid = Binder.getCallingUid(); 18049 final int permission = mContext.checkCallingOrSelfPermission( 18050 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18051 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18052 enforceCrossUserPermission(uid, userId, 18053 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18054 // writer 18055 synchronized (mPackages) { 18056 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18057 allowedByPermission, uid, userId)) { 18058 scheduleWritePackageRestrictionsLocked(userId); 18059 } 18060 } 18061 } 18062 18063 @Override 18064 public String getInstallerPackageName(String packageName) { 18065 // reader 18066 synchronized (mPackages) { 18067 return mSettings.getInstallerPackageNameLPr(packageName); 18068 } 18069 } 18070 18071 public boolean isOrphaned(String packageName) { 18072 // reader 18073 synchronized (mPackages) { 18074 return mSettings.isOrphaned(packageName); 18075 } 18076 } 18077 18078 @Override 18079 public int getApplicationEnabledSetting(String packageName, int userId) { 18080 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18081 int uid = Binder.getCallingUid(); 18082 enforceCrossUserPermission(uid, userId, 18083 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18084 // reader 18085 synchronized (mPackages) { 18086 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18087 } 18088 } 18089 18090 @Override 18091 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18092 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18093 int uid = Binder.getCallingUid(); 18094 enforceCrossUserPermission(uid, userId, 18095 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18096 // reader 18097 synchronized (mPackages) { 18098 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18099 } 18100 } 18101 18102 @Override 18103 public void enterSafeMode() { 18104 enforceSystemOrRoot("Only the system can request entering safe mode"); 18105 18106 if (!mSystemReady) { 18107 mSafeMode = true; 18108 } 18109 } 18110 18111 @Override 18112 public void systemReady() { 18113 mSystemReady = true; 18114 18115 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18116 // disabled after already being started. 18117 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18118 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18119 18120 // Read the compatibilty setting when the system is ready. 18121 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18122 mContext.getContentResolver(), 18123 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18124 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18125 if (DEBUG_SETTINGS) { 18126 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18127 } 18128 18129 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18130 18131 synchronized (mPackages) { 18132 // Verify that all of the preferred activity components actually 18133 // exist. It is possible for applications to be updated and at 18134 // that point remove a previously declared activity component that 18135 // had been set as a preferred activity. We try to clean this up 18136 // the next time we encounter that preferred activity, but it is 18137 // possible for the user flow to never be able to return to that 18138 // situation so here we do a sanity check to make sure we haven't 18139 // left any junk around. 18140 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18141 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18142 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18143 removed.clear(); 18144 for (PreferredActivity pa : pir.filterSet()) { 18145 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18146 removed.add(pa); 18147 } 18148 } 18149 if (removed.size() > 0) { 18150 for (int r=0; r<removed.size(); r++) { 18151 PreferredActivity pa = removed.get(r); 18152 Slog.w(TAG, "Removing dangling preferred activity: " 18153 + pa.mPref.mComponent); 18154 pir.removeFilter(pa); 18155 } 18156 mSettings.writePackageRestrictionsLPr( 18157 mSettings.mPreferredActivities.keyAt(i)); 18158 } 18159 } 18160 18161 for (int userId : UserManagerService.getInstance().getUserIds()) { 18162 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18163 grantPermissionsUserIds = ArrayUtils.appendInt( 18164 grantPermissionsUserIds, userId); 18165 } 18166 } 18167 } 18168 sUserManager.systemReady(); 18169 18170 // If we upgraded grant all default permissions before kicking off. 18171 for (int userId : grantPermissionsUserIds) { 18172 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18173 } 18174 18175 // If we did not grant default permissions, we preload from this the 18176 // default permission exceptions lazily to ensure we don't hit the 18177 // disk on a new user creation. 18178 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18179 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18180 } 18181 18182 // Kick off any messages waiting for system ready 18183 if (mPostSystemReadyMessages != null) { 18184 for (Message msg : mPostSystemReadyMessages) { 18185 msg.sendToTarget(); 18186 } 18187 mPostSystemReadyMessages = null; 18188 } 18189 18190 // Watch for external volumes that come and go over time 18191 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18192 storage.registerListener(mStorageListener); 18193 18194 mInstallerService.systemReady(); 18195 mPackageDexOptimizer.systemReady(); 18196 18197 MountServiceInternal mountServiceInternal = LocalServices.getService( 18198 MountServiceInternal.class); 18199 mountServiceInternal.addExternalStoragePolicy( 18200 new MountServiceInternal.ExternalStorageMountPolicy() { 18201 @Override 18202 public int getMountMode(int uid, String packageName) { 18203 if (Process.isIsolated(uid)) { 18204 return Zygote.MOUNT_EXTERNAL_NONE; 18205 } 18206 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18207 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18208 } 18209 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18210 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18211 } 18212 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18213 return Zygote.MOUNT_EXTERNAL_READ; 18214 } 18215 return Zygote.MOUNT_EXTERNAL_WRITE; 18216 } 18217 18218 @Override 18219 public boolean hasExternalStorage(int uid, String packageName) { 18220 return true; 18221 } 18222 }); 18223 18224 // Now that we're mostly running, clean up stale users and apps 18225 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18226 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18227 } 18228 18229 @Override 18230 public boolean isSafeMode() { 18231 return mSafeMode; 18232 } 18233 18234 @Override 18235 public boolean hasSystemUidErrors() { 18236 return mHasSystemUidErrors; 18237 } 18238 18239 static String arrayToString(int[] array) { 18240 StringBuffer buf = new StringBuffer(128); 18241 buf.append('['); 18242 if (array != null) { 18243 for (int i=0; i<array.length; i++) { 18244 if (i > 0) buf.append(", "); 18245 buf.append(array[i]); 18246 } 18247 } 18248 buf.append(']'); 18249 return buf.toString(); 18250 } 18251 18252 static class DumpState { 18253 public static final int DUMP_LIBS = 1 << 0; 18254 public static final int DUMP_FEATURES = 1 << 1; 18255 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18256 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18257 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18258 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18259 public static final int DUMP_PERMISSIONS = 1 << 6; 18260 public static final int DUMP_PACKAGES = 1 << 7; 18261 public static final int DUMP_SHARED_USERS = 1 << 8; 18262 public static final int DUMP_MESSAGES = 1 << 9; 18263 public static final int DUMP_PROVIDERS = 1 << 10; 18264 public static final int DUMP_VERIFIERS = 1 << 11; 18265 public static final int DUMP_PREFERRED = 1 << 12; 18266 public static final int DUMP_PREFERRED_XML = 1 << 13; 18267 public static final int DUMP_KEYSETS = 1 << 14; 18268 public static final int DUMP_VERSION = 1 << 15; 18269 public static final int DUMP_INSTALLS = 1 << 16; 18270 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18271 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18272 public static final int DUMP_FROZEN = 1 << 19; 18273 public static final int DUMP_DEXOPT = 1 << 20; 18274 public static final int DUMP_COMPILER_STATS = 1 << 21; 18275 18276 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18277 18278 private int mTypes; 18279 18280 private int mOptions; 18281 18282 private boolean mTitlePrinted; 18283 18284 private SharedUserSetting mSharedUser; 18285 18286 public boolean isDumping(int type) { 18287 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18288 return true; 18289 } 18290 18291 return (mTypes & type) != 0; 18292 } 18293 18294 public void setDump(int type) { 18295 mTypes |= type; 18296 } 18297 18298 public boolean isOptionEnabled(int option) { 18299 return (mOptions & option) != 0; 18300 } 18301 18302 public void setOptionEnabled(int option) { 18303 mOptions |= option; 18304 } 18305 18306 public boolean onTitlePrinted() { 18307 final boolean printed = mTitlePrinted; 18308 mTitlePrinted = true; 18309 return printed; 18310 } 18311 18312 public boolean getTitlePrinted() { 18313 return mTitlePrinted; 18314 } 18315 18316 public void setTitlePrinted(boolean enabled) { 18317 mTitlePrinted = enabled; 18318 } 18319 18320 public SharedUserSetting getSharedUser() { 18321 return mSharedUser; 18322 } 18323 18324 public void setSharedUser(SharedUserSetting user) { 18325 mSharedUser = user; 18326 } 18327 } 18328 18329 @Override 18330 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18331 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18332 (new PackageManagerShellCommand(this)).exec( 18333 this, in, out, err, args, resultReceiver); 18334 } 18335 18336 @Override 18337 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18338 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18339 != PackageManager.PERMISSION_GRANTED) { 18340 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18341 + Binder.getCallingPid() 18342 + ", uid=" + Binder.getCallingUid() 18343 + " without permission " 18344 + android.Manifest.permission.DUMP); 18345 return; 18346 } 18347 18348 DumpState dumpState = new DumpState(); 18349 boolean fullPreferred = false; 18350 boolean checkin = false; 18351 18352 String packageName = null; 18353 ArraySet<String> permissionNames = null; 18354 18355 int opti = 0; 18356 while (opti < args.length) { 18357 String opt = args[opti]; 18358 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18359 break; 18360 } 18361 opti++; 18362 18363 if ("-a".equals(opt)) { 18364 // Right now we only know how to print all. 18365 } else if ("-h".equals(opt)) { 18366 pw.println("Package manager dump options:"); 18367 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18368 pw.println(" --checkin: dump for a checkin"); 18369 pw.println(" -f: print details of intent filters"); 18370 pw.println(" -h: print this help"); 18371 pw.println(" cmd may be one of:"); 18372 pw.println(" l[ibraries]: list known shared libraries"); 18373 pw.println(" f[eatures]: list device features"); 18374 pw.println(" k[eysets]: print known keysets"); 18375 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18376 pw.println(" perm[issions]: dump permissions"); 18377 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18378 pw.println(" pref[erred]: print preferred package settings"); 18379 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18380 pw.println(" prov[iders]: dump content providers"); 18381 pw.println(" p[ackages]: dump installed packages"); 18382 pw.println(" s[hared-users]: dump shared user IDs"); 18383 pw.println(" m[essages]: print collected runtime messages"); 18384 pw.println(" v[erifiers]: print package verifier info"); 18385 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18386 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18387 pw.println(" version: print database version info"); 18388 pw.println(" write: write current settings now"); 18389 pw.println(" installs: details about install sessions"); 18390 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18391 pw.println(" dexopt: dump dexopt state"); 18392 pw.println(" compiler-stats: dump compiler statistics"); 18393 pw.println(" <package.name>: info about given package"); 18394 return; 18395 } else if ("--checkin".equals(opt)) { 18396 checkin = true; 18397 } else if ("-f".equals(opt)) { 18398 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18399 } else { 18400 pw.println("Unknown argument: " + opt + "; use -h for help"); 18401 } 18402 } 18403 18404 // Is the caller requesting to dump a particular piece of data? 18405 if (opti < args.length) { 18406 String cmd = args[opti]; 18407 opti++; 18408 // Is this a package name? 18409 if ("android".equals(cmd) || cmd.contains(".")) { 18410 packageName = cmd; 18411 // When dumping a single package, we always dump all of its 18412 // filter information since the amount of data will be reasonable. 18413 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18414 } else if ("check-permission".equals(cmd)) { 18415 if (opti >= args.length) { 18416 pw.println("Error: check-permission missing permission argument"); 18417 return; 18418 } 18419 String perm = args[opti]; 18420 opti++; 18421 if (opti >= args.length) { 18422 pw.println("Error: check-permission missing package argument"); 18423 return; 18424 } 18425 String pkg = args[opti]; 18426 opti++; 18427 int user = UserHandle.getUserId(Binder.getCallingUid()); 18428 if (opti < args.length) { 18429 try { 18430 user = Integer.parseInt(args[opti]); 18431 } catch (NumberFormatException e) { 18432 pw.println("Error: check-permission user argument is not a number: " 18433 + args[opti]); 18434 return; 18435 } 18436 } 18437 pw.println(checkPermission(perm, pkg, user)); 18438 return; 18439 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18440 dumpState.setDump(DumpState.DUMP_LIBS); 18441 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18442 dumpState.setDump(DumpState.DUMP_FEATURES); 18443 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18444 if (opti >= args.length) { 18445 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18446 | DumpState.DUMP_SERVICE_RESOLVERS 18447 | DumpState.DUMP_RECEIVER_RESOLVERS 18448 | DumpState.DUMP_CONTENT_RESOLVERS); 18449 } else { 18450 while (opti < args.length) { 18451 String name = args[opti]; 18452 if ("a".equals(name) || "activity".equals(name)) { 18453 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18454 } else if ("s".equals(name) || "service".equals(name)) { 18455 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18456 } else if ("r".equals(name) || "receiver".equals(name)) { 18457 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18458 } else if ("c".equals(name) || "content".equals(name)) { 18459 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18460 } else { 18461 pw.println("Error: unknown resolver table type: " + name); 18462 return; 18463 } 18464 opti++; 18465 } 18466 } 18467 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18468 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18469 } else if ("permission".equals(cmd)) { 18470 if (opti >= args.length) { 18471 pw.println("Error: permission requires permission name"); 18472 return; 18473 } 18474 permissionNames = new ArraySet<>(); 18475 while (opti < args.length) { 18476 permissionNames.add(args[opti]); 18477 opti++; 18478 } 18479 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18480 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18481 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18482 dumpState.setDump(DumpState.DUMP_PREFERRED); 18483 } else if ("preferred-xml".equals(cmd)) { 18484 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18485 if (opti < args.length && "--full".equals(args[opti])) { 18486 fullPreferred = true; 18487 opti++; 18488 } 18489 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18490 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18491 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18492 dumpState.setDump(DumpState.DUMP_PACKAGES); 18493 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18494 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18495 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18496 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18497 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18498 dumpState.setDump(DumpState.DUMP_MESSAGES); 18499 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18500 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18501 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18502 || "intent-filter-verifiers".equals(cmd)) { 18503 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18504 } else if ("version".equals(cmd)) { 18505 dumpState.setDump(DumpState.DUMP_VERSION); 18506 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18507 dumpState.setDump(DumpState.DUMP_KEYSETS); 18508 } else if ("installs".equals(cmd)) { 18509 dumpState.setDump(DumpState.DUMP_INSTALLS); 18510 } else if ("frozen".equals(cmd)) { 18511 dumpState.setDump(DumpState.DUMP_FROZEN); 18512 } else if ("dexopt".equals(cmd)) { 18513 dumpState.setDump(DumpState.DUMP_DEXOPT); 18514 } else if ("compiler-stats".equals(cmd)) { 18515 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18516 } else if ("write".equals(cmd)) { 18517 synchronized (mPackages) { 18518 mSettings.writeLPr(); 18519 pw.println("Settings written."); 18520 return; 18521 } 18522 } 18523 } 18524 18525 if (checkin) { 18526 pw.println("vers,1"); 18527 } 18528 18529 // reader 18530 synchronized (mPackages) { 18531 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18532 if (!checkin) { 18533 if (dumpState.onTitlePrinted()) 18534 pw.println(); 18535 pw.println("Database versions:"); 18536 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18537 } 18538 } 18539 18540 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18541 if (!checkin) { 18542 if (dumpState.onTitlePrinted()) 18543 pw.println(); 18544 pw.println("Verifiers:"); 18545 pw.print(" Required: "); 18546 pw.print(mRequiredVerifierPackage); 18547 pw.print(" (uid="); 18548 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18549 UserHandle.USER_SYSTEM)); 18550 pw.println(")"); 18551 } else if (mRequiredVerifierPackage != null) { 18552 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18553 pw.print(","); 18554 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18555 UserHandle.USER_SYSTEM)); 18556 } 18557 } 18558 18559 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18560 packageName == null) { 18561 if (mIntentFilterVerifierComponent != null) { 18562 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18563 if (!checkin) { 18564 if (dumpState.onTitlePrinted()) 18565 pw.println(); 18566 pw.println("Intent Filter Verifier:"); 18567 pw.print(" Using: "); 18568 pw.print(verifierPackageName); 18569 pw.print(" (uid="); 18570 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18571 UserHandle.USER_SYSTEM)); 18572 pw.println(")"); 18573 } else if (verifierPackageName != null) { 18574 pw.print("ifv,"); pw.print(verifierPackageName); 18575 pw.print(","); 18576 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18577 UserHandle.USER_SYSTEM)); 18578 } 18579 } else { 18580 pw.println(); 18581 pw.println("No Intent Filter Verifier available!"); 18582 } 18583 } 18584 18585 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18586 boolean printedHeader = false; 18587 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18588 while (it.hasNext()) { 18589 String name = it.next(); 18590 SharedLibraryEntry ent = mSharedLibraries.get(name); 18591 if (!checkin) { 18592 if (!printedHeader) { 18593 if (dumpState.onTitlePrinted()) 18594 pw.println(); 18595 pw.println("Libraries:"); 18596 printedHeader = true; 18597 } 18598 pw.print(" "); 18599 } else { 18600 pw.print("lib,"); 18601 } 18602 pw.print(name); 18603 if (!checkin) { 18604 pw.print(" -> "); 18605 } 18606 if (ent.path != null) { 18607 if (!checkin) { 18608 pw.print("(jar) "); 18609 pw.print(ent.path); 18610 } else { 18611 pw.print(",jar,"); 18612 pw.print(ent.path); 18613 } 18614 } else { 18615 if (!checkin) { 18616 pw.print("(apk) "); 18617 pw.print(ent.apk); 18618 } else { 18619 pw.print(",apk,"); 18620 pw.print(ent.apk); 18621 } 18622 } 18623 pw.println(); 18624 } 18625 } 18626 18627 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18628 if (dumpState.onTitlePrinted()) 18629 pw.println(); 18630 if (!checkin) { 18631 pw.println("Features:"); 18632 } 18633 18634 for (FeatureInfo feat : mAvailableFeatures.values()) { 18635 if (checkin) { 18636 pw.print("feat,"); 18637 pw.print(feat.name); 18638 pw.print(","); 18639 pw.println(feat.version); 18640 } else { 18641 pw.print(" "); 18642 pw.print(feat.name); 18643 if (feat.version > 0) { 18644 pw.print(" version="); 18645 pw.print(feat.version); 18646 } 18647 pw.println(); 18648 } 18649 } 18650 } 18651 18652 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18653 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18654 : "Activity Resolver Table:", " ", packageName, 18655 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18656 dumpState.setTitlePrinted(true); 18657 } 18658 } 18659 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18660 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18661 : "Receiver Resolver Table:", " ", packageName, 18662 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18663 dumpState.setTitlePrinted(true); 18664 } 18665 } 18666 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18667 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18668 : "Service Resolver Table:", " ", packageName, 18669 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18670 dumpState.setTitlePrinted(true); 18671 } 18672 } 18673 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18674 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18675 : "Provider Resolver Table:", " ", packageName, 18676 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18677 dumpState.setTitlePrinted(true); 18678 } 18679 } 18680 18681 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18682 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18683 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18684 int user = mSettings.mPreferredActivities.keyAt(i); 18685 if (pir.dump(pw, 18686 dumpState.getTitlePrinted() 18687 ? "\nPreferred Activities User " + user + ":" 18688 : "Preferred Activities User " + user + ":", " ", 18689 packageName, true, false)) { 18690 dumpState.setTitlePrinted(true); 18691 } 18692 } 18693 } 18694 18695 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18696 pw.flush(); 18697 FileOutputStream fout = new FileOutputStream(fd); 18698 BufferedOutputStream str = new BufferedOutputStream(fout); 18699 XmlSerializer serializer = new FastXmlSerializer(); 18700 try { 18701 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18702 serializer.startDocument(null, true); 18703 serializer.setFeature( 18704 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18705 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18706 serializer.endDocument(); 18707 serializer.flush(); 18708 } catch (IllegalArgumentException e) { 18709 pw.println("Failed writing: " + e); 18710 } catch (IllegalStateException e) { 18711 pw.println("Failed writing: " + e); 18712 } catch (IOException e) { 18713 pw.println("Failed writing: " + e); 18714 } 18715 } 18716 18717 if (!checkin 18718 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18719 && packageName == null) { 18720 pw.println(); 18721 int count = mSettings.mPackages.size(); 18722 if (count == 0) { 18723 pw.println("No applications!"); 18724 pw.println(); 18725 } else { 18726 final String prefix = " "; 18727 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18728 if (allPackageSettings.size() == 0) { 18729 pw.println("No domain preferred apps!"); 18730 pw.println(); 18731 } else { 18732 pw.println("App verification status:"); 18733 pw.println(); 18734 count = 0; 18735 for (PackageSetting ps : allPackageSettings) { 18736 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18737 if (ivi == null || ivi.getPackageName() == null) continue; 18738 pw.println(prefix + "Package: " + ivi.getPackageName()); 18739 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18740 pw.println(prefix + "Status: " + ivi.getStatusString()); 18741 pw.println(); 18742 count++; 18743 } 18744 if (count == 0) { 18745 pw.println(prefix + "No app verification established."); 18746 pw.println(); 18747 } 18748 for (int userId : sUserManager.getUserIds()) { 18749 pw.println("App linkages for user " + userId + ":"); 18750 pw.println(); 18751 count = 0; 18752 for (PackageSetting ps : allPackageSettings) { 18753 final long status = ps.getDomainVerificationStatusForUser(userId); 18754 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18755 continue; 18756 } 18757 pw.println(prefix + "Package: " + ps.name); 18758 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18759 String statusStr = IntentFilterVerificationInfo. 18760 getStatusStringFromValue(status); 18761 pw.println(prefix + "Status: " + statusStr); 18762 pw.println(); 18763 count++; 18764 } 18765 if (count == 0) { 18766 pw.println(prefix + "No configured app linkages."); 18767 pw.println(); 18768 } 18769 } 18770 } 18771 } 18772 } 18773 18774 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18775 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18776 if (packageName == null && permissionNames == null) { 18777 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18778 if (iperm == 0) { 18779 if (dumpState.onTitlePrinted()) 18780 pw.println(); 18781 pw.println("AppOp Permissions:"); 18782 } 18783 pw.print(" AppOp Permission "); 18784 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18785 pw.println(":"); 18786 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18787 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18788 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18789 } 18790 } 18791 } 18792 } 18793 18794 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18795 boolean printedSomething = false; 18796 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18797 if (packageName != null && !packageName.equals(p.info.packageName)) { 18798 continue; 18799 } 18800 if (!printedSomething) { 18801 if (dumpState.onTitlePrinted()) 18802 pw.println(); 18803 pw.println("Registered ContentProviders:"); 18804 printedSomething = true; 18805 } 18806 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18807 pw.print(" "); pw.println(p.toString()); 18808 } 18809 printedSomething = false; 18810 for (Map.Entry<String, PackageParser.Provider> entry : 18811 mProvidersByAuthority.entrySet()) { 18812 PackageParser.Provider p = entry.getValue(); 18813 if (packageName != null && !packageName.equals(p.info.packageName)) { 18814 continue; 18815 } 18816 if (!printedSomething) { 18817 if (dumpState.onTitlePrinted()) 18818 pw.println(); 18819 pw.println("ContentProvider Authorities:"); 18820 printedSomething = true; 18821 } 18822 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18823 pw.print(" "); pw.println(p.toString()); 18824 if (p.info != null && p.info.applicationInfo != null) { 18825 final String appInfo = p.info.applicationInfo.toString(); 18826 pw.print(" applicationInfo="); pw.println(appInfo); 18827 } 18828 } 18829 } 18830 18831 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18832 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18833 } 18834 18835 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18836 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18837 } 18838 18839 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18840 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18841 } 18842 18843 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18844 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18845 } 18846 18847 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18848 // XXX should handle packageName != null by dumping only install data that 18849 // the given package is involved with. 18850 if (dumpState.onTitlePrinted()) pw.println(); 18851 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18852 } 18853 18854 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18855 // XXX should handle packageName != null by dumping only install data that 18856 // the given package is involved with. 18857 if (dumpState.onTitlePrinted()) pw.println(); 18858 18859 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18860 ipw.println(); 18861 ipw.println("Frozen packages:"); 18862 ipw.increaseIndent(); 18863 if (mFrozenPackages.size() == 0) { 18864 ipw.println("(none)"); 18865 } else { 18866 for (int i = 0; i < mFrozenPackages.size(); i++) { 18867 ipw.println(mFrozenPackages.valueAt(i)); 18868 } 18869 } 18870 ipw.decreaseIndent(); 18871 } 18872 18873 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18874 if (dumpState.onTitlePrinted()) pw.println(); 18875 dumpDexoptStateLPr(pw, packageName); 18876 } 18877 18878 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 18879 if (dumpState.onTitlePrinted()) pw.println(); 18880 dumpCompilerStatsLPr(pw, packageName); 18881 } 18882 18883 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18884 if (dumpState.onTitlePrinted()) pw.println(); 18885 mSettings.dumpReadMessagesLPr(pw, dumpState); 18886 18887 pw.println(); 18888 pw.println("Package warning messages:"); 18889 BufferedReader in = null; 18890 String line = null; 18891 try { 18892 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18893 while ((line = in.readLine()) != null) { 18894 if (line.contains("ignored: updated version")) continue; 18895 pw.println(line); 18896 } 18897 } catch (IOException ignored) { 18898 } finally { 18899 IoUtils.closeQuietly(in); 18900 } 18901 } 18902 18903 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18904 BufferedReader in = null; 18905 String line = null; 18906 try { 18907 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18908 while ((line = in.readLine()) != null) { 18909 if (line.contains("ignored: updated version")) continue; 18910 pw.print("msg,"); 18911 pw.println(line); 18912 } 18913 } catch (IOException ignored) { 18914 } finally { 18915 IoUtils.closeQuietly(in); 18916 } 18917 } 18918 } 18919 } 18920 18921 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18922 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18923 ipw.println(); 18924 ipw.println("Dexopt state:"); 18925 ipw.increaseIndent(); 18926 Collection<PackageParser.Package> packages = null; 18927 if (packageName != null) { 18928 PackageParser.Package targetPackage = mPackages.get(packageName); 18929 if (targetPackage != null) { 18930 packages = Collections.singletonList(targetPackage); 18931 } else { 18932 ipw.println("Unable to find package: " + packageName); 18933 return; 18934 } 18935 } else { 18936 packages = mPackages.values(); 18937 } 18938 18939 for (PackageParser.Package pkg : packages) { 18940 ipw.println("[" + pkg.packageName + "]"); 18941 ipw.increaseIndent(); 18942 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18943 ipw.decreaseIndent(); 18944 } 18945 } 18946 18947 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 18948 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18949 ipw.println(); 18950 ipw.println("Compiler stats:"); 18951 ipw.increaseIndent(); 18952 Collection<PackageParser.Package> packages = null; 18953 if (packageName != null) { 18954 PackageParser.Package targetPackage = mPackages.get(packageName); 18955 if (targetPackage != null) { 18956 packages = Collections.singletonList(targetPackage); 18957 } else { 18958 ipw.println("Unable to find package: " + packageName); 18959 return; 18960 } 18961 } else { 18962 packages = mPackages.values(); 18963 } 18964 18965 for (PackageParser.Package pkg : packages) { 18966 ipw.println("[" + pkg.packageName + "]"); 18967 ipw.increaseIndent(); 18968 18969 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 18970 if (stats == null) { 18971 ipw.println("(No recorded stats)"); 18972 } else { 18973 stats.dump(ipw); 18974 } 18975 ipw.decreaseIndent(); 18976 } 18977 } 18978 18979 private String dumpDomainString(String packageName) { 18980 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18981 .getList(); 18982 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18983 18984 ArraySet<String> result = new ArraySet<>(); 18985 if (iviList.size() > 0) { 18986 for (IntentFilterVerificationInfo ivi : iviList) { 18987 for (String host : ivi.getDomains()) { 18988 result.add(host); 18989 } 18990 } 18991 } 18992 if (filters != null && filters.size() > 0) { 18993 for (IntentFilter filter : filters) { 18994 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18995 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18996 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18997 result.addAll(filter.getHostsList()); 18998 } 18999 } 19000 } 19001 19002 StringBuilder sb = new StringBuilder(result.size() * 16); 19003 for (String domain : result) { 19004 if (sb.length() > 0) sb.append(" "); 19005 sb.append(domain); 19006 } 19007 return sb.toString(); 19008 } 19009 19010 // ------- apps on sdcard specific code ------- 19011 static final boolean DEBUG_SD_INSTALL = false; 19012 19013 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19014 19015 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19016 19017 private boolean mMediaMounted = false; 19018 19019 static String getEncryptKey() { 19020 try { 19021 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19022 SD_ENCRYPTION_KEYSTORE_NAME); 19023 if (sdEncKey == null) { 19024 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19025 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19026 if (sdEncKey == null) { 19027 Slog.e(TAG, "Failed to create encryption keys"); 19028 return null; 19029 } 19030 } 19031 return sdEncKey; 19032 } catch (NoSuchAlgorithmException nsae) { 19033 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19034 return null; 19035 } catch (IOException ioe) { 19036 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19037 return null; 19038 } 19039 } 19040 19041 /* 19042 * Update media status on PackageManager. 19043 */ 19044 @Override 19045 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19046 int callingUid = Binder.getCallingUid(); 19047 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19048 throw new SecurityException("Media status can only be updated by the system"); 19049 } 19050 // reader; this apparently protects mMediaMounted, but should probably 19051 // be a different lock in that case. 19052 synchronized (mPackages) { 19053 Log.i(TAG, "Updating external media status from " 19054 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19055 + (mediaStatus ? "mounted" : "unmounted")); 19056 if (DEBUG_SD_INSTALL) 19057 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19058 + ", mMediaMounted=" + mMediaMounted); 19059 if (mediaStatus == mMediaMounted) { 19060 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19061 : 0, -1); 19062 mHandler.sendMessage(msg); 19063 return; 19064 } 19065 mMediaMounted = mediaStatus; 19066 } 19067 // Queue up an async operation since the package installation may take a 19068 // little while. 19069 mHandler.post(new Runnable() { 19070 public void run() { 19071 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19072 } 19073 }); 19074 } 19075 19076 /** 19077 * Called by MountService when the initial ASECs to scan are available. 19078 * Should block until all the ASEC containers are finished being scanned. 19079 */ 19080 public void scanAvailableAsecs() { 19081 updateExternalMediaStatusInner(true, false, false); 19082 } 19083 19084 /* 19085 * Collect information of applications on external media, map them against 19086 * existing containers and update information based on current mount status. 19087 * Please note that we always have to report status if reportStatus has been 19088 * set to true especially when unloading packages. 19089 */ 19090 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19091 boolean externalStorage) { 19092 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19093 int[] uidArr = EmptyArray.INT; 19094 19095 final String[] list = PackageHelper.getSecureContainerList(); 19096 if (ArrayUtils.isEmpty(list)) { 19097 Log.i(TAG, "No secure containers found"); 19098 } else { 19099 // Process list of secure containers and categorize them 19100 // as active or stale based on their package internal state. 19101 19102 // reader 19103 synchronized (mPackages) { 19104 for (String cid : list) { 19105 // Leave stages untouched for now; installer service owns them 19106 if (PackageInstallerService.isStageName(cid)) continue; 19107 19108 if (DEBUG_SD_INSTALL) 19109 Log.i(TAG, "Processing container " + cid); 19110 String pkgName = getAsecPackageName(cid); 19111 if (pkgName == null) { 19112 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19113 continue; 19114 } 19115 if (DEBUG_SD_INSTALL) 19116 Log.i(TAG, "Looking for pkg : " + pkgName); 19117 19118 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19119 if (ps == null) { 19120 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19121 continue; 19122 } 19123 19124 /* 19125 * Skip packages that are not external if we're unmounting 19126 * external storage. 19127 */ 19128 if (externalStorage && !isMounted && !isExternal(ps)) { 19129 continue; 19130 } 19131 19132 final AsecInstallArgs args = new AsecInstallArgs(cid, 19133 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19134 // The package status is changed only if the code path 19135 // matches between settings and the container id. 19136 if (ps.codePathString != null 19137 && ps.codePathString.startsWith(args.getCodePath())) { 19138 if (DEBUG_SD_INSTALL) { 19139 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19140 + " at code path: " + ps.codePathString); 19141 } 19142 19143 // We do have a valid package installed on sdcard 19144 processCids.put(args, ps.codePathString); 19145 final int uid = ps.appId; 19146 if (uid != -1) { 19147 uidArr = ArrayUtils.appendInt(uidArr, uid); 19148 } 19149 } else { 19150 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19151 + ps.codePathString); 19152 } 19153 } 19154 } 19155 19156 Arrays.sort(uidArr); 19157 } 19158 19159 // Process packages with valid entries. 19160 if (isMounted) { 19161 if (DEBUG_SD_INSTALL) 19162 Log.i(TAG, "Loading packages"); 19163 loadMediaPackages(processCids, uidArr, externalStorage); 19164 startCleaningPackages(); 19165 mInstallerService.onSecureContainersAvailable(); 19166 } else { 19167 if (DEBUG_SD_INSTALL) 19168 Log.i(TAG, "Unloading packages"); 19169 unloadMediaPackages(processCids, uidArr, reportStatus); 19170 } 19171 } 19172 19173 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19174 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19175 final int size = infos.size(); 19176 final String[] packageNames = new String[size]; 19177 final int[] packageUids = new int[size]; 19178 for (int i = 0; i < size; i++) { 19179 final ApplicationInfo info = infos.get(i); 19180 packageNames[i] = info.packageName; 19181 packageUids[i] = info.uid; 19182 } 19183 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19184 finishedReceiver); 19185 } 19186 19187 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19188 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19189 sendResourcesChangedBroadcast(mediaStatus, replacing, 19190 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19191 } 19192 19193 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19194 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19195 int size = pkgList.length; 19196 if (size > 0) { 19197 // Send broadcasts here 19198 Bundle extras = new Bundle(); 19199 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19200 if (uidArr != null) { 19201 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19202 } 19203 if (replacing) { 19204 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19205 } 19206 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19207 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19208 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19209 } 19210 } 19211 19212 /* 19213 * Look at potentially valid container ids from processCids If package 19214 * information doesn't match the one on record or package scanning fails, 19215 * the cid is added to list of removeCids. We currently don't delete stale 19216 * containers. 19217 */ 19218 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19219 boolean externalStorage) { 19220 ArrayList<String> pkgList = new ArrayList<String>(); 19221 Set<AsecInstallArgs> keys = processCids.keySet(); 19222 19223 for (AsecInstallArgs args : keys) { 19224 String codePath = processCids.get(args); 19225 if (DEBUG_SD_INSTALL) 19226 Log.i(TAG, "Loading container : " + args.cid); 19227 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19228 try { 19229 // Make sure there are no container errors first. 19230 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19231 Slog.e(TAG, "Failed to mount cid : " + args.cid 19232 + " when installing from sdcard"); 19233 continue; 19234 } 19235 // Check code path here. 19236 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19237 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19238 + " does not match one in settings " + codePath); 19239 continue; 19240 } 19241 // Parse package 19242 int parseFlags = mDefParseFlags; 19243 if (args.isExternalAsec()) { 19244 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19245 } 19246 if (args.isFwdLocked()) { 19247 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19248 } 19249 19250 synchronized (mInstallLock) { 19251 PackageParser.Package pkg = null; 19252 try { 19253 // Sadly we don't know the package name yet to freeze it 19254 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19255 SCAN_IGNORE_FROZEN, 0, null); 19256 } catch (PackageManagerException e) { 19257 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19258 } 19259 // Scan the package 19260 if (pkg != null) { 19261 /* 19262 * TODO why is the lock being held? doPostInstall is 19263 * called in other places without the lock. This needs 19264 * to be straightened out. 19265 */ 19266 // writer 19267 synchronized (mPackages) { 19268 retCode = PackageManager.INSTALL_SUCCEEDED; 19269 pkgList.add(pkg.packageName); 19270 // Post process args 19271 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19272 pkg.applicationInfo.uid); 19273 } 19274 } else { 19275 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19276 } 19277 } 19278 19279 } finally { 19280 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19281 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19282 } 19283 } 19284 } 19285 // writer 19286 synchronized (mPackages) { 19287 // If the platform SDK has changed since the last time we booted, 19288 // we need to re-grant app permission to catch any new ones that 19289 // appear. This is really a hack, and means that apps can in some 19290 // cases get permissions that the user didn't initially explicitly 19291 // allow... it would be nice to have some better way to handle 19292 // this situation. 19293 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19294 : mSettings.getInternalVersion(); 19295 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19296 : StorageManager.UUID_PRIVATE_INTERNAL; 19297 19298 int updateFlags = UPDATE_PERMISSIONS_ALL; 19299 if (ver.sdkVersion != mSdkVersion) { 19300 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19301 + mSdkVersion + "; regranting permissions for external"); 19302 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19303 } 19304 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19305 19306 // Yay, everything is now upgraded 19307 ver.forceCurrent(); 19308 19309 // can downgrade to reader 19310 // Persist settings 19311 mSettings.writeLPr(); 19312 } 19313 // Send a broadcast to let everyone know we are done processing 19314 if (pkgList.size() > 0) { 19315 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19316 } 19317 } 19318 19319 /* 19320 * Utility method to unload a list of specified containers 19321 */ 19322 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19323 // Just unmount all valid containers. 19324 for (AsecInstallArgs arg : cidArgs) { 19325 synchronized (mInstallLock) { 19326 arg.doPostDeleteLI(false); 19327 } 19328 } 19329 } 19330 19331 /* 19332 * Unload packages mounted on external media. This involves deleting package 19333 * data from internal structures, sending broadcasts about disabled packages, 19334 * gc'ing to free up references, unmounting all secure containers 19335 * corresponding to packages on external media, and posting a 19336 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19337 * that we always have to post this message if status has been requested no 19338 * matter what. 19339 */ 19340 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19341 final boolean reportStatus) { 19342 if (DEBUG_SD_INSTALL) 19343 Log.i(TAG, "unloading media packages"); 19344 ArrayList<String> pkgList = new ArrayList<String>(); 19345 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19346 final Set<AsecInstallArgs> keys = processCids.keySet(); 19347 for (AsecInstallArgs args : keys) { 19348 String pkgName = args.getPackageName(); 19349 if (DEBUG_SD_INSTALL) 19350 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19351 // Delete package internally 19352 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19353 synchronized (mInstallLock) { 19354 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19355 final boolean res; 19356 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19357 "unloadMediaPackages")) { 19358 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19359 null); 19360 } 19361 if (res) { 19362 pkgList.add(pkgName); 19363 } else { 19364 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19365 failedList.add(args); 19366 } 19367 } 19368 } 19369 19370 // reader 19371 synchronized (mPackages) { 19372 // We didn't update the settings after removing each package; 19373 // write them now for all packages. 19374 mSettings.writeLPr(); 19375 } 19376 19377 // We have to absolutely send UPDATED_MEDIA_STATUS only 19378 // after confirming that all the receivers processed the ordered 19379 // broadcast when packages get disabled, force a gc to clean things up. 19380 // and unload all the containers. 19381 if (pkgList.size() > 0) { 19382 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19383 new IIntentReceiver.Stub() { 19384 public void performReceive(Intent intent, int resultCode, String data, 19385 Bundle extras, boolean ordered, boolean sticky, 19386 int sendingUser) throws RemoteException { 19387 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19388 reportStatus ? 1 : 0, 1, keys); 19389 mHandler.sendMessage(msg); 19390 } 19391 }); 19392 } else { 19393 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19394 keys); 19395 mHandler.sendMessage(msg); 19396 } 19397 } 19398 19399 private void loadPrivatePackages(final VolumeInfo vol) { 19400 mHandler.post(new Runnable() { 19401 @Override 19402 public void run() { 19403 loadPrivatePackagesInner(vol); 19404 } 19405 }); 19406 } 19407 19408 private void loadPrivatePackagesInner(VolumeInfo vol) { 19409 final String volumeUuid = vol.fsUuid; 19410 if (TextUtils.isEmpty(volumeUuid)) { 19411 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19412 return; 19413 } 19414 19415 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19416 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19417 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19418 19419 final VersionInfo ver; 19420 final List<PackageSetting> packages; 19421 synchronized (mPackages) { 19422 ver = mSettings.findOrCreateVersion(volumeUuid); 19423 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19424 } 19425 19426 for (PackageSetting ps : packages) { 19427 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19428 synchronized (mInstallLock) { 19429 final PackageParser.Package pkg; 19430 try { 19431 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19432 loaded.add(pkg.applicationInfo); 19433 19434 } catch (PackageManagerException e) { 19435 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19436 } 19437 19438 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19439 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19440 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19441 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19442 } 19443 } 19444 } 19445 19446 // Reconcile app data for all started/unlocked users 19447 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19448 final UserManager um = mContext.getSystemService(UserManager.class); 19449 UserManagerInternal umInternal = getUserManagerInternal(); 19450 for (UserInfo user : um.getUsers()) { 19451 final int flags; 19452 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19453 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19454 } else if (umInternal.isUserRunning(user.id)) { 19455 flags = StorageManager.FLAG_STORAGE_DE; 19456 } else { 19457 continue; 19458 } 19459 19460 try { 19461 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19462 synchronized (mInstallLock) { 19463 reconcileAppsDataLI(volumeUuid, user.id, flags); 19464 } 19465 } catch (IllegalStateException e) { 19466 // Device was probably ejected, and we'll process that event momentarily 19467 Slog.w(TAG, "Failed to prepare storage: " + e); 19468 } 19469 } 19470 19471 synchronized (mPackages) { 19472 int updateFlags = UPDATE_PERMISSIONS_ALL; 19473 if (ver.sdkVersion != mSdkVersion) { 19474 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19475 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19476 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19477 } 19478 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19479 19480 // Yay, everything is now upgraded 19481 ver.forceCurrent(); 19482 19483 mSettings.writeLPr(); 19484 } 19485 19486 for (PackageFreezer freezer : freezers) { 19487 freezer.close(); 19488 } 19489 19490 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19491 sendResourcesChangedBroadcast(true, false, loaded, null); 19492 } 19493 19494 private void unloadPrivatePackages(final VolumeInfo vol) { 19495 mHandler.post(new Runnable() { 19496 @Override 19497 public void run() { 19498 unloadPrivatePackagesInner(vol); 19499 } 19500 }); 19501 } 19502 19503 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19504 final String volumeUuid = vol.fsUuid; 19505 if (TextUtils.isEmpty(volumeUuid)) { 19506 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19507 return; 19508 } 19509 19510 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19511 synchronized (mInstallLock) { 19512 synchronized (mPackages) { 19513 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19514 for (PackageSetting ps : packages) { 19515 if (ps.pkg == null) continue; 19516 19517 final ApplicationInfo info = ps.pkg.applicationInfo; 19518 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19519 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19520 19521 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19522 "unloadPrivatePackagesInner")) { 19523 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19524 false, null)) { 19525 unloaded.add(info); 19526 } else { 19527 Slog.w(TAG, "Failed to unload " + ps.codePath); 19528 } 19529 } 19530 19531 // Try very hard to release any references to this package 19532 // so we don't risk the system server being killed due to 19533 // open FDs 19534 AttributeCache.instance().removePackage(ps.name); 19535 } 19536 19537 mSettings.writeLPr(); 19538 } 19539 } 19540 19541 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19542 sendResourcesChangedBroadcast(false, false, unloaded, null); 19543 19544 // Try very hard to release any references to this path so we don't risk 19545 // the system server being killed due to open FDs 19546 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19547 19548 for (int i = 0; i < 3; i++) { 19549 System.gc(); 19550 System.runFinalization(); 19551 } 19552 } 19553 19554 /** 19555 * Prepare storage areas for given user on all mounted devices. 19556 */ 19557 void prepareUserData(int userId, int userSerial, int flags) { 19558 synchronized (mInstallLock) { 19559 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19560 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19561 final String volumeUuid = vol.getFsUuid(); 19562 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19563 } 19564 } 19565 } 19566 19567 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19568 boolean allowRecover) { 19569 // Prepare storage and verify that serial numbers are consistent; if 19570 // there's a mismatch we need to destroy to avoid leaking data 19571 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19572 try { 19573 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19574 19575 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19576 UserManagerService.enforceSerialNumber( 19577 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19578 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19579 UserManagerService.enforceSerialNumber( 19580 Environment.getDataSystemDeDirectory(userId), userSerial); 19581 } 19582 } 19583 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19584 UserManagerService.enforceSerialNumber( 19585 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19586 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19587 UserManagerService.enforceSerialNumber( 19588 Environment.getDataSystemCeDirectory(userId), userSerial); 19589 } 19590 } 19591 19592 synchronized (mInstallLock) { 19593 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19594 } 19595 } catch (Exception e) { 19596 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19597 + " because we failed to prepare: " + e); 19598 destroyUserDataLI(volumeUuid, userId, 19599 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19600 19601 if (allowRecover) { 19602 // Try one last time; if we fail again we're really in trouble 19603 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19604 } 19605 } 19606 } 19607 19608 /** 19609 * Destroy storage areas for given user on all mounted devices. 19610 */ 19611 void destroyUserData(int userId, int flags) { 19612 synchronized (mInstallLock) { 19613 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19614 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19615 final String volumeUuid = vol.getFsUuid(); 19616 destroyUserDataLI(volumeUuid, userId, flags); 19617 } 19618 } 19619 } 19620 19621 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19622 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19623 try { 19624 // Clean up app data, profile data, and media data 19625 mInstaller.destroyUserData(volumeUuid, userId, flags); 19626 19627 // Clean up system data 19628 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19629 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19630 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19631 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19632 } 19633 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19634 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19635 } 19636 } 19637 19638 // Data with special labels is now gone, so finish the job 19639 storage.destroyUserStorage(volumeUuid, userId, flags); 19640 19641 } catch (Exception e) { 19642 logCriticalInfo(Log.WARN, 19643 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19644 } 19645 } 19646 19647 /** 19648 * Examine all users present on given mounted volume, and destroy data 19649 * belonging to users that are no longer valid, or whose user ID has been 19650 * recycled. 19651 */ 19652 private void reconcileUsers(String volumeUuid) { 19653 final List<File> files = new ArrayList<>(); 19654 Collections.addAll(files, FileUtils 19655 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19656 Collections.addAll(files, FileUtils 19657 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19658 Collections.addAll(files, FileUtils 19659 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19660 Collections.addAll(files, FileUtils 19661 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19662 for (File file : files) { 19663 if (!file.isDirectory()) continue; 19664 19665 final int userId; 19666 final UserInfo info; 19667 try { 19668 userId = Integer.parseInt(file.getName()); 19669 info = sUserManager.getUserInfo(userId); 19670 } catch (NumberFormatException e) { 19671 Slog.w(TAG, "Invalid user directory " + file); 19672 continue; 19673 } 19674 19675 boolean destroyUser = false; 19676 if (info == null) { 19677 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19678 + " because no matching user was found"); 19679 destroyUser = true; 19680 } else if (!mOnlyCore) { 19681 try { 19682 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19683 } catch (IOException e) { 19684 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19685 + " because we failed to enforce serial number: " + e); 19686 destroyUser = true; 19687 } 19688 } 19689 19690 if (destroyUser) { 19691 synchronized (mInstallLock) { 19692 destroyUserDataLI(volumeUuid, userId, 19693 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19694 } 19695 } 19696 } 19697 } 19698 19699 private void assertPackageKnown(String volumeUuid, String packageName) 19700 throws PackageManagerException { 19701 synchronized (mPackages) { 19702 final PackageSetting ps = mSettings.mPackages.get(packageName); 19703 if (ps == null) { 19704 throw new PackageManagerException("Package " + packageName + " is unknown"); 19705 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19706 throw new PackageManagerException( 19707 "Package " + packageName + " found on unknown volume " + volumeUuid 19708 + "; expected volume " + ps.volumeUuid); 19709 } 19710 } 19711 } 19712 19713 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19714 throws PackageManagerException { 19715 synchronized (mPackages) { 19716 final PackageSetting ps = mSettings.mPackages.get(packageName); 19717 if (ps == null) { 19718 throw new PackageManagerException("Package " + packageName + " is unknown"); 19719 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19720 throw new PackageManagerException( 19721 "Package " + packageName + " found on unknown volume " + volumeUuid 19722 + "; expected volume " + ps.volumeUuid); 19723 } else if (!ps.getInstalled(userId)) { 19724 throw new PackageManagerException( 19725 "Package " + packageName + " not installed for user " + userId); 19726 } 19727 } 19728 } 19729 19730 /** 19731 * Examine all apps present on given mounted volume, and destroy apps that 19732 * aren't expected, either due to uninstallation or reinstallation on 19733 * another volume. 19734 */ 19735 private void reconcileApps(String volumeUuid) { 19736 final File[] files = FileUtils 19737 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19738 for (File file : files) { 19739 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19740 && !PackageInstallerService.isStageName(file.getName()); 19741 if (!isPackage) { 19742 // Ignore entries which are not packages 19743 continue; 19744 } 19745 19746 try { 19747 final PackageLite pkg = PackageParser.parsePackageLite(file, 19748 PackageParser.PARSE_MUST_BE_APK); 19749 assertPackageKnown(volumeUuid, pkg.packageName); 19750 19751 } catch (PackageParserException | PackageManagerException e) { 19752 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19753 synchronized (mInstallLock) { 19754 removeCodePathLI(file); 19755 } 19756 } 19757 } 19758 } 19759 19760 /** 19761 * Reconcile all app data for the given user. 19762 * <p> 19763 * Verifies that directories exist and that ownership and labeling is 19764 * correct for all installed apps on all mounted volumes. 19765 */ 19766 void reconcileAppsData(int userId, int flags) { 19767 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19768 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19769 final String volumeUuid = vol.getFsUuid(); 19770 synchronized (mInstallLock) { 19771 reconcileAppsDataLI(volumeUuid, userId, flags); 19772 } 19773 } 19774 } 19775 19776 /** 19777 * Reconcile all app data on given mounted volume. 19778 * <p> 19779 * Destroys app data that isn't expected, either due to uninstallation or 19780 * reinstallation on another volume. 19781 * <p> 19782 * Verifies that directories exist and that ownership and labeling is 19783 * correct for all installed apps. 19784 */ 19785 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19786 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19787 + Integer.toHexString(flags)); 19788 19789 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19790 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19791 19792 // First look for stale data that doesn't belong, and check if things 19793 // have changed since we did our last restorecon 19794 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19795 if (StorageManager.isFileEncryptedNativeOrEmulated() 19796 && !StorageManager.isUserKeyUnlocked(userId)) { 19797 throw new RuntimeException( 19798 "Yikes, someone asked us to reconcile CE storage while " + userId 19799 + " was still locked; this would have caused massive data loss!"); 19800 } 19801 19802 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19803 for (File file : files) { 19804 final String packageName = file.getName(); 19805 try { 19806 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19807 } catch (PackageManagerException e) { 19808 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19809 try { 19810 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19811 StorageManager.FLAG_STORAGE_CE, 0); 19812 } catch (InstallerException e2) { 19813 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19814 } 19815 } 19816 } 19817 } 19818 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19819 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19820 for (File file : files) { 19821 final String packageName = file.getName(); 19822 try { 19823 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19824 } catch (PackageManagerException e) { 19825 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19826 try { 19827 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19828 StorageManager.FLAG_STORAGE_DE, 0); 19829 } catch (InstallerException e2) { 19830 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19831 } 19832 } 19833 } 19834 } 19835 19836 // Ensure that data directories are ready to roll for all packages 19837 // installed for this volume and user 19838 final List<PackageSetting> packages; 19839 synchronized (mPackages) { 19840 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19841 } 19842 int preparedCount = 0; 19843 for (PackageSetting ps : packages) { 19844 final String packageName = ps.name; 19845 if (ps.pkg == null) { 19846 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19847 // TODO: might be due to legacy ASEC apps; we should circle back 19848 // and reconcile again once they're scanned 19849 continue; 19850 } 19851 19852 if (ps.getInstalled(userId)) { 19853 prepareAppDataLIF(ps.pkg, userId, flags); 19854 19855 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19856 // We may have just shuffled around app data directories, so 19857 // prepare them one more time 19858 prepareAppDataLIF(ps.pkg, userId, flags); 19859 } 19860 19861 preparedCount++; 19862 } 19863 } 19864 19865 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 19866 } 19867 19868 /** 19869 * Prepare app data for the given app just after it was installed or 19870 * upgraded. This method carefully only touches users that it's installed 19871 * for, and it forces a restorecon to handle any seinfo changes. 19872 * <p> 19873 * Verifies that directories exist and that ownership and labeling is 19874 * correct for all installed apps. If there is an ownership mismatch, it 19875 * will try recovering system apps by wiping data; third-party app data is 19876 * left intact. 19877 * <p> 19878 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19879 */ 19880 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19881 final PackageSetting ps; 19882 synchronized (mPackages) { 19883 ps = mSettings.mPackages.get(pkg.packageName); 19884 mSettings.writeKernelMappingLPr(ps); 19885 } 19886 19887 final UserManager um = mContext.getSystemService(UserManager.class); 19888 UserManagerInternal umInternal = getUserManagerInternal(); 19889 for (UserInfo user : um.getUsers()) { 19890 final int flags; 19891 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19892 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19893 } else if (umInternal.isUserRunning(user.id)) { 19894 flags = StorageManager.FLAG_STORAGE_DE; 19895 } else { 19896 continue; 19897 } 19898 19899 if (ps.getInstalled(user.id)) { 19900 // TODO: when user data is locked, mark that we're still dirty 19901 prepareAppDataLIF(pkg, user.id, flags); 19902 } 19903 } 19904 } 19905 19906 /** 19907 * Prepare app data for the given app. 19908 * <p> 19909 * Verifies that directories exist and that ownership and labeling is 19910 * correct for all installed apps. If there is an ownership mismatch, this 19911 * will try recovering system apps by wiping data; third-party app data is 19912 * left intact. 19913 */ 19914 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 19915 if (pkg == null) { 19916 Slog.wtf(TAG, "Package was null!", new Throwable()); 19917 return; 19918 } 19919 prepareAppDataLeafLIF(pkg, userId, flags); 19920 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19921 for (int i = 0; i < childCount; i++) { 19922 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 19923 } 19924 } 19925 19926 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19927 if (DEBUG_APP_DATA) { 19928 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19929 + Integer.toHexString(flags)); 19930 } 19931 19932 final String volumeUuid = pkg.volumeUuid; 19933 final String packageName = pkg.packageName; 19934 final ApplicationInfo app = pkg.applicationInfo; 19935 final int appId = UserHandle.getAppId(app.uid); 19936 19937 Preconditions.checkNotNull(app.seinfo); 19938 19939 long ceDataInode = -1; 19940 try { 19941 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19942 appId, app.seinfo, app.targetSdkVersion); 19943 } catch (InstallerException e) { 19944 if (app.isSystemApp()) { 19945 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19946 + ", but trying to recover: " + e); 19947 destroyAppDataLeafLIF(pkg, userId, flags); 19948 try { 19949 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19950 appId, app.seinfo, app.targetSdkVersion); 19951 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19952 } catch (InstallerException e2) { 19953 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19954 } 19955 } else { 19956 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19957 } 19958 } 19959 19960 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 19961 // TODO: mark this structure as dirty so we persist it! 19962 synchronized (mPackages) { 19963 final PackageSetting ps = mSettings.mPackages.get(packageName); 19964 if (ps != null) { 19965 ps.setCeDataInode(ceDataInode, userId); 19966 } 19967 } 19968 } 19969 19970 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19971 } 19972 19973 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19974 if (pkg == null) { 19975 Slog.wtf(TAG, "Package was null!", new Throwable()); 19976 return; 19977 } 19978 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19979 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19980 for (int i = 0; i < childCount; i++) { 19981 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19982 } 19983 } 19984 19985 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19986 final String volumeUuid = pkg.volumeUuid; 19987 final String packageName = pkg.packageName; 19988 final ApplicationInfo app = pkg.applicationInfo; 19989 19990 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19991 // Create a native library symlink only if we have native libraries 19992 // and if the native libraries are 32 bit libraries. We do not provide 19993 // this symlink for 64 bit libraries. 19994 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19995 final String nativeLibPath = app.nativeLibraryDir; 19996 try { 19997 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19998 nativeLibPath, userId); 19999 } catch (InstallerException e) { 20000 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20001 } 20002 } 20003 } 20004 } 20005 20006 /** 20007 * For system apps on non-FBE devices, this method migrates any existing 20008 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20009 * requested by the app. 20010 */ 20011 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20012 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20013 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20014 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20015 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20016 try { 20017 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20018 storageTarget); 20019 } catch (InstallerException e) { 20020 logCriticalInfo(Log.WARN, 20021 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20022 } 20023 return true; 20024 } else { 20025 return false; 20026 } 20027 } 20028 20029 public PackageFreezer freezePackage(String packageName, String killReason) { 20030 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20031 } 20032 20033 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20034 return new PackageFreezer(packageName, userId, killReason); 20035 } 20036 20037 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20038 String killReason) { 20039 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20040 } 20041 20042 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20043 String killReason) { 20044 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20045 return new PackageFreezer(); 20046 } else { 20047 return freezePackage(packageName, userId, killReason); 20048 } 20049 } 20050 20051 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20052 String killReason) { 20053 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20054 } 20055 20056 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20057 String killReason) { 20058 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20059 return new PackageFreezer(); 20060 } else { 20061 return freezePackage(packageName, userId, killReason); 20062 } 20063 } 20064 20065 /** 20066 * Class that freezes and kills the given package upon creation, and 20067 * unfreezes it upon closing. This is typically used when doing surgery on 20068 * app code/data to prevent the app from running while you're working. 20069 */ 20070 private class PackageFreezer implements AutoCloseable { 20071 private final String mPackageName; 20072 private final PackageFreezer[] mChildren; 20073 20074 private final boolean mWeFroze; 20075 20076 private final AtomicBoolean mClosed = new AtomicBoolean(); 20077 private final CloseGuard mCloseGuard = CloseGuard.get(); 20078 20079 /** 20080 * Create and return a stub freezer that doesn't actually do anything, 20081 * typically used when someone requested 20082 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20083 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20084 */ 20085 public PackageFreezer() { 20086 mPackageName = null; 20087 mChildren = null; 20088 mWeFroze = false; 20089 mCloseGuard.open("close"); 20090 } 20091 20092 public PackageFreezer(String packageName, int userId, String killReason) { 20093 synchronized (mPackages) { 20094 mPackageName = packageName; 20095 mWeFroze = mFrozenPackages.add(mPackageName); 20096 20097 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20098 if (ps != null) { 20099 killApplication(ps.name, ps.appId, userId, killReason); 20100 } 20101 20102 final PackageParser.Package p = mPackages.get(packageName); 20103 if (p != null && p.childPackages != null) { 20104 final int N = p.childPackages.size(); 20105 mChildren = new PackageFreezer[N]; 20106 for (int i = 0; i < N; i++) { 20107 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20108 userId, killReason); 20109 } 20110 } else { 20111 mChildren = null; 20112 } 20113 } 20114 mCloseGuard.open("close"); 20115 } 20116 20117 @Override 20118 protected void finalize() throws Throwable { 20119 try { 20120 mCloseGuard.warnIfOpen(); 20121 close(); 20122 } finally { 20123 super.finalize(); 20124 } 20125 } 20126 20127 @Override 20128 public void close() { 20129 mCloseGuard.close(); 20130 if (mClosed.compareAndSet(false, true)) { 20131 synchronized (mPackages) { 20132 if (mWeFroze) { 20133 mFrozenPackages.remove(mPackageName); 20134 } 20135 20136 if (mChildren != null) { 20137 for (PackageFreezer freezer : mChildren) { 20138 freezer.close(); 20139 } 20140 } 20141 } 20142 } 20143 } 20144 } 20145 20146 /** 20147 * Verify that given package is currently frozen. 20148 */ 20149 private void checkPackageFrozen(String packageName) { 20150 synchronized (mPackages) { 20151 if (!mFrozenPackages.contains(packageName)) { 20152 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20153 } 20154 } 20155 } 20156 20157 @Override 20158 public int movePackage(final String packageName, final String volumeUuid) { 20159 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20160 20161 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20162 final int moveId = mNextMoveId.getAndIncrement(); 20163 mHandler.post(new Runnable() { 20164 @Override 20165 public void run() { 20166 try { 20167 movePackageInternal(packageName, volumeUuid, moveId, user); 20168 } catch (PackageManagerException e) { 20169 Slog.w(TAG, "Failed to move " + packageName, e); 20170 mMoveCallbacks.notifyStatusChanged(moveId, 20171 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20172 } 20173 } 20174 }); 20175 return moveId; 20176 } 20177 20178 private void movePackageInternal(final String packageName, final String volumeUuid, 20179 final int moveId, UserHandle user) throws PackageManagerException { 20180 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20181 final PackageManager pm = mContext.getPackageManager(); 20182 20183 final boolean currentAsec; 20184 final String currentVolumeUuid; 20185 final File codeFile; 20186 final String installerPackageName; 20187 final String packageAbiOverride; 20188 final int appId; 20189 final String seinfo; 20190 final String label; 20191 final int targetSdkVersion; 20192 final PackageFreezer freezer; 20193 final int[] installedUserIds; 20194 20195 // reader 20196 synchronized (mPackages) { 20197 final PackageParser.Package pkg = mPackages.get(packageName); 20198 final PackageSetting ps = mSettings.mPackages.get(packageName); 20199 if (pkg == null || ps == null) { 20200 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20201 } 20202 20203 if (pkg.applicationInfo.isSystemApp()) { 20204 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20205 "Cannot move system application"); 20206 } 20207 20208 if (pkg.applicationInfo.isExternalAsec()) { 20209 currentAsec = true; 20210 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20211 } else if (pkg.applicationInfo.isForwardLocked()) { 20212 currentAsec = true; 20213 currentVolumeUuid = "forward_locked"; 20214 } else { 20215 currentAsec = false; 20216 currentVolumeUuid = ps.volumeUuid; 20217 20218 final File probe = new File(pkg.codePath); 20219 final File probeOat = new File(probe, "oat"); 20220 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20221 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20222 "Move only supported for modern cluster style installs"); 20223 } 20224 } 20225 20226 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20227 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20228 "Package already moved to " + volumeUuid); 20229 } 20230 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20231 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20232 "Device admin cannot be moved"); 20233 } 20234 20235 if (mFrozenPackages.contains(packageName)) { 20236 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20237 "Failed to move already frozen package"); 20238 } 20239 20240 codeFile = new File(pkg.codePath); 20241 installerPackageName = ps.installerPackageName; 20242 packageAbiOverride = ps.cpuAbiOverrideString; 20243 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20244 seinfo = pkg.applicationInfo.seinfo; 20245 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20246 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20247 freezer = freezePackage(packageName, "movePackageInternal"); 20248 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20249 } 20250 20251 final Bundle extras = new Bundle(); 20252 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20253 extras.putString(Intent.EXTRA_TITLE, label); 20254 mMoveCallbacks.notifyCreated(moveId, extras); 20255 20256 int installFlags; 20257 final boolean moveCompleteApp; 20258 final File measurePath; 20259 20260 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20261 installFlags = INSTALL_INTERNAL; 20262 moveCompleteApp = !currentAsec; 20263 measurePath = Environment.getDataAppDirectory(volumeUuid); 20264 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20265 installFlags = INSTALL_EXTERNAL; 20266 moveCompleteApp = false; 20267 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20268 } else { 20269 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20270 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20271 || !volume.isMountedWritable()) { 20272 freezer.close(); 20273 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20274 "Move location not mounted private volume"); 20275 } 20276 20277 Preconditions.checkState(!currentAsec); 20278 20279 installFlags = INSTALL_INTERNAL; 20280 moveCompleteApp = true; 20281 measurePath = Environment.getDataAppDirectory(volumeUuid); 20282 } 20283 20284 final PackageStats stats = new PackageStats(null, -1); 20285 synchronized (mInstaller) { 20286 for (int userId : installedUserIds) { 20287 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20288 freezer.close(); 20289 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20290 "Failed to measure package size"); 20291 } 20292 } 20293 } 20294 20295 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20296 + stats.dataSize); 20297 20298 final long startFreeBytes = measurePath.getFreeSpace(); 20299 final long sizeBytes; 20300 if (moveCompleteApp) { 20301 sizeBytes = stats.codeSize + stats.dataSize; 20302 } else { 20303 sizeBytes = stats.codeSize; 20304 } 20305 20306 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20307 freezer.close(); 20308 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20309 "Not enough free space to move"); 20310 } 20311 20312 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20313 20314 final CountDownLatch installedLatch = new CountDownLatch(1); 20315 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20316 @Override 20317 public void onUserActionRequired(Intent intent) throws RemoteException { 20318 throw new IllegalStateException(); 20319 } 20320 20321 @Override 20322 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20323 Bundle extras) throws RemoteException { 20324 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20325 + PackageManager.installStatusToString(returnCode, msg)); 20326 20327 installedLatch.countDown(); 20328 freezer.close(); 20329 20330 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20331 switch (status) { 20332 case PackageInstaller.STATUS_SUCCESS: 20333 mMoveCallbacks.notifyStatusChanged(moveId, 20334 PackageManager.MOVE_SUCCEEDED); 20335 break; 20336 case PackageInstaller.STATUS_FAILURE_STORAGE: 20337 mMoveCallbacks.notifyStatusChanged(moveId, 20338 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20339 break; 20340 default: 20341 mMoveCallbacks.notifyStatusChanged(moveId, 20342 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20343 break; 20344 } 20345 } 20346 }; 20347 20348 final MoveInfo move; 20349 if (moveCompleteApp) { 20350 // Kick off a thread to report progress estimates 20351 new Thread() { 20352 @Override 20353 public void run() { 20354 while (true) { 20355 try { 20356 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20357 break; 20358 } 20359 } catch (InterruptedException ignored) { 20360 } 20361 20362 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20363 final int progress = 10 + (int) MathUtils.constrain( 20364 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20365 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20366 } 20367 } 20368 }.start(); 20369 20370 final String dataAppName = codeFile.getName(); 20371 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20372 dataAppName, appId, seinfo, targetSdkVersion); 20373 } else { 20374 move = null; 20375 } 20376 20377 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20378 20379 final Message msg = mHandler.obtainMessage(INIT_COPY); 20380 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20381 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20382 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20383 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20384 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20385 msg.obj = params; 20386 20387 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20388 System.identityHashCode(msg.obj)); 20389 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20390 System.identityHashCode(msg.obj)); 20391 20392 mHandler.sendMessage(msg); 20393 } 20394 20395 @Override 20396 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20397 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20398 20399 final int realMoveId = mNextMoveId.getAndIncrement(); 20400 final Bundle extras = new Bundle(); 20401 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20402 mMoveCallbacks.notifyCreated(realMoveId, extras); 20403 20404 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20405 @Override 20406 public void onCreated(int moveId, Bundle extras) { 20407 // Ignored 20408 } 20409 20410 @Override 20411 public void onStatusChanged(int moveId, int status, long estMillis) { 20412 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20413 } 20414 }; 20415 20416 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20417 storage.setPrimaryStorageUuid(volumeUuid, callback); 20418 return realMoveId; 20419 } 20420 20421 @Override 20422 public int getMoveStatus(int moveId) { 20423 mContext.enforceCallingOrSelfPermission( 20424 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20425 return mMoveCallbacks.mLastStatus.get(moveId); 20426 } 20427 20428 @Override 20429 public void registerMoveCallback(IPackageMoveObserver callback) { 20430 mContext.enforceCallingOrSelfPermission( 20431 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20432 mMoveCallbacks.register(callback); 20433 } 20434 20435 @Override 20436 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20437 mContext.enforceCallingOrSelfPermission( 20438 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20439 mMoveCallbacks.unregister(callback); 20440 } 20441 20442 @Override 20443 public boolean setInstallLocation(int loc) { 20444 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20445 null); 20446 if (getInstallLocation() == loc) { 20447 return true; 20448 } 20449 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20450 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20451 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20452 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20453 return true; 20454 } 20455 return false; 20456 } 20457 20458 @Override 20459 public int getInstallLocation() { 20460 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20461 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20462 PackageHelper.APP_INSTALL_AUTO); 20463 } 20464 20465 /** Called by UserManagerService */ 20466 void cleanUpUser(UserManagerService userManager, int userHandle) { 20467 synchronized (mPackages) { 20468 mDirtyUsers.remove(userHandle); 20469 mUserNeedsBadging.delete(userHandle); 20470 mSettings.removeUserLPw(userHandle); 20471 mPendingBroadcasts.remove(userHandle); 20472 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20473 removeUnusedPackagesLPw(userManager, userHandle); 20474 } 20475 } 20476 20477 /** 20478 * We're removing userHandle and would like to remove any downloaded packages 20479 * that are no longer in use by any other user. 20480 * @param userHandle the user being removed 20481 */ 20482 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20483 final boolean DEBUG_CLEAN_APKS = false; 20484 int [] users = userManager.getUserIds(); 20485 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20486 while (psit.hasNext()) { 20487 PackageSetting ps = psit.next(); 20488 if (ps.pkg == null) { 20489 continue; 20490 } 20491 final String packageName = ps.pkg.packageName; 20492 // Skip over if system app 20493 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20494 continue; 20495 } 20496 if (DEBUG_CLEAN_APKS) { 20497 Slog.i(TAG, "Checking package " + packageName); 20498 } 20499 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20500 if (keep) { 20501 if (DEBUG_CLEAN_APKS) { 20502 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20503 } 20504 } else { 20505 for (int i = 0; i < users.length; i++) { 20506 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20507 keep = true; 20508 if (DEBUG_CLEAN_APKS) { 20509 Slog.i(TAG, " Keeping package " + packageName + " for user " 20510 + users[i]); 20511 } 20512 break; 20513 } 20514 } 20515 } 20516 if (!keep) { 20517 if (DEBUG_CLEAN_APKS) { 20518 Slog.i(TAG, " Removing package " + packageName); 20519 } 20520 mHandler.post(new Runnable() { 20521 public void run() { 20522 deletePackageX(packageName, userHandle, 0); 20523 } //end run 20524 }); 20525 } 20526 } 20527 } 20528 20529 /** Called by UserManagerService */ 20530 void createNewUser(int userId) { 20531 synchronized (mInstallLock) { 20532 mSettings.createNewUserLI(this, mInstaller, userId); 20533 } 20534 synchronized (mPackages) { 20535 scheduleWritePackageRestrictionsLocked(userId); 20536 scheduleWritePackageListLocked(userId); 20537 applyFactoryDefaultBrowserLPw(userId); 20538 primeDomainVerificationsLPw(userId); 20539 } 20540 } 20541 20542 void onNewUserCreated(final int userId) { 20543 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20544 // If permission review for legacy apps is required, we represent 20545 // dagerous permissions for such apps as always granted runtime 20546 // permissions to keep per user flag state whether review is needed. 20547 // Hence, if a new user is added we have to propagate dangerous 20548 // permission grants for these legacy apps. 20549 if (mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) { 20550 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20551 | UPDATE_PERMISSIONS_REPLACE_ALL); 20552 } 20553 } 20554 20555 @Override 20556 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20557 mContext.enforceCallingOrSelfPermission( 20558 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20559 "Only package verification agents can read the verifier device identity"); 20560 20561 synchronized (mPackages) { 20562 return mSettings.getVerifierDeviceIdentityLPw(); 20563 } 20564 } 20565 20566 @Override 20567 public void setPermissionEnforced(String permission, boolean enforced) { 20568 // TODO: Now that we no longer change GID for storage, this should to away. 20569 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20570 "setPermissionEnforced"); 20571 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20572 synchronized (mPackages) { 20573 if (mSettings.mReadExternalStorageEnforced == null 20574 || mSettings.mReadExternalStorageEnforced != enforced) { 20575 mSettings.mReadExternalStorageEnforced = enforced; 20576 mSettings.writeLPr(); 20577 } 20578 } 20579 // kill any non-foreground processes so we restart them and 20580 // grant/revoke the GID. 20581 final IActivityManager am = ActivityManagerNative.getDefault(); 20582 if (am != null) { 20583 final long token = Binder.clearCallingIdentity(); 20584 try { 20585 am.killProcessesBelowForeground("setPermissionEnforcement"); 20586 } catch (RemoteException e) { 20587 } finally { 20588 Binder.restoreCallingIdentity(token); 20589 } 20590 } 20591 } else { 20592 throw new IllegalArgumentException("No selective enforcement for " + permission); 20593 } 20594 } 20595 20596 @Override 20597 @Deprecated 20598 public boolean isPermissionEnforced(String permission) { 20599 return true; 20600 } 20601 20602 @Override 20603 public boolean isStorageLow() { 20604 final long token = Binder.clearCallingIdentity(); 20605 try { 20606 final DeviceStorageMonitorInternal 20607 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20608 if (dsm != null) { 20609 return dsm.isMemoryLow(); 20610 } else { 20611 return false; 20612 } 20613 } finally { 20614 Binder.restoreCallingIdentity(token); 20615 } 20616 } 20617 20618 @Override 20619 public IPackageInstaller getPackageInstaller() { 20620 return mInstallerService; 20621 } 20622 20623 private boolean userNeedsBadging(int userId) { 20624 int index = mUserNeedsBadging.indexOfKey(userId); 20625 if (index < 0) { 20626 final UserInfo userInfo; 20627 final long token = Binder.clearCallingIdentity(); 20628 try { 20629 userInfo = sUserManager.getUserInfo(userId); 20630 } finally { 20631 Binder.restoreCallingIdentity(token); 20632 } 20633 final boolean b; 20634 if (userInfo != null && userInfo.isManagedProfile()) { 20635 b = true; 20636 } else { 20637 b = false; 20638 } 20639 mUserNeedsBadging.put(userId, b); 20640 return b; 20641 } 20642 return mUserNeedsBadging.valueAt(index); 20643 } 20644 20645 @Override 20646 public KeySet getKeySetByAlias(String packageName, String alias) { 20647 if (packageName == null || alias == null) { 20648 return null; 20649 } 20650 synchronized(mPackages) { 20651 final PackageParser.Package pkg = mPackages.get(packageName); 20652 if (pkg == null) { 20653 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20654 throw new IllegalArgumentException("Unknown package: " + packageName); 20655 } 20656 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20657 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20658 } 20659 } 20660 20661 @Override 20662 public KeySet getSigningKeySet(String packageName) { 20663 if (packageName == null) { 20664 return null; 20665 } 20666 synchronized(mPackages) { 20667 final PackageParser.Package pkg = mPackages.get(packageName); 20668 if (pkg == null) { 20669 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20670 throw new IllegalArgumentException("Unknown package: " + packageName); 20671 } 20672 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20673 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20674 throw new SecurityException("May not access signing KeySet of other apps."); 20675 } 20676 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20677 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20678 } 20679 } 20680 20681 @Override 20682 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20683 if (packageName == null || ks == null) { 20684 return false; 20685 } 20686 synchronized(mPackages) { 20687 final PackageParser.Package pkg = mPackages.get(packageName); 20688 if (pkg == null) { 20689 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20690 throw new IllegalArgumentException("Unknown package: " + packageName); 20691 } 20692 IBinder ksh = ks.getToken(); 20693 if (ksh instanceof KeySetHandle) { 20694 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20695 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20696 } 20697 return false; 20698 } 20699 } 20700 20701 @Override 20702 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20703 if (packageName == null || ks == null) { 20704 return false; 20705 } 20706 synchronized(mPackages) { 20707 final PackageParser.Package pkg = mPackages.get(packageName); 20708 if (pkg == null) { 20709 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20710 throw new IllegalArgumentException("Unknown package: " + packageName); 20711 } 20712 IBinder ksh = ks.getToken(); 20713 if (ksh instanceof KeySetHandle) { 20714 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20715 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20716 } 20717 return false; 20718 } 20719 } 20720 20721 private void deletePackageIfUnusedLPr(final String packageName) { 20722 PackageSetting ps = mSettings.mPackages.get(packageName); 20723 if (ps == null) { 20724 return; 20725 } 20726 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20727 // TODO Implement atomic delete if package is unused 20728 // It is currently possible that the package will be deleted even if it is installed 20729 // after this method returns. 20730 mHandler.post(new Runnable() { 20731 public void run() { 20732 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20733 } 20734 }); 20735 } 20736 } 20737 20738 /** 20739 * Check and throw if the given before/after packages would be considered a 20740 * downgrade. 20741 */ 20742 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20743 throws PackageManagerException { 20744 if (after.versionCode < before.mVersionCode) { 20745 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20746 "Update version code " + after.versionCode + " is older than current " 20747 + before.mVersionCode); 20748 } else if (after.versionCode == before.mVersionCode) { 20749 if (after.baseRevisionCode < before.baseRevisionCode) { 20750 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20751 "Update base revision code " + after.baseRevisionCode 20752 + " is older than current " + before.baseRevisionCode); 20753 } 20754 20755 if (!ArrayUtils.isEmpty(after.splitNames)) { 20756 for (int i = 0; i < after.splitNames.length; i++) { 20757 final String splitName = after.splitNames[i]; 20758 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20759 if (j != -1) { 20760 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20761 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20762 "Update split " + splitName + " revision code " 20763 + after.splitRevisionCodes[i] + " is older than current " 20764 + before.splitRevisionCodes[j]); 20765 } 20766 } 20767 } 20768 } 20769 } 20770 } 20771 20772 private static class MoveCallbacks extends Handler { 20773 private static final int MSG_CREATED = 1; 20774 private static final int MSG_STATUS_CHANGED = 2; 20775 20776 private final RemoteCallbackList<IPackageMoveObserver> 20777 mCallbacks = new RemoteCallbackList<>(); 20778 20779 private final SparseIntArray mLastStatus = new SparseIntArray(); 20780 20781 public MoveCallbacks(Looper looper) { 20782 super(looper); 20783 } 20784 20785 public void register(IPackageMoveObserver callback) { 20786 mCallbacks.register(callback); 20787 } 20788 20789 public void unregister(IPackageMoveObserver callback) { 20790 mCallbacks.unregister(callback); 20791 } 20792 20793 @Override 20794 public void handleMessage(Message msg) { 20795 final SomeArgs args = (SomeArgs) msg.obj; 20796 final int n = mCallbacks.beginBroadcast(); 20797 for (int i = 0; i < n; i++) { 20798 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20799 try { 20800 invokeCallback(callback, msg.what, args); 20801 } catch (RemoteException ignored) { 20802 } 20803 } 20804 mCallbacks.finishBroadcast(); 20805 args.recycle(); 20806 } 20807 20808 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20809 throws RemoteException { 20810 switch (what) { 20811 case MSG_CREATED: { 20812 callback.onCreated(args.argi1, (Bundle) args.arg2); 20813 break; 20814 } 20815 case MSG_STATUS_CHANGED: { 20816 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20817 break; 20818 } 20819 } 20820 } 20821 20822 private void notifyCreated(int moveId, Bundle extras) { 20823 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20824 20825 final SomeArgs args = SomeArgs.obtain(); 20826 args.argi1 = moveId; 20827 args.arg2 = extras; 20828 obtainMessage(MSG_CREATED, args).sendToTarget(); 20829 } 20830 20831 private void notifyStatusChanged(int moveId, int status) { 20832 notifyStatusChanged(moveId, status, -1); 20833 } 20834 20835 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20836 Slog.v(TAG, "Move " + moveId + " status " + status); 20837 20838 final SomeArgs args = SomeArgs.obtain(); 20839 args.argi1 = moveId; 20840 args.argi2 = status; 20841 args.arg3 = estMillis; 20842 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20843 20844 synchronized (mLastStatus) { 20845 mLastStatus.put(moveId, status); 20846 } 20847 } 20848 } 20849 20850 private final static class OnPermissionChangeListeners extends Handler { 20851 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20852 20853 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20854 new RemoteCallbackList<>(); 20855 20856 public OnPermissionChangeListeners(Looper looper) { 20857 super(looper); 20858 } 20859 20860 @Override 20861 public void handleMessage(Message msg) { 20862 switch (msg.what) { 20863 case MSG_ON_PERMISSIONS_CHANGED: { 20864 final int uid = msg.arg1; 20865 handleOnPermissionsChanged(uid); 20866 } break; 20867 } 20868 } 20869 20870 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20871 mPermissionListeners.register(listener); 20872 20873 } 20874 20875 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20876 mPermissionListeners.unregister(listener); 20877 } 20878 20879 public void onPermissionsChanged(int uid) { 20880 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20881 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20882 } 20883 } 20884 20885 private void handleOnPermissionsChanged(int uid) { 20886 final int count = mPermissionListeners.beginBroadcast(); 20887 try { 20888 for (int i = 0; i < count; i++) { 20889 IOnPermissionsChangeListener callback = mPermissionListeners 20890 .getBroadcastItem(i); 20891 try { 20892 callback.onPermissionsChanged(uid); 20893 } catch (RemoteException e) { 20894 Log.e(TAG, "Permission listener is dead", e); 20895 } 20896 } 20897 } finally { 20898 mPermissionListeners.finishBroadcast(); 20899 } 20900 } 20901 } 20902 20903 private class PackageManagerInternalImpl extends PackageManagerInternal { 20904 @Override 20905 public void setLocationPackagesProvider(PackagesProvider provider) { 20906 synchronized (mPackages) { 20907 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20908 } 20909 } 20910 20911 @Override 20912 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20913 synchronized (mPackages) { 20914 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20915 } 20916 } 20917 20918 @Override 20919 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20920 synchronized (mPackages) { 20921 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20922 } 20923 } 20924 20925 @Override 20926 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20927 synchronized (mPackages) { 20928 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20929 } 20930 } 20931 20932 @Override 20933 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20934 synchronized (mPackages) { 20935 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20936 } 20937 } 20938 20939 @Override 20940 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20941 synchronized (mPackages) { 20942 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20943 } 20944 } 20945 20946 @Override 20947 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20948 synchronized (mPackages) { 20949 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20950 packageName, userId); 20951 } 20952 } 20953 20954 @Override 20955 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20956 synchronized (mPackages) { 20957 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20958 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20959 packageName, userId); 20960 } 20961 } 20962 20963 @Override 20964 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20965 synchronized (mPackages) { 20966 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20967 packageName, userId); 20968 } 20969 } 20970 20971 @Override 20972 public void setKeepUninstalledPackages(final List<String> packageList) { 20973 Preconditions.checkNotNull(packageList); 20974 List<String> removedFromList = null; 20975 synchronized (mPackages) { 20976 if (mKeepUninstalledPackages != null) { 20977 final int packagesCount = mKeepUninstalledPackages.size(); 20978 for (int i = 0; i < packagesCount; i++) { 20979 String oldPackage = mKeepUninstalledPackages.get(i); 20980 if (packageList != null && packageList.contains(oldPackage)) { 20981 continue; 20982 } 20983 if (removedFromList == null) { 20984 removedFromList = new ArrayList<>(); 20985 } 20986 removedFromList.add(oldPackage); 20987 } 20988 } 20989 mKeepUninstalledPackages = new ArrayList<>(packageList); 20990 if (removedFromList != null) { 20991 final int removedCount = removedFromList.size(); 20992 for (int i = 0; i < removedCount; i++) { 20993 deletePackageIfUnusedLPr(removedFromList.get(i)); 20994 } 20995 } 20996 } 20997 } 20998 20999 @Override 21000 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21001 synchronized (mPackages) { 21002 // If we do not support permission review, done. 21003 if (!mPermissionReviewRequired && !Build.PERMISSIONS_REVIEW_REQUIRED) { 21004 return false; 21005 } 21006 21007 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21008 if (packageSetting == null) { 21009 return false; 21010 } 21011 21012 // Permission review applies only to apps not supporting the new permission model. 21013 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21014 return false; 21015 } 21016 21017 // Legacy apps have the permission and get user consent on launch. 21018 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21019 return permissionsState.isPermissionReviewRequired(userId); 21020 } 21021 } 21022 21023 @Override 21024 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21025 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21026 } 21027 21028 @Override 21029 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21030 int userId) { 21031 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21032 } 21033 21034 @Override 21035 public void setDeviceAndProfileOwnerPackages( 21036 int deviceOwnerUserId, String deviceOwnerPackage, 21037 SparseArray<String> profileOwnerPackages) { 21038 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21039 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21040 } 21041 21042 @Override 21043 public boolean isPackageDataProtected(int userId, String packageName) { 21044 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21045 } 21046 21047 @Override 21048 public boolean wasPackageEverLaunched(String packageName, int userId) { 21049 synchronized (mPackages) { 21050 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21051 } 21052 } 21053 } 21054 21055 @Override 21056 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21057 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21058 synchronized (mPackages) { 21059 final long identity = Binder.clearCallingIdentity(); 21060 try { 21061 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21062 packageNames, userId); 21063 } finally { 21064 Binder.restoreCallingIdentity(identity); 21065 } 21066 } 21067 } 21068 21069 @Override 21070 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 21071 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 21072 synchronized (mPackages) { 21073 final long identity = Binder.clearCallingIdentity(); 21074 try { 21075 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 21076 packageNames, userId); 21077 } finally { 21078 Binder.restoreCallingIdentity(identity); 21079 } 21080 } 21081 } 21082 21083 private static void enforceSystemOrPhoneCaller(String tag) { 21084 int callingUid = Binder.getCallingUid(); 21085 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21086 throw new SecurityException( 21087 "Cannot call " + tag + " from UID " + callingUid); 21088 } 21089 } 21090 21091 boolean isHistoricalPackageUsageAvailable() { 21092 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21093 } 21094 21095 /** 21096 * Return a <b>copy</b> of the collection of packages known to the package manager. 21097 * @return A copy of the values of mPackages. 21098 */ 21099 Collection<PackageParser.Package> getPackages() { 21100 synchronized (mPackages) { 21101 return new ArrayList<>(mPackages.values()); 21102 } 21103 } 21104 21105 /** 21106 * Logs process start information (including base APK hash) to the security log. 21107 * @hide 21108 */ 21109 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21110 String apkFile, int pid) { 21111 if (!SecurityLog.isLoggingEnabled()) { 21112 return; 21113 } 21114 Bundle data = new Bundle(); 21115 data.putLong("startTimestamp", System.currentTimeMillis()); 21116 data.putString("processName", processName); 21117 data.putInt("uid", uid); 21118 data.putString("seinfo", seinfo); 21119 data.putString("apkFile", apkFile); 21120 data.putInt("pid", pid); 21121 Message msg = mProcessLoggingHandler.obtainMessage( 21122 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21123 msg.setData(data); 21124 mProcessLoggingHandler.sendMessage(msg); 21125 } 21126 21127 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21128 return mCompilerStats.getPackageStats(pkgName); 21129 } 21130 21131 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21132 return getOrCreateCompilerPackageStats(pkg.packageName); 21133 } 21134 21135 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21136 return mCompilerStats.getOrCreatePackageStats(pkgName); 21137 } 21138 21139 public void deleteCompilerPackageStats(String pkgName) { 21140 mCompilerStats.deletePackageStats(pkgName); 21141 } 21142} 21143