PackageManagerService.java revision 574994afde208fcb60f5aea9921b9b381e13e888
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 /** Special library name that skips shared libraries check during compilation. */ 528 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 529 530 final ServiceThread mHandlerThread; 531 532 final PackageHandler mHandler; 533 534 private final ProcessLoggingHandler mProcessLoggingHandler; 535 536 /** 537 * Messages for {@link #mHandler} that need to wait for system ready before 538 * being dispatched. 539 */ 540 private ArrayList<Message> mPostSystemReadyMessages; 541 542 final int mSdkVersion = Build.VERSION.SDK_INT; 543 544 final Context mContext; 545 final boolean mFactoryTest; 546 final boolean mOnlyCore; 547 final DisplayMetrics mMetrics; 548 final int mDefParseFlags; 549 final String[] mSeparateProcesses; 550 final boolean mIsUpgrade; 551 final boolean mIsPreNUpgrade; 552 final boolean mIsPreNMR1Upgrade; 553 554 @GuardedBy("mPackages") 555 private boolean mDexOptDialogShown; 556 557 /** The location for ASEC container files on internal storage. */ 558 final String mAsecInternalPath; 559 560 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 561 // LOCK HELD. Can be called with mInstallLock held. 562 @GuardedBy("mInstallLock") 563 final Installer mInstaller; 564 565 /** Directory where installed third-party apps stored */ 566 final File mAppInstallDir; 567 final File mEphemeralInstallDir; 568 569 /** 570 * Directory to which applications installed internally have their 571 * 32 bit native libraries copied. 572 */ 573 private File mAppLib32InstallDir; 574 575 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 576 // apps. 577 final File mDrmAppPrivateInstallDir; 578 579 // ---------------------------------------------------------------- 580 581 // Lock for state used when installing and doing other long running 582 // operations. Methods that must be called with this lock held have 583 // the suffix "LI". 584 final Object mInstallLock = new Object(); 585 586 // ---------------------------------------------------------------- 587 588 // Keys are String (package name), values are Package. This also serves 589 // as the lock for the global state. Methods that must be called with 590 // this lock held have the prefix "LP". 591 @GuardedBy("mPackages") 592 final ArrayMap<String, PackageParser.Package> mPackages = 593 new ArrayMap<String, PackageParser.Package>(); 594 595 final ArrayMap<String, Set<String>> mKnownCodebase = 596 new ArrayMap<String, Set<String>>(); 597 598 // Tracks available target package names -> overlay package paths. 599 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 600 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 601 602 /** 603 * Tracks new system packages [received in an OTA] that we expect to 604 * find updated user-installed versions. Keys are package name, values 605 * are package location. 606 */ 607 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 608 /** 609 * Tracks high priority intent filters for protected actions. During boot, certain 610 * filter actions are protected and should never be allowed to have a high priority 611 * intent filter for them. However, there is one, and only one exception -- the 612 * setup wizard. It must be able to define a high priority intent filter for these 613 * actions to ensure there are no escapes from the wizard. We need to delay processing 614 * of these during boot as we need to look at all of the system packages in order 615 * to know which component is the setup wizard. 616 */ 617 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 618 /** 619 * Whether or not processing protected filters should be deferred. 620 */ 621 private boolean mDeferProtectedFilters = true; 622 623 /** 624 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 625 */ 626 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 627 /** 628 * Whether or not system app permissions should be promoted from install to runtime. 629 */ 630 boolean mPromoteSystemApps; 631 632 @GuardedBy("mPackages") 633 final Settings mSettings; 634 635 /** 636 * Set of package names that are currently "frozen", which means active 637 * surgery is being done on the code/data for that package. The platform 638 * will refuse to launch frozen packages to avoid race conditions. 639 * 640 * @see PackageFreezer 641 */ 642 @GuardedBy("mPackages") 643 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 644 645 final ProtectedPackages mProtectedPackages; 646 647 boolean mFirstBoot; 648 649 // System configuration read by SystemConfig. 650 final int[] mGlobalGids; 651 final SparseArray<ArraySet<String>> mSystemPermissions; 652 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 653 654 // If mac_permissions.xml was found for seinfo labeling. 655 boolean mFoundPolicyFile; 656 657 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 658 659 public static final class SharedLibraryEntry { 660 public final String path; 661 public final String apk; 662 663 SharedLibraryEntry(String _path, String _apk) { 664 path = _path; 665 apk = _apk; 666 } 667 } 668 669 // Currently known shared libraries. 670 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 671 new ArrayMap<String, SharedLibraryEntry>(); 672 673 // All available activities, for your resolving pleasure. 674 final ActivityIntentResolver mActivities = 675 new ActivityIntentResolver(); 676 677 // All available receivers, for your resolving pleasure. 678 final ActivityIntentResolver mReceivers = 679 new ActivityIntentResolver(); 680 681 // All available services, for your resolving pleasure. 682 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 683 684 // All available providers, for your resolving pleasure. 685 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 686 687 // Mapping from provider base names (first directory in content URI codePath) 688 // to the provider information. 689 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 690 new ArrayMap<String, PackageParser.Provider>(); 691 692 // Mapping from instrumentation class names to info about them. 693 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 694 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 695 696 // Mapping from permission names to info about them. 697 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 698 new ArrayMap<String, PackageParser.PermissionGroup>(); 699 700 // Packages whose data we have transfered into another package, thus 701 // should no longer exist. 702 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 703 704 // Broadcast actions that are only available to the system. 705 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 706 707 /** List of packages waiting for verification. */ 708 final SparseArray<PackageVerificationState> mPendingVerification 709 = new SparseArray<PackageVerificationState>(); 710 711 /** Set of packages associated with each app op permission. */ 712 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 713 714 final PackageInstallerService mInstallerService; 715 716 private final PackageDexOptimizer mPackageDexOptimizer; 717 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 718 // is used by other apps). 719 private final DexManager mDexManager; 720 721 private AtomicInteger mNextMoveId = new AtomicInteger(); 722 private final MoveCallbacks mMoveCallbacks; 723 724 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 725 726 // Cache of users who need badging. 727 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 728 729 /** Token for keys in mPendingVerification. */ 730 private int mPendingVerificationToken = 0; 731 732 volatile boolean mSystemReady; 733 volatile boolean mSafeMode; 734 volatile boolean mHasSystemUidErrors; 735 736 ApplicationInfo mAndroidApplication; 737 final ActivityInfo mResolveActivity = new ActivityInfo(); 738 final ResolveInfo mResolveInfo = new ResolveInfo(); 739 ComponentName mResolveComponentName; 740 PackageParser.Package mPlatformPackage; 741 ComponentName mCustomResolverComponentName; 742 743 boolean mResolverReplaced = false; 744 745 private final @Nullable ComponentName mIntentFilterVerifierComponent; 746 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 747 748 private int mIntentFilterVerificationToken = 0; 749 750 /** Component that knows whether or not an ephemeral application exists */ 751 final ComponentName mEphemeralResolverComponent; 752 /** The service connection to the ephemeral resolver */ 753 final EphemeralResolverConnection mEphemeralResolverConnection; 754 755 /** Component used to install ephemeral applications */ 756 final ComponentName mEphemeralInstallerComponent; 757 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 758 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 759 760 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 761 = new SparseArray<IntentFilterVerificationState>(); 762 763 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 764 765 // List of packages names to keep cached, even if they are uninstalled for all users 766 private List<String> mKeepUninstalledPackages; 767 768 private UserManagerInternal mUserManagerInternal; 769 770 private static class IFVerificationParams { 771 PackageParser.Package pkg; 772 boolean replacing; 773 int userId; 774 int verifierUid; 775 776 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 777 int _userId, int _verifierUid) { 778 pkg = _pkg; 779 replacing = _replacing; 780 userId = _userId; 781 replacing = _replacing; 782 verifierUid = _verifierUid; 783 } 784 } 785 786 private interface IntentFilterVerifier<T extends IntentFilter> { 787 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 788 T filter, String packageName); 789 void startVerifications(int userId); 790 void receiveVerificationResponse(int verificationId); 791 } 792 793 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 794 private Context mContext; 795 private ComponentName mIntentFilterVerifierComponent; 796 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 797 798 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 799 mContext = context; 800 mIntentFilterVerifierComponent = verifierComponent; 801 } 802 803 private String getDefaultScheme() { 804 return IntentFilter.SCHEME_HTTPS; 805 } 806 807 @Override 808 public void startVerifications(int userId) { 809 // Launch verifications requests 810 int count = mCurrentIntentFilterVerifications.size(); 811 for (int n=0; n<count; n++) { 812 int verificationId = mCurrentIntentFilterVerifications.get(n); 813 final IntentFilterVerificationState ivs = 814 mIntentFilterVerificationStates.get(verificationId); 815 816 String packageName = ivs.getPackageName(); 817 818 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 819 final int filterCount = filters.size(); 820 ArraySet<String> domainsSet = new ArraySet<>(); 821 for (int m=0; m<filterCount; m++) { 822 PackageParser.ActivityIntentInfo filter = filters.get(m); 823 domainsSet.addAll(filter.getHostsList()); 824 } 825 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 826 synchronized (mPackages) { 827 if (mSettings.createIntentFilterVerificationIfNeededLPw( 828 packageName, domainsList) != null) { 829 scheduleWriteSettingsLocked(); 830 } 831 } 832 sendVerificationRequest(userId, verificationId, ivs); 833 } 834 mCurrentIntentFilterVerifications.clear(); 835 } 836 837 private void sendVerificationRequest(int userId, int verificationId, 838 IntentFilterVerificationState ivs) { 839 840 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 841 verificationIntent.putExtra( 842 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 843 verificationId); 844 verificationIntent.putExtra( 845 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 846 getDefaultScheme()); 847 verificationIntent.putExtra( 848 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 849 ivs.getHostsString()); 850 verificationIntent.putExtra( 851 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 852 ivs.getPackageName()); 853 verificationIntent.setComponent(mIntentFilterVerifierComponent); 854 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 855 856 UserHandle user = new UserHandle(userId); 857 mContext.sendBroadcastAsUser(verificationIntent, user); 858 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 859 "Sending IntentFilter verification broadcast"); 860 } 861 862 public void receiveVerificationResponse(int verificationId) { 863 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 864 865 final boolean verified = ivs.isVerified(); 866 867 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 868 final int count = filters.size(); 869 if (DEBUG_DOMAIN_VERIFICATION) { 870 Slog.i(TAG, "Received verification response " + verificationId 871 + " for " + count + " filters, verified=" + verified); 872 } 873 for (int n=0; n<count; n++) { 874 PackageParser.ActivityIntentInfo filter = filters.get(n); 875 filter.setVerified(verified); 876 877 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 878 + " verified with result:" + verified + " and hosts:" 879 + ivs.getHostsString()); 880 } 881 882 mIntentFilterVerificationStates.remove(verificationId); 883 884 final String packageName = ivs.getPackageName(); 885 IntentFilterVerificationInfo ivi = null; 886 887 synchronized (mPackages) { 888 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 889 } 890 if (ivi == null) { 891 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 892 + verificationId + " packageName:" + packageName); 893 return; 894 } 895 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 896 "Updating IntentFilterVerificationInfo for package " + packageName 897 +" verificationId:" + verificationId); 898 899 synchronized (mPackages) { 900 if (verified) { 901 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 902 } else { 903 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 904 } 905 scheduleWriteSettingsLocked(); 906 907 final int userId = ivs.getUserId(); 908 if (userId != UserHandle.USER_ALL) { 909 final int userStatus = 910 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 911 912 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 913 boolean needUpdate = false; 914 915 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 916 // already been set by the User thru the Disambiguation dialog 917 switch (userStatus) { 918 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 919 if (verified) { 920 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 921 } else { 922 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 923 } 924 needUpdate = true; 925 break; 926 927 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 928 if (verified) { 929 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 930 needUpdate = true; 931 } 932 break; 933 934 default: 935 // Nothing to do 936 } 937 938 if (needUpdate) { 939 mSettings.updateIntentFilterVerificationStatusLPw( 940 packageName, updatedStatus, userId); 941 scheduleWritePackageRestrictionsLocked(userId); 942 } 943 } 944 } 945 } 946 947 @Override 948 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 949 ActivityIntentInfo filter, String packageName) { 950 if (!hasValidDomains(filter)) { 951 return false; 952 } 953 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 954 if (ivs == null) { 955 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 956 packageName); 957 } 958 if (DEBUG_DOMAIN_VERIFICATION) { 959 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 960 } 961 ivs.addFilter(filter); 962 return true; 963 } 964 965 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 966 int userId, int verificationId, String packageName) { 967 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 968 verifierUid, userId, packageName); 969 ivs.setPendingState(); 970 synchronized (mPackages) { 971 mIntentFilterVerificationStates.append(verificationId, ivs); 972 mCurrentIntentFilterVerifications.add(verificationId); 973 } 974 return ivs; 975 } 976 } 977 978 private static boolean hasValidDomains(ActivityIntentInfo filter) { 979 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 980 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 981 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 982 } 983 984 // Set of pending broadcasts for aggregating enable/disable of components. 985 static class PendingPackageBroadcasts { 986 // for each user id, a map of <package name -> components within that package> 987 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 988 989 public PendingPackageBroadcasts() { 990 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 991 } 992 993 public ArrayList<String> get(int userId, String packageName) { 994 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 995 return packages.get(packageName); 996 } 997 998 public void put(int userId, String packageName, ArrayList<String> components) { 999 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1000 packages.put(packageName, components); 1001 } 1002 1003 public void remove(int userId, String packageName) { 1004 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1005 if (packages != null) { 1006 packages.remove(packageName); 1007 } 1008 } 1009 1010 public void remove(int userId) { 1011 mUidMap.remove(userId); 1012 } 1013 1014 public int userIdCount() { 1015 return mUidMap.size(); 1016 } 1017 1018 public int userIdAt(int n) { 1019 return mUidMap.keyAt(n); 1020 } 1021 1022 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1023 return mUidMap.get(userId); 1024 } 1025 1026 public int size() { 1027 // total number of pending broadcast entries across all userIds 1028 int num = 0; 1029 for (int i = 0; i< mUidMap.size(); i++) { 1030 num += mUidMap.valueAt(i).size(); 1031 } 1032 return num; 1033 } 1034 1035 public void clear() { 1036 mUidMap.clear(); 1037 } 1038 1039 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1040 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1041 if (map == null) { 1042 map = new ArrayMap<String, ArrayList<String>>(); 1043 mUidMap.put(userId, map); 1044 } 1045 return map; 1046 } 1047 } 1048 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1049 1050 // Service Connection to remote media container service to copy 1051 // package uri's from external media onto secure containers 1052 // or internal storage. 1053 private IMediaContainerService mContainerService = null; 1054 1055 static final int SEND_PENDING_BROADCAST = 1; 1056 static final int MCS_BOUND = 3; 1057 static final int END_COPY = 4; 1058 static final int INIT_COPY = 5; 1059 static final int MCS_UNBIND = 6; 1060 static final int START_CLEANING_PACKAGE = 7; 1061 static final int FIND_INSTALL_LOC = 8; 1062 static final int POST_INSTALL = 9; 1063 static final int MCS_RECONNECT = 10; 1064 static final int MCS_GIVE_UP = 11; 1065 static final int UPDATED_MEDIA_STATUS = 12; 1066 static final int WRITE_SETTINGS = 13; 1067 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1068 static final int PACKAGE_VERIFIED = 15; 1069 static final int CHECK_PENDING_VERIFICATION = 16; 1070 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1071 static final int INTENT_FILTER_VERIFIED = 18; 1072 static final int WRITE_PACKAGE_LIST = 19; 1073 1074 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1075 1076 // Delay time in millisecs 1077 static final int BROADCAST_DELAY = 10 * 1000; 1078 1079 static UserManagerService sUserManager; 1080 1081 // Stores a list of users whose package restrictions file needs to be updated 1082 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1083 1084 final private DefaultContainerConnection mDefContainerConn = 1085 new DefaultContainerConnection(); 1086 class DefaultContainerConnection implements ServiceConnection { 1087 public void onServiceConnected(ComponentName name, IBinder service) { 1088 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1089 IMediaContainerService imcs = 1090 IMediaContainerService.Stub.asInterface(service); 1091 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1092 } 1093 1094 public void onServiceDisconnected(ComponentName name) { 1095 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1096 } 1097 } 1098 1099 // Recordkeeping of restore-after-install operations that are currently in flight 1100 // between the Package Manager and the Backup Manager 1101 static class PostInstallData { 1102 public InstallArgs args; 1103 public PackageInstalledInfo res; 1104 1105 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1106 args = _a; 1107 res = _r; 1108 } 1109 } 1110 1111 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1112 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1113 1114 // XML tags for backup/restore of various bits of state 1115 private static final String TAG_PREFERRED_BACKUP = "pa"; 1116 private static final String TAG_DEFAULT_APPS = "da"; 1117 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1118 1119 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1120 private static final String TAG_ALL_GRANTS = "rt-grants"; 1121 private static final String TAG_GRANT = "grant"; 1122 private static final String ATTR_PACKAGE_NAME = "pkg"; 1123 1124 private static final String TAG_PERMISSION = "perm"; 1125 private static final String ATTR_PERMISSION_NAME = "name"; 1126 private static final String ATTR_IS_GRANTED = "g"; 1127 private static final String ATTR_USER_SET = "set"; 1128 private static final String ATTR_USER_FIXED = "fixed"; 1129 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1130 1131 // System/policy permission grants are not backed up 1132 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1133 FLAG_PERMISSION_POLICY_FIXED 1134 | FLAG_PERMISSION_SYSTEM_FIXED 1135 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1136 1137 // And we back up these user-adjusted states 1138 private static final int USER_RUNTIME_GRANT_MASK = 1139 FLAG_PERMISSION_USER_SET 1140 | FLAG_PERMISSION_USER_FIXED 1141 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1142 1143 final @Nullable String mRequiredVerifierPackage; 1144 final @NonNull String mRequiredInstallerPackage; 1145 final @NonNull String mRequiredUninstallerPackage; 1146 final @Nullable String mSetupWizardPackage; 1147 final @Nullable String mStorageManagerPackage; 1148 final @NonNull String mServicesSystemSharedLibraryPackageName; 1149 final @NonNull String mSharedSystemSharedLibraryPackageName; 1150 1151 final boolean mPermissionReviewRequired; 1152 1153 private final PackageUsage mPackageUsage = new PackageUsage(); 1154 private final CompilerStats mCompilerStats = new CompilerStats(); 1155 1156 class PackageHandler extends Handler { 1157 private boolean mBound = false; 1158 final ArrayList<HandlerParams> mPendingInstalls = 1159 new ArrayList<HandlerParams>(); 1160 1161 private boolean connectToService() { 1162 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1163 " DefaultContainerService"); 1164 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1165 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1166 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1167 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1168 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1169 mBound = true; 1170 return true; 1171 } 1172 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1173 return false; 1174 } 1175 1176 private void disconnectService() { 1177 mContainerService = null; 1178 mBound = false; 1179 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1180 mContext.unbindService(mDefContainerConn); 1181 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1182 } 1183 1184 PackageHandler(Looper looper) { 1185 super(looper); 1186 } 1187 1188 public void handleMessage(Message msg) { 1189 try { 1190 doHandleMessage(msg); 1191 } finally { 1192 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1193 } 1194 } 1195 1196 void doHandleMessage(Message msg) { 1197 switch (msg.what) { 1198 case INIT_COPY: { 1199 HandlerParams params = (HandlerParams) msg.obj; 1200 int idx = mPendingInstalls.size(); 1201 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1202 // If a bind was already initiated we dont really 1203 // need to do anything. The pending install 1204 // will be processed later on. 1205 if (!mBound) { 1206 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1207 System.identityHashCode(mHandler)); 1208 // If this is the only one pending we might 1209 // have to bind to the service again. 1210 if (!connectToService()) { 1211 Slog.e(TAG, "Failed to bind to media container service"); 1212 params.serviceError(); 1213 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1214 System.identityHashCode(mHandler)); 1215 if (params.traceMethod != null) { 1216 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1217 params.traceCookie); 1218 } 1219 return; 1220 } else { 1221 // Once we bind to the service, the first 1222 // pending request will be processed. 1223 mPendingInstalls.add(idx, params); 1224 } 1225 } else { 1226 mPendingInstalls.add(idx, params); 1227 // Already bound to the service. Just make 1228 // sure we trigger off processing the first request. 1229 if (idx == 0) { 1230 mHandler.sendEmptyMessage(MCS_BOUND); 1231 } 1232 } 1233 break; 1234 } 1235 case MCS_BOUND: { 1236 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1237 if (msg.obj != null) { 1238 mContainerService = (IMediaContainerService) msg.obj; 1239 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1240 System.identityHashCode(mHandler)); 1241 } 1242 if (mContainerService == null) { 1243 if (!mBound) { 1244 // Something seriously wrong since we are not bound and we are not 1245 // waiting for connection. Bail out. 1246 Slog.e(TAG, "Cannot bind to media container service"); 1247 for (HandlerParams params : mPendingInstalls) { 1248 // Indicate service bind error 1249 params.serviceError(); 1250 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1251 System.identityHashCode(params)); 1252 if (params.traceMethod != null) { 1253 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1254 params.traceMethod, params.traceCookie); 1255 } 1256 return; 1257 } 1258 mPendingInstalls.clear(); 1259 } else { 1260 Slog.w(TAG, "Waiting to connect to media container service"); 1261 } 1262 } else if (mPendingInstalls.size() > 0) { 1263 HandlerParams params = mPendingInstalls.get(0); 1264 if (params != null) { 1265 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1266 System.identityHashCode(params)); 1267 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1268 if (params.startCopy()) { 1269 // We are done... look for more work or to 1270 // go idle. 1271 if (DEBUG_SD_INSTALL) Log.i(TAG, 1272 "Checking for more work or unbind..."); 1273 // Delete pending install 1274 if (mPendingInstalls.size() > 0) { 1275 mPendingInstalls.remove(0); 1276 } 1277 if (mPendingInstalls.size() == 0) { 1278 if (mBound) { 1279 if (DEBUG_SD_INSTALL) Log.i(TAG, 1280 "Posting delayed MCS_UNBIND"); 1281 removeMessages(MCS_UNBIND); 1282 Message ubmsg = obtainMessage(MCS_UNBIND); 1283 // Unbind after a little delay, to avoid 1284 // continual thrashing. 1285 sendMessageDelayed(ubmsg, 10000); 1286 } 1287 } else { 1288 // There are more pending requests in queue. 1289 // Just post MCS_BOUND message to trigger processing 1290 // of next pending install. 1291 if (DEBUG_SD_INSTALL) Log.i(TAG, 1292 "Posting MCS_BOUND for next work"); 1293 mHandler.sendEmptyMessage(MCS_BOUND); 1294 } 1295 } 1296 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1297 } 1298 } else { 1299 // Should never happen ideally. 1300 Slog.w(TAG, "Empty queue"); 1301 } 1302 break; 1303 } 1304 case MCS_RECONNECT: { 1305 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1306 if (mPendingInstalls.size() > 0) { 1307 if (mBound) { 1308 disconnectService(); 1309 } 1310 if (!connectToService()) { 1311 Slog.e(TAG, "Failed to bind to media container service"); 1312 for (HandlerParams params : mPendingInstalls) { 1313 // Indicate service bind error 1314 params.serviceError(); 1315 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1316 System.identityHashCode(params)); 1317 } 1318 mPendingInstalls.clear(); 1319 } 1320 } 1321 break; 1322 } 1323 case MCS_UNBIND: { 1324 // If there is no actual work left, then time to unbind. 1325 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1326 1327 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1328 if (mBound) { 1329 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1330 1331 disconnectService(); 1332 } 1333 } else if (mPendingInstalls.size() > 0) { 1334 // There are more pending requests in queue. 1335 // Just post MCS_BOUND message to trigger processing 1336 // of next pending install. 1337 mHandler.sendEmptyMessage(MCS_BOUND); 1338 } 1339 1340 break; 1341 } 1342 case MCS_GIVE_UP: { 1343 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1344 HandlerParams params = mPendingInstalls.remove(0); 1345 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1346 System.identityHashCode(params)); 1347 break; 1348 } 1349 case SEND_PENDING_BROADCAST: { 1350 String packages[]; 1351 ArrayList<String> components[]; 1352 int size = 0; 1353 int uids[]; 1354 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1355 synchronized (mPackages) { 1356 if (mPendingBroadcasts == null) { 1357 return; 1358 } 1359 size = mPendingBroadcasts.size(); 1360 if (size <= 0) { 1361 // Nothing to be done. Just return 1362 return; 1363 } 1364 packages = new String[size]; 1365 components = new ArrayList[size]; 1366 uids = new int[size]; 1367 int i = 0; // filling out the above arrays 1368 1369 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1370 int packageUserId = mPendingBroadcasts.userIdAt(n); 1371 Iterator<Map.Entry<String, ArrayList<String>>> it 1372 = mPendingBroadcasts.packagesForUserId(packageUserId) 1373 .entrySet().iterator(); 1374 while (it.hasNext() && i < size) { 1375 Map.Entry<String, ArrayList<String>> ent = it.next(); 1376 packages[i] = ent.getKey(); 1377 components[i] = ent.getValue(); 1378 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1379 uids[i] = (ps != null) 1380 ? UserHandle.getUid(packageUserId, ps.appId) 1381 : -1; 1382 i++; 1383 } 1384 } 1385 size = i; 1386 mPendingBroadcasts.clear(); 1387 } 1388 // Send broadcasts 1389 for (int i = 0; i < size; i++) { 1390 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1391 } 1392 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1393 break; 1394 } 1395 case START_CLEANING_PACKAGE: { 1396 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1397 final String packageName = (String)msg.obj; 1398 final int userId = msg.arg1; 1399 final boolean andCode = msg.arg2 != 0; 1400 synchronized (mPackages) { 1401 if (userId == UserHandle.USER_ALL) { 1402 int[] users = sUserManager.getUserIds(); 1403 for (int user : users) { 1404 mSettings.addPackageToCleanLPw( 1405 new PackageCleanItem(user, packageName, andCode)); 1406 } 1407 } else { 1408 mSettings.addPackageToCleanLPw( 1409 new PackageCleanItem(userId, packageName, andCode)); 1410 } 1411 } 1412 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1413 startCleaningPackages(); 1414 } break; 1415 case POST_INSTALL: { 1416 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1417 1418 PostInstallData data = mRunningInstalls.get(msg.arg1); 1419 final boolean didRestore = (msg.arg2 != 0); 1420 mRunningInstalls.delete(msg.arg1); 1421 1422 if (data != null) { 1423 InstallArgs args = data.args; 1424 PackageInstalledInfo parentRes = data.res; 1425 1426 final boolean grantPermissions = (args.installFlags 1427 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1428 final boolean killApp = (args.installFlags 1429 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1430 final String[] grantedPermissions = args.installGrantPermissions; 1431 1432 // Handle the parent package 1433 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1434 grantedPermissions, didRestore, args.installerPackageName, 1435 args.observer); 1436 1437 // Handle the child packages 1438 final int childCount = (parentRes.addedChildPackages != null) 1439 ? parentRes.addedChildPackages.size() : 0; 1440 for (int i = 0; i < childCount; i++) { 1441 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1442 handlePackagePostInstall(childRes, grantPermissions, killApp, 1443 grantedPermissions, false, args.installerPackageName, 1444 args.observer); 1445 } 1446 1447 // Log tracing if needed 1448 if (args.traceMethod != null) { 1449 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1450 args.traceCookie); 1451 } 1452 } else { 1453 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1454 } 1455 1456 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1457 } break; 1458 case UPDATED_MEDIA_STATUS: { 1459 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1460 boolean reportStatus = msg.arg1 == 1; 1461 boolean doGc = msg.arg2 == 1; 1462 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1463 if (doGc) { 1464 // Force a gc to clear up stale containers. 1465 Runtime.getRuntime().gc(); 1466 } 1467 if (msg.obj != null) { 1468 @SuppressWarnings("unchecked") 1469 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1470 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1471 // Unload containers 1472 unloadAllContainers(args); 1473 } 1474 if (reportStatus) { 1475 try { 1476 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1477 PackageHelper.getMountService().finishMediaUpdate(); 1478 } catch (RemoteException e) { 1479 Log.e(TAG, "MountService not running?"); 1480 } 1481 } 1482 } break; 1483 case WRITE_SETTINGS: { 1484 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1485 synchronized (mPackages) { 1486 removeMessages(WRITE_SETTINGS); 1487 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1488 mSettings.writeLPr(); 1489 mDirtyUsers.clear(); 1490 } 1491 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1492 } break; 1493 case WRITE_PACKAGE_RESTRICTIONS: { 1494 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1495 synchronized (mPackages) { 1496 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1497 for (int userId : mDirtyUsers) { 1498 mSettings.writePackageRestrictionsLPr(userId); 1499 } 1500 mDirtyUsers.clear(); 1501 } 1502 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1503 } break; 1504 case WRITE_PACKAGE_LIST: { 1505 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1506 synchronized (mPackages) { 1507 removeMessages(WRITE_PACKAGE_LIST); 1508 mSettings.writePackageListLPr(msg.arg1); 1509 } 1510 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1511 } break; 1512 case CHECK_PENDING_VERIFICATION: { 1513 final int verificationId = msg.arg1; 1514 final PackageVerificationState state = mPendingVerification.get(verificationId); 1515 1516 if ((state != null) && !state.timeoutExtended()) { 1517 final InstallArgs args = state.getInstallArgs(); 1518 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1519 1520 Slog.i(TAG, "Verification timed out for " + originUri); 1521 mPendingVerification.remove(verificationId); 1522 1523 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1524 1525 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1526 Slog.i(TAG, "Continuing with installation of " + originUri); 1527 state.setVerifierResponse(Binder.getCallingUid(), 1528 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1529 broadcastPackageVerified(verificationId, originUri, 1530 PackageManager.VERIFICATION_ALLOW, 1531 state.getInstallArgs().getUser()); 1532 try { 1533 ret = args.copyApk(mContainerService, true); 1534 } catch (RemoteException e) { 1535 Slog.e(TAG, "Could not contact the ContainerService"); 1536 } 1537 } else { 1538 broadcastPackageVerified(verificationId, originUri, 1539 PackageManager.VERIFICATION_REJECT, 1540 state.getInstallArgs().getUser()); 1541 } 1542 1543 Trace.asyncTraceEnd( 1544 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1545 1546 processPendingInstall(args, ret); 1547 mHandler.sendEmptyMessage(MCS_UNBIND); 1548 } 1549 break; 1550 } 1551 case PACKAGE_VERIFIED: { 1552 final int verificationId = msg.arg1; 1553 1554 final PackageVerificationState state = mPendingVerification.get(verificationId); 1555 if (state == null) { 1556 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1557 break; 1558 } 1559 1560 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1561 1562 state.setVerifierResponse(response.callerUid, response.code); 1563 1564 if (state.isVerificationComplete()) { 1565 mPendingVerification.remove(verificationId); 1566 1567 final InstallArgs args = state.getInstallArgs(); 1568 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1569 1570 int ret; 1571 if (state.isInstallAllowed()) { 1572 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1573 broadcastPackageVerified(verificationId, originUri, 1574 response.code, state.getInstallArgs().getUser()); 1575 try { 1576 ret = args.copyApk(mContainerService, true); 1577 } catch (RemoteException e) { 1578 Slog.e(TAG, "Could not contact the ContainerService"); 1579 } 1580 } else { 1581 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1582 } 1583 1584 Trace.asyncTraceEnd( 1585 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1586 1587 processPendingInstall(args, ret); 1588 mHandler.sendEmptyMessage(MCS_UNBIND); 1589 } 1590 1591 break; 1592 } 1593 case START_INTENT_FILTER_VERIFICATIONS: { 1594 IFVerificationParams params = (IFVerificationParams) msg.obj; 1595 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1596 params.replacing, params.pkg); 1597 break; 1598 } 1599 case INTENT_FILTER_VERIFIED: { 1600 final int verificationId = msg.arg1; 1601 1602 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1603 verificationId); 1604 if (state == null) { 1605 Slog.w(TAG, "Invalid IntentFilter verification token " 1606 + verificationId + " received"); 1607 break; 1608 } 1609 1610 final int userId = state.getUserId(); 1611 1612 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1613 "Processing IntentFilter verification with token:" 1614 + verificationId + " and userId:" + userId); 1615 1616 final IntentFilterVerificationResponse response = 1617 (IntentFilterVerificationResponse) msg.obj; 1618 1619 state.setVerifierResponse(response.callerUid, response.code); 1620 1621 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1622 "IntentFilter verification with token:" + verificationId 1623 + " and userId:" + userId 1624 + " is settings verifier response with response code:" 1625 + response.code); 1626 1627 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1628 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1629 + response.getFailedDomainsString()); 1630 } 1631 1632 if (state.isVerificationComplete()) { 1633 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1634 } else { 1635 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1636 "IntentFilter verification with token:" + verificationId 1637 + " was not said to be complete"); 1638 } 1639 1640 break; 1641 } 1642 } 1643 } 1644 } 1645 1646 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1647 boolean killApp, String[] grantedPermissions, 1648 boolean launchedForRestore, String installerPackage, 1649 IPackageInstallObserver2 installObserver) { 1650 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1651 // Send the removed broadcasts 1652 if (res.removedInfo != null) { 1653 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1654 } 1655 1656 // Now that we successfully installed the package, grant runtime 1657 // permissions if requested before broadcasting the install. 1658 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1659 >= Build.VERSION_CODES.M) { 1660 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1661 } 1662 1663 final boolean update = res.removedInfo != null 1664 && res.removedInfo.removedPackage != null; 1665 1666 // If this is the first time we have child packages for a disabled privileged 1667 // app that had no children, we grant requested runtime permissions to the new 1668 // children if the parent on the system image had them already granted. 1669 if (res.pkg.parentPackage != null) { 1670 synchronized (mPackages) { 1671 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1672 } 1673 } 1674 1675 synchronized (mPackages) { 1676 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1677 } 1678 1679 final String packageName = res.pkg.applicationInfo.packageName; 1680 Bundle extras = new Bundle(1); 1681 extras.putInt(Intent.EXTRA_UID, res.uid); 1682 1683 // Determine the set of users who are adding this package for 1684 // the first time vs. those who are seeing an update. 1685 int[] firstUsers = EMPTY_INT_ARRAY; 1686 int[] updateUsers = EMPTY_INT_ARRAY; 1687 if (res.origUsers == null || res.origUsers.length == 0) { 1688 firstUsers = res.newUsers; 1689 } else { 1690 for (int newUser : res.newUsers) { 1691 boolean isNew = true; 1692 for (int origUser : res.origUsers) { 1693 if (origUser == newUser) { 1694 isNew = false; 1695 break; 1696 } 1697 } 1698 if (isNew) { 1699 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1700 } else { 1701 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1702 } 1703 } 1704 } 1705 1706 // Send installed broadcasts if the install/update is not ephemeral 1707 if (!isEphemeral(res.pkg)) { 1708 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1709 1710 // Send added for users that see the package for the first time 1711 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1712 extras, 0 /*flags*/, null /*targetPackage*/, 1713 null /*finishedReceiver*/, firstUsers); 1714 1715 // Send added for users that don't see the package for the first time 1716 if (update) { 1717 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1718 } 1719 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1720 extras, 0 /*flags*/, null /*targetPackage*/, 1721 null /*finishedReceiver*/, updateUsers); 1722 1723 // Send replaced for users that don't see the package for the first time 1724 if (update) { 1725 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1726 packageName, extras, 0 /*flags*/, 1727 null /*targetPackage*/, null /*finishedReceiver*/, 1728 updateUsers); 1729 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1730 null /*package*/, null /*extras*/, 0 /*flags*/, 1731 packageName /*targetPackage*/, 1732 null /*finishedReceiver*/, updateUsers); 1733 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1734 // First-install and we did a restore, so we're responsible for the 1735 // first-launch broadcast. 1736 if (DEBUG_BACKUP) { 1737 Slog.i(TAG, "Post-restore of " + packageName 1738 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1739 } 1740 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1741 } 1742 1743 // Send broadcast package appeared if forward locked/external for all users 1744 // treat asec-hosted packages like removable media on upgrade 1745 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1746 if (DEBUG_INSTALL) { 1747 Slog.i(TAG, "upgrading pkg " + res.pkg 1748 + " is ASEC-hosted -> AVAILABLE"); 1749 } 1750 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1751 ArrayList<String> pkgList = new ArrayList<>(1); 1752 pkgList.add(packageName); 1753 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1754 } 1755 } 1756 1757 // Work that needs to happen on first install within each user 1758 if (firstUsers != null && firstUsers.length > 0) { 1759 synchronized (mPackages) { 1760 for (int userId : firstUsers) { 1761 // If this app is a browser and it's newly-installed for some 1762 // users, clear any default-browser state in those users. The 1763 // app's nature doesn't depend on the user, so we can just check 1764 // its browser nature in any user and generalize. 1765 if (packageIsBrowser(packageName, userId)) { 1766 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1767 } 1768 1769 // We may also need to apply pending (restored) runtime 1770 // permission grants within these users. 1771 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1772 } 1773 } 1774 } 1775 1776 // Log current value of "unknown sources" setting 1777 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1778 getUnknownSourcesSettings()); 1779 1780 // Force a gc to clear up things 1781 Runtime.getRuntime().gc(); 1782 1783 // Remove the replaced package's older resources safely now 1784 // We delete after a gc for applications on sdcard. 1785 if (res.removedInfo != null && res.removedInfo.args != null) { 1786 synchronized (mInstallLock) { 1787 res.removedInfo.args.doPostDeleteLI(true); 1788 } 1789 } 1790 1791 if (!isEphemeral(res.pkg)) { 1792 // Notify DexManager that the package was installed for new users. 1793 // The updated users should already be indexed and the package code paths 1794 // should not change. 1795 // Don't notify the manager for ephemeral apps as they are not expected to 1796 // survive long enough to benefit of background optimizations. 1797 for (int userId : firstUsers) { 1798 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1799 mDexManager.notifyPackageInstalled(info, userId); 1800 } 1801 } 1802 } 1803 1804 // If someone is watching installs - notify them 1805 if (installObserver != null) { 1806 try { 1807 Bundle extras = extrasForInstallResult(res); 1808 installObserver.onPackageInstalled(res.name, res.returnCode, 1809 res.returnMsg, extras); 1810 } catch (RemoteException e) { 1811 Slog.i(TAG, "Observer no longer exists."); 1812 } 1813 } 1814 } 1815 1816 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1817 PackageParser.Package pkg) { 1818 if (pkg.parentPackage == null) { 1819 return; 1820 } 1821 if (pkg.requestedPermissions == null) { 1822 return; 1823 } 1824 final PackageSetting disabledSysParentPs = mSettings 1825 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1826 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1827 || !disabledSysParentPs.isPrivileged() 1828 || (disabledSysParentPs.childPackageNames != null 1829 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1830 return; 1831 } 1832 final int[] allUserIds = sUserManager.getUserIds(); 1833 final int permCount = pkg.requestedPermissions.size(); 1834 for (int i = 0; i < permCount; i++) { 1835 String permission = pkg.requestedPermissions.get(i); 1836 BasePermission bp = mSettings.mPermissions.get(permission); 1837 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1838 continue; 1839 } 1840 for (int userId : allUserIds) { 1841 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1842 permission, userId)) { 1843 grantRuntimePermission(pkg.packageName, permission, userId); 1844 } 1845 } 1846 } 1847 } 1848 1849 private StorageEventListener mStorageListener = new StorageEventListener() { 1850 @Override 1851 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1852 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1853 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1854 final String volumeUuid = vol.getFsUuid(); 1855 1856 // Clean up any users or apps that were removed or recreated 1857 // while this volume was missing 1858 reconcileUsers(volumeUuid); 1859 reconcileApps(volumeUuid); 1860 1861 // Clean up any install sessions that expired or were 1862 // cancelled while this volume was missing 1863 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1864 1865 loadPrivatePackages(vol); 1866 1867 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1868 unloadPrivatePackages(vol); 1869 } 1870 } 1871 1872 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1873 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1874 updateExternalMediaStatus(true, false); 1875 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1876 updateExternalMediaStatus(false, false); 1877 } 1878 } 1879 } 1880 1881 @Override 1882 public void onVolumeForgotten(String fsUuid) { 1883 if (TextUtils.isEmpty(fsUuid)) { 1884 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1885 return; 1886 } 1887 1888 // Remove any apps installed on the forgotten volume 1889 synchronized (mPackages) { 1890 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1891 for (PackageSetting ps : packages) { 1892 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1893 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1894 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1895 } 1896 1897 mSettings.onVolumeForgotten(fsUuid); 1898 mSettings.writeLPr(); 1899 } 1900 } 1901 }; 1902 1903 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1904 String[] grantedPermissions) { 1905 for (int userId : userIds) { 1906 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1907 } 1908 1909 // We could have touched GID membership, so flush out packages.list 1910 synchronized (mPackages) { 1911 mSettings.writePackageListLPr(); 1912 } 1913 } 1914 1915 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1916 String[] grantedPermissions) { 1917 SettingBase sb = (SettingBase) pkg.mExtras; 1918 if (sb == null) { 1919 return; 1920 } 1921 1922 PermissionsState permissionsState = sb.getPermissionsState(); 1923 1924 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1925 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1926 1927 for (String permission : pkg.requestedPermissions) { 1928 final BasePermission bp; 1929 synchronized (mPackages) { 1930 bp = mSettings.mPermissions.get(permission); 1931 } 1932 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1933 && (grantedPermissions == null 1934 || ArrayUtils.contains(grantedPermissions, permission))) { 1935 final int flags = permissionsState.getPermissionFlags(permission, userId); 1936 // Installer cannot change immutable permissions. 1937 if ((flags & immutableFlags) == 0) { 1938 grantRuntimePermission(pkg.packageName, permission, userId); 1939 } 1940 } 1941 } 1942 } 1943 1944 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1945 Bundle extras = null; 1946 switch (res.returnCode) { 1947 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1948 extras = new Bundle(); 1949 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1950 res.origPermission); 1951 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1952 res.origPackage); 1953 break; 1954 } 1955 case PackageManager.INSTALL_SUCCEEDED: { 1956 extras = new Bundle(); 1957 extras.putBoolean(Intent.EXTRA_REPLACING, 1958 res.removedInfo != null && res.removedInfo.removedPackage != null); 1959 break; 1960 } 1961 } 1962 return extras; 1963 } 1964 1965 void scheduleWriteSettingsLocked() { 1966 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1967 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1968 } 1969 } 1970 1971 void scheduleWritePackageListLocked(int userId) { 1972 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 1973 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 1974 msg.arg1 = userId; 1975 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 1976 } 1977 } 1978 1979 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1980 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1981 scheduleWritePackageRestrictionsLocked(userId); 1982 } 1983 1984 void scheduleWritePackageRestrictionsLocked(int userId) { 1985 final int[] userIds = (userId == UserHandle.USER_ALL) 1986 ? sUserManager.getUserIds() : new int[]{userId}; 1987 for (int nextUserId : userIds) { 1988 if (!sUserManager.exists(nextUserId)) return; 1989 mDirtyUsers.add(nextUserId); 1990 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1991 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1992 } 1993 } 1994 } 1995 1996 public static PackageManagerService main(Context context, Installer installer, 1997 boolean factoryTest, boolean onlyCore) { 1998 // Self-check for initial settings. 1999 PackageManagerServiceCompilerMapping.checkProperties(); 2000 2001 PackageManagerService m = new PackageManagerService(context, installer, 2002 factoryTest, onlyCore); 2003 m.enableSystemUserPackages(); 2004 ServiceManager.addService("package", m); 2005 return m; 2006 } 2007 2008 private void enableSystemUserPackages() { 2009 if (!UserManager.isSplitSystemUser()) { 2010 return; 2011 } 2012 // For system user, enable apps based on the following conditions: 2013 // - app is whitelisted or belong to one of these groups: 2014 // -- system app which has no launcher icons 2015 // -- system app which has INTERACT_ACROSS_USERS permission 2016 // -- system IME app 2017 // - app is not in the blacklist 2018 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2019 Set<String> enableApps = new ArraySet<>(); 2020 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2021 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2022 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2023 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2024 enableApps.addAll(wlApps); 2025 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2026 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2027 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2028 enableApps.removeAll(blApps); 2029 Log.i(TAG, "Applications installed for system user: " + enableApps); 2030 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2031 UserHandle.SYSTEM); 2032 final int allAppsSize = allAps.size(); 2033 synchronized (mPackages) { 2034 for (int i = 0; i < allAppsSize; i++) { 2035 String pName = allAps.get(i); 2036 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2037 // Should not happen, but we shouldn't be failing if it does 2038 if (pkgSetting == null) { 2039 continue; 2040 } 2041 boolean install = enableApps.contains(pName); 2042 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2043 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2044 + " for system user"); 2045 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2046 } 2047 } 2048 } 2049 } 2050 2051 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2052 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2053 Context.DISPLAY_SERVICE); 2054 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2055 } 2056 2057 /** 2058 * Requests that files preopted on a secondary system partition be copied to the data partition 2059 * if possible. Note that the actual copying of the files is accomplished by init for security 2060 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2061 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2062 */ 2063 private static void requestCopyPreoptedFiles() { 2064 final int WAIT_TIME_MS = 100; 2065 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2066 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2067 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2068 // We will wait for up to 100 seconds. 2069 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2070 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2071 try { 2072 Thread.sleep(WAIT_TIME_MS); 2073 } catch (InterruptedException e) { 2074 // Do nothing 2075 } 2076 if (SystemClock.uptimeMillis() > timeEnd) { 2077 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2078 Slog.wtf(TAG, "cppreopt did not finish!"); 2079 break; 2080 } 2081 } 2082 } 2083 } 2084 2085 public PackageManagerService(Context context, Installer installer, 2086 boolean factoryTest, boolean onlyCore) { 2087 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2088 SystemClock.uptimeMillis()); 2089 2090 if (mSdkVersion <= 0) { 2091 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2092 } 2093 2094 mContext = context; 2095 2096 mPermissionReviewRequired = context.getResources().getBoolean( 2097 R.bool.config_permissionReviewRequired); 2098 2099 mFactoryTest = factoryTest; 2100 mOnlyCore = onlyCore; 2101 mMetrics = new DisplayMetrics(); 2102 mSettings = new Settings(mPackages); 2103 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2104 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2105 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2106 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2107 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2108 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2109 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2110 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2111 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2112 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2113 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2114 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2115 2116 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2117 if (separateProcesses != null && separateProcesses.length() > 0) { 2118 if ("*".equals(separateProcesses)) { 2119 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2120 mSeparateProcesses = null; 2121 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2122 } else { 2123 mDefParseFlags = 0; 2124 mSeparateProcesses = separateProcesses.split(","); 2125 Slog.w(TAG, "Running with debug.separate_processes: " 2126 + separateProcesses); 2127 } 2128 } else { 2129 mDefParseFlags = 0; 2130 mSeparateProcesses = null; 2131 } 2132 2133 mInstaller = installer; 2134 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2135 "*dexopt*"); 2136 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2137 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2138 2139 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2140 FgThread.get().getLooper()); 2141 2142 getDefaultDisplayMetrics(context, mMetrics); 2143 2144 SystemConfig systemConfig = SystemConfig.getInstance(); 2145 mGlobalGids = systemConfig.getGlobalGids(); 2146 mSystemPermissions = systemConfig.getSystemPermissions(); 2147 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2148 2149 mProtectedPackages = new ProtectedPackages(mContext); 2150 2151 synchronized (mInstallLock) { 2152 // writer 2153 synchronized (mPackages) { 2154 mHandlerThread = new ServiceThread(TAG, 2155 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2156 mHandlerThread.start(); 2157 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2158 mProcessLoggingHandler = new ProcessLoggingHandler(); 2159 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2160 2161 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2162 2163 File dataDir = Environment.getDataDirectory(); 2164 mAppInstallDir = new File(dataDir, "app"); 2165 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2166 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2167 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2168 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2169 2170 sUserManager = new UserManagerService(context, this, mPackages); 2171 2172 // Propagate permission configuration in to package manager. 2173 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2174 = systemConfig.getPermissions(); 2175 for (int i=0; i<permConfig.size(); i++) { 2176 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2177 BasePermission bp = mSettings.mPermissions.get(perm.name); 2178 if (bp == null) { 2179 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2180 mSettings.mPermissions.put(perm.name, bp); 2181 } 2182 if (perm.gids != null) { 2183 bp.setGids(perm.gids, perm.perUser); 2184 } 2185 } 2186 2187 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2188 for (int i=0; i<libConfig.size(); i++) { 2189 mSharedLibraries.put(libConfig.keyAt(i), 2190 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2191 } 2192 2193 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2194 2195 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2196 2197 if (mFirstBoot) { 2198 requestCopyPreoptedFiles(); 2199 } 2200 2201 String customResolverActivity = Resources.getSystem().getString( 2202 R.string.config_customResolverActivity); 2203 if (TextUtils.isEmpty(customResolverActivity)) { 2204 customResolverActivity = null; 2205 } else { 2206 mCustomResolverComponentName = ComponentName.unflattenFromString( 2207 customResolverActivity); 2208 } 2209 2210 long startTime = SystemClock.uptimeMillis(); 2211 2212 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2213 startTime); 2214 2215 // Set flag to monitor and not change apk file paths when 2216 // scanning install directories. 2217 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2218 2219 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2220 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2221 2222 if (bootClassPath == null) { 2223 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2224 } 2225 2226 if (systemServerClassPath == null) { 2227 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2228 } 2229 2230 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2231 final String[] dexCodeInstructionSets = 2232 getDexCodeInstructionSets( 2233 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2234 2235 /** 2236 * Ensure all external libraries have had dexopt run on them. 2237 */ 2238 if (mSharedLibraries.size() > 0) { 2239 // NOTE: For now, we're compiling these system "shared libraries" 2240 // (and framework jars) into all available architectures. It's possible 2241 // to compile them only when we come across an app that uses them (there's 2242 // already logic for that in scanPackageLI) but that adds some complexity. 2243 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2244 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2245 final String lib = libEntry.path; 2246 if (lib == null) { 2247 continue; 2248 } 2249 2250 try { 2251 // Shared libraries do not have profiles so we perform a full 2252 // AOT compilation (if needed). 2253 int dexoptNeeded = DexFile.getDexOptNeeded( 2254 lib, dexCodeInstructionSet, 2255 getCompilerFilterForReason(REASON_SHARED_APK), 2256 false /* newProfile */); 2257 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2258 mInstaller.dexopt(lib, Process.SYSTEM_UID, "*", 2259 dexCodeInstructionSet, dexoptNeeded, null, 2260 DEXOPT_PUBLIC, 2261 getCompilerFilterForReason(REASON_SHARED_APK), 2262 StorageManager.UUID_PRIVATE_INTERNAL, 2263 SKIP_SHARED_LIBRARY_CHECK); 2264 } 2265 } catch (FileNotFoundException e) { 2266 Slog.w(TAG, "Library not found: " + lib); 2267 } catch (IOException | InstallerException e) { 2268 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2269 + e.getMessage()); 2270 } 2271 } 2272 } 2273 } 2274 2275 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2276 2277 final VersionInfo ver = mSettings.getInternalVersion(); 2278 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2279 2280 // when upgrading from pre-M, promote system app permissions from install to runtime 2281 mPromoteSystemApps = 2282 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2283 2284 // When upgrading from pre-N, we need to handle package extraction like first boot, 2285 // as there is no profiling data available. 2286 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2287 2288 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2289 2290 // save off the names of pre-existing system packages prior to scanning; we don't 2291 // want to automatically grant runtime permissions for new system apps 2292 if (mPromoteSystemApps) { 2293 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2294 while (pkgSettingIter.hasNext()) { 2295 PackageSetting ps = pkgSettingIter.next(); 2296 if (isSystemApp(ps)) { 2297 mExistingSystemPackages.add(ps.name); 2298 } 2299 } 2300 } 2301 2302 // Collect vendor overlay packages. 2303 // (Do this before scanning any apps.) 2304 // For security and version matching reason, only consider 2305 // overlay packages if they reside in the right directory. 2306 File vendorOverlayDir; 2307 String overlaySkuDir = SystemProperties.get(VENDOR_OVERLAY_SKU_PROPERTY); 2308 if (!overlaySkuDir.isEmpty()) { 2309 vendorOverlayDir = new File(VENDOR_OVERLAY_DIR, overlaySkuDir); 2310 } else { 2311 vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2312 } 2313 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2314 | PackageParser.PARSE_IS_SYSTEM 2315 | PackageParser.PARSE_IS_SYSTEM_DIR 2316 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2317 2318 // Find base frameworks (resource packages without code). 2319 scanDirTracedLI(frameworkDir, mDefParseFlags 2320 | PackageParser.PARSE_IS_SYSTEM 2321 | PackageParser.PARSE_IS_SYSTEM_DIR 2322 | PackageParser.PARSE_IS_PRIVILEGED, 2323 scanFlags | SCAN_NO_DEX, 0); 2324 2325 // Collected privileged system packages. 2326 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2327 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2328 | PackageParser.PARSE_IS_SYSTEM 2329 | PackageParser.PARSE_IS_SYSTEM_DIR 2330 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2331 2332 // Collect ordinary system packages. 2333 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2334 scanDirTracedLI(systemAppDir, mDefParseFlags 2335 | PackageParser.PARSE_IS_SYSTEM 2336 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2337 2338 // Collect all vendor packages. 2339 File vendorAppDir = new File("/vendor/app"); 2340 try { 2341 vendorAppDir = vendorAppDir.getCanonicalFile(); 2342 } catch (IOException e) { 2343 // failed to look up canonical path, continue with original one 2344 } 2345 scanDirTracedLI(vendorAppDir, mDefParseFlags 2346 | PackageParser.PARSE_IS_SYSTEM 2347 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2348 2349 // Collect all OEM packages. 2350 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2351 scanDirTracedLI(oemAppDir, mDefParseFlags 2352 | PackageParser.PARSE_IS_SYSTEM 2353 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2354 2355 // Prune any system packages that no longer exist. 2356 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2357 if (!mOnlyCore) { 2358 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2359 while (psit.hasNext()) { 2360 PackageSetting ps = psit.next(); 2361 2362 /* 2363 * If this is not a system app, it can't be a 2364 * disable system app. 2365 */ 2366 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2367 continue; 2368 } 2369 2370 /* 2371 * If the package is scanned, it's not erased. 2372 */ 2373 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2374 if (scannedPkg != null) { 2375 /* 2376 * If the system app is both scanned and in the 2377 * disabled packages list, then it must have been 2378 * added via OTA. Remove it from the currently 2379 * scanned package so the previously user-installed 2380 * application can be scanned. 2381 */ 2382 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2383 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2384 + ps.name + "; removing system app. Last known codePath=" 2385 + ps.codePathString + ", installStatus=" + ps.installStatus 2386 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2387 + scannedPkg.mVersionCode); 2388 removePackageLI(scannedPkg, true); 2389 mExpectingBetter.put(ps.name, ps.codePath); 2390 } 2391 2392 continue; 2393 } 2394 2395 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2396 psit.remove(); 2397 logCriticalInfo(Log.WARN, "System package " + ps.name 2398 + " no longer exists; it's data will be wiped"); 2399 // Actual deletion of code and data will be handled by later 2400 // reconciliation step 2401 } else { 2402 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2403 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2404 possiblyDeletedUpdatedSystemApps.add(ps.name); 2405 } 2406 } 2407 } 2408 } 2409 2410 //look for any incomplete package installations 2411 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2412 for (int i = 0; i < deletePkgsList.size(); i++) { 2413 // Actual deletion of code and data will be handled by later 2414 // reconciliation step 2415 final String packageName = deletePkgsList.get(i).name; 2416 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2417 synchronized (mPackages) { 2418 mSettings.removePackageLPw(packageName); 2419 } 2420 } 2421 2422 //delete tmp files 2423 deleteTempPackageFiles(); 2424 2425 // Remove any shared userIDs that have no associated packages 2426 mSettings.pruneSharedUsersLPw(); 2427 2428 if (!mOnlyCore) { 2429 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2430 SystemClock.uptimeMillis()); 2431 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2432 2433 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2434 | PackageParser.PARSE_FORWARD_LOCK, 2435 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2436 2437 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2438 | PackageParser.PARSE_IS_EPHEMERAL, 2439 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2440 2441 /** 2442 * Remove disable package settings for any updated system 2443 * apps that were removed via an OTA. If they're not a 2444 * previously-updated app, remove them completely. 2445 * Otherwise, just revoke their system-level permissions. 2446 */ 2447 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2448 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2449 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2450 2451 String msg; 2452 if (deletedPkg == null) { 2453 msg = "Updated system package " + deletedAppName 2454 + " no longer exists; it's data will be wiped"; 2455 // Actual deletion of code and data will be handled by later 2456 // reconciliation step 2457 } else { 2458 msg = "Updated system app + " + deletedAppName 2459 + " no longer present; removing system privileges for " 2460 + deletedAppName; 2461 2462 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2463 2464 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2465 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2466 } 2467 logCriticalInfo(Log.WARN, msg); 2468 } 2469 2470 /** 2471 * Make sure all system apps that we expected to appear on 2472 * the userdata partition actually showed up. If they never 2473 * appeared, crawl back and revive the system version. 2474 */ 2475 for (int i = 0; i < mExpectingBetter.size(); i++) { 2476 final String packageName = mExpectingBetter.keyAt(i); 2477 if (!mPackages.containsKey(packageName)) { 2478 final File scanFile = mExpectingBetter.valueAt(i); 2479 2480 logCriticalInfo(Log.WARN, "Expected better " + packageName 2481 + " but never showed up; reverting to system"); 2482 2483 int reparseFlags = mDefParseFlags; 2484 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2485 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2486 | PackageParser.PARSE_IS_SYSTEM_DIR 2487 | PackageParser.PARSE_IS_PRIVILEGED; 2488 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2489 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2490 | PackageParser.PARSE_IS_SYSTEM_DIR; 2491 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2492 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2493 | PackageParser.PARSE_IS_SYSTEM_DIR; 2494 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2495 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2496 | PackageParser.PARSE_IS_SYSTEM_DIR; 2497 } else { 2498 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2499 continue; 2500 } 2501 2502 mSettings.enableSystemPackageLPw(packageName); 2503 2504 try { 2505 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2506 } catch (PackageManagerException e) { 2507 Slog.e(TAG, "Failed to parse original system package: " 2508 + e.getMessage()); 2509 } 2510 } 2511 } 2512 } 2513 mExpectingBetter.clear(); 2514 2515 // Resolve the storage manager. 2516 mStorageManagerPackage = getStorageManagerPackageName(); 2517 2518 // Resolve protected action filters. Only the setup wizard is allowed to 2519 // have a high priority filter for these actions. 2520 mSetupWizardPackage = getSetupWizardPackageName(); 2521 if (mProtectedFilters.size() > 0) { 2522 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2523 Slog.i(TAG, "No setup wizard;" 2524 + " All protected intents capped to priority 0"); 2525 } 2526 for (ActivityIntentInfo filter : mProtectedFilters) { 2527 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2528 if (DEBUG_FILTERS) { 2529 Slog.i(TAG, "Found setup wizard;" 2530 + " allow priority " + filter.getPriority() + ";" 2531 + " package: " + filter.activity.info.packageName 2532 + " activity: " + filter.activity.className 2533 + " priority: " + filter.getPriority()); 2534 } 2535 // skip setup wizard; allow it to keep the high priority filter 2536 continue; 2537 } 2538 Slog.w(TAG, "Protected action; cap priority to 0;" 2539 + " package: " + filter.activity.info.packageName 2540 + " activity: " + filter.activity.className 2541 + " origPrio: " + filter.getPriority()); 2542 filter.setPriority(0); 2543 } 2544 } 2545 mDeferProtectedFilters = false; 2546 mProtectedFilters.clear(); 2547 2548 // Now that we know all of the shared libraries, update all clients to have 2549 // the correct library paths. 2550 updateAllSharedLibrariesLPw(); 2551 2552 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2553 // NOTE: We ignore potential failures here during a system scan (like 2554 // the rest of the commands above) because there's precious little we 2555 // can do about it. A settings error is reported, though. 2556 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2557 false /* boot complete */); 2558 } 2559 2560 // Now that we know all the packages we are keeping, 2561 // read and update their last usage times. 2562 mPackageUsage.read(mPackages); 2563 mCompilerStats.read(); 2564 2565 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2566 SystemClock.uptimeMillis()); 2567 Slog.i(TAG, "Time to scan packages: " 2568 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2569 + " seconds"); 2570 2571 // If the platform SDK has changed since the last time we booted, 2572 // we need to re-grant app permission to catch any new ones that 2573 // appear. This is really a hack, and means that apps can in some 2574 // cases get permissions that the user didn't initially explicitly 2575 // allow... it would be nice to have some better way to handle 2576 // this situation. 2577 int updateFlags = UPDATE_PERMISSIONS_ALL; 2578 if (ver.sdkVersion != mSdkVersion) { 2579 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2580 + mSdkVersion + "; regranting permissions for internal storage"); 2581 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2582 } 2583 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2584 ver.sdkVersion = mSdkVersion; 2585 2586 // If this is the first boot or an update from pre-M, and it is a normal 2587 // boot, then we need to initialize the default preferred apps across 2588 // all defined users. 2589 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2590 for (UserInfo user : sUserManager.getUsers(true)) { 2591 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2592 applyFactoryDefaultBrowserLPw(user.id); 2593 primeDomainVerificationsLPw(user.id); 2594 } 2595 } 2596 2597 // Prepare storage for system user really early during boot, 2598 // since core system apps like SettingsProvider and SystemUI 2599 // can't wait for user to start 2600 final int storageFlags; 2601 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2602 storageFlags = StorageManager.FLAG_STORAGE_DE; 2603 } else { 2604 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2605 } 2606 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2607 storageFlags); 2608 2609 // If this is first boot after an OTA, and a normal boot, then 2610 // we need to clear code cache directories. 2611 // Note that we do *not* clear the application profiles. These remain valid 2612 // across OTAs and are used to drive profile verification (post OTA) and 2613 // profile compilation (without waiting to collect a fresh set of profiles). 2614 if (mIsUpgrade && !onlyCore) { 2615 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2616 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2617 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2618 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2619 // No apps are running this early, so no need to freeze 2620 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2621 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2622 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2623 } 2624 } 2625 ver.fingerprint = Build.FINGERPRINT; 2626 } 2627 2628 checkDefaultBrowser(); 2629 2630 // clear only after permissions and other defaults have been updated 2631 mExistingSystemPackages.clear(); 2632 mPromoteSystemApps = false; 2633 2634 // All the changes are done during package scanning. 2635 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2636 2637 // can downgrade to reader 2638 mSettings.writeLPr(); 2639 2640 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2641 // early on (before the package manager declares itself as early) because other 2642 // components in the system server might ask for package contexts for these apps. 2643 // 2644 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2645 // (i.e, that the data partition is unavailable). 2646 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2647 long start = System.nanoTime(); 2648 List<PackageParser.Package> coreApps = new ArrayList<>(); 2649 for (PackageParser.Package pkg : mPackages.values()) { 2650 if (pkg.coreApp) { 2651 coreApps.add(pkg); 2652 } 2653 } 2654 2655 int[] stats = performDexOptUpgrade(coreApps, false, 2656 getCompilerFilterForReason(REASON_CORE_APP)); 2657 2658 final int elapsedTimeSeconds = 2659 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2660 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2661 2662 if (DEBUG_DEXOPT) { 2663 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2664 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2665 } 2666 2667 2668 // TODO: Should we log these stats to tron too ? 2669 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2670 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2671 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2672 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2673 } 2674 2675 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2676 SystemClock.uptimeMillis()); 2677 2678 if (!mOnlyCore) { 2679 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2680 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2681 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2682 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2683 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2684 mIntentFilterVerifierComponent); 2685 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2686 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2687 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2688 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2689 } else { 2690 mRequiredVerifierPackage = null; 2691 mRequiredInstallerPackage = null; 2692 mRequiredUninstallerPackage = null; 2693 mIntentFilterVerifierComponent = null; 2694 mIntentFilterVerifier = null; 2695 mServicesSystemSharedLibraryPackageName = null; 2696 mSharedSystemSharedLibraryPackageName = null; 2697 } 2698 2699 mInstallerService = new PackageInstallerService(context, this); 2700 2701 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2702 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2703 // both the installer and resolver must be present to enable ephemeral 2704 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2705 if (DEBUG_EPHEMERAL) { 2706 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2707 + " installer:" + ephemeralInstallerComponent); 2708 } 2709 mEphemeralResolverComponent = ephemeralResolverComponent; 2710 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2711 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2712 mEphemeralResolverConnection = 2713 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2714 } else { 2715 if (DEBUG_EPHEMERAL) { 2716 final String missingComponent = 2717 (ephemeralResolverComponent == null) 2718 ? (ephemeralInstallerComponent == null) 2719 ? "resolver and installer" 2720 : "resolver" 2721 : "installer"; 2722 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2723 } 2724 mEphemeralResolverComponent = null; 2725 mEphemeralInstallerComponent = null; 2726 mEphemeralResolverConnection = null; 2727 } 2728 2729 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2730 2731 // Read and update the usage of dex files. 2732 // Do this at the end of PM init so that all the packages have their 2733 // data directory reconciled. 2734 // At this point we know the code paths of the packages, so we can validate 2735 // the disk file and build the internal cache. 2736 // The usage file is expected to be small so loading and verifying it 2737 // should take a fairly small time compare to the other activities (e.g. package 2738 // scanning). 2739 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2740 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2741 for (int userId : currentUserIds) { 2742 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2743 } 2744 mDexManager.load(userPackages); 2745 } // synchronized (mPackages) 2746 } // synchronized (mInstallLock) 2747 2748 // Now after opening every single application zip, make sure they 2749 // are all flushed. Not really needed, but keeps things nice and 2750 // tidy. 2751 Runtime.getRuntime().gc(); 2752 2753 // The initial scanning above does many calls into installd while 2754 // holding the mPackages lock, but we're mostly interested in yelling 2755 // once we have a booted system. 2756 mInstaller.setWarnIfHeld(mPackages); 2757 2758 // Expose private service for system components to use. 2759 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2760 } 2761 2762 @Override 2763 public boolean isFirstBoot() { 2764 return mFirstBoot; 2765 } 2766 2767 @Override 2768 public boolean isOnlyCoreApps() { 2769 return mOnlyCore; 2770 } 2771 2772 @Override 2773 public boolean isUpgrade() { 2774 return mIsUpgrade; 2775 } 2776 2777 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2778 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2779 2780 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2781 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2782 UserHandle.USER_SYSTEM); 2783 if (matches.size() == 1) { 2784 return matches.get(0).getComponentInfo().packageName; 2785 } else if (matches.size() == 0) { 2786 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2787 return null; 2788 } 2789 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2790 } 2791 2792 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2793 synchronized (mPackages) { 2794 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2795 if (libraryEntry == null) { 2796 throw new IllegalStateException("Missing required shared library:" + libraryName); 2797 } 2798 return libraryEntry.apk; 2799 } 2800 } 2801 2802 private @NonNull String getRequiredInstallerLPr() { 2803 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2804 intent.addCategory(Intent.CATEGORY_DEFAULT); 2805 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2806 2807 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2808 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2809 UserHandle.USER_SYSTEM); 2810 if (matches.size() == 1) { 2811 ResolveInfo resolveInfo = matches.get(0); 2812 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2813 throw new RuntimeException("The installer must be a privileged app"); 2814 } 2815 return matches.get(0).getComponentInfo().packageName; 2816 } else { 2817 throw new RuntimeException("There must be exactly one installer; found " + matches); 2818 } 2819 } 2820 2821 private @NonNull String getRequiredUninstallerLPr() { 2822 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2823 intent.addCategory(Intent.CATEGORY_DEFAULT); 2824 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2825 2826 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2827 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2828 UserHandle.USER_SYSTEM); 2829 if (resolveInfo == null || 2830 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2831 throw new RuntimeException("There must be exactly one uninstaller; found " 2832 + resolveInfo); 2833 } 2834 return resolveInfo.getComponentInfo().packageName; 2835 } 2836 2837 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2838 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2839 2840 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2841 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2842 UserHandle.USER_SYSTEM); 2843 ResolveInfo best = null; 2844 final int N = matches.size(); 2845 for (int i = 0; i < N; i++) { 2846 final ResolveInfo cur = matches.get(i); 2847 final String packageName = cur.getComponentInfo().packageName; 2848 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2849 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2850 continue; 2851 } 2852 2853 if (best == null || cur.priority > best.priority) { 2854 best = cur; 2855 } 2856 } 2857 2858 if (best != null) { 2859 return best.getComponentInfo().getComponentName(); 2860 } else { 2861 throw new RuntimeException("There must be at least one intent filter verifier"); 2862 } 2863 } 2864 2865 private @Nullable ComponentName getEphemeralResolverLPr() { 2866 final String[] packageArray = 2867 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2868 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2869 if (DEBUG_EPHEMERAL) { 2870 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2871 } 2872 return null; 2873 } 2874 2875 final int resolveFlags = 2876 MATCH_DIRECT_BOOT_AWARE 2877 | MATCH_DIRECT_BOOT_UNAWARE 2878 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2879 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2880 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2881 resolveFlags, UserHandle.USER_SYSTEM); 2882 2883 final int N = resolvers.size(); 2884 if (N == 0) { 2885 if (DEBUG_EPHEMERAL) { 2886 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2887 } 2888 return null; 2889 } 2890 2891 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2892 for (int i = 0; i < N; i++) { 2893 final ResolveInfo info = resolvers.get(i); 2894 2895 if (info.serviceInfo == null) { 2896 continue; 2897 } 2898 2899 final String packageName = info.serviceInfo.packageName; 2900 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2901 if (DEBUG_EPHEMERAL) { 2902 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2903 + " pkg: " + packageName + ", info:" + info); 2904 } 2905 continue; 2906 } 2907 2908 if (DEBUG_EPHEMERAL) { 2909 Slog.v(TAG, "Ephemeral resolver found;" 2910 + " pkg: " + packageName + ", info:" + info); 2911 } 2912 return new ComponentName(packageName, info.serviceInfo.name); 2913 } 2914 if (DEBUG_EPHEMERAL) { 2915 Slog.v(TAG, "Ephemeral resolver NOT found"); 2916 } 2917 return null; 2918 } 2919 2920 private @Nullable ComponentName getEphemeralInstallerLPr() { 2921 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2922 intent.addCategory(Intent.CATEGORY_DEFAULT); 2923 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2924 2925 final int resolveFlags = 2926 MATCH_DIRECT_BOOT_AWARE 2927 | MATCH_DIRECT_BOOT_UNAWARE 2928 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2929 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2930 resolveFlags, UserHandle.USER_SYSTEM); 2931 if (matches.size() == 0) { 2932 return null; 2933 } else if (matches.size() == 1) { 2934 return matches.get(0).getComponentInfo().getComponentName(); 2935 } else { 2936 throw new RuntimeException( 2937 "There must be at most one ephemeral installer; found " + matches); 2938 } 2939 } 2940 2941 private void primeDomainVerificationsLPw(int userId) { 2942 if (DEBUG_DOMAIN_VERIFICATION) { 2943 Slog.d(TAG, "Priming domain verifications in user " + userId); 2944 } 2945 2946 SystemConfig systemConfig = SystemConfig.getInstance(); 2947 ArraySet<String> packages = systemConfig.getLinkedApps(); 2948 ArraySet<String> domains = new ArraySet<String>(); 2949 2950 for (String packageName : packages) { 2951 PackageParser.Package pkg = mPackages.get(packageName); 2952 if (pkg != null) { 2953 if (!pkg.isSystemApp()) { 2954 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2955 continue; 2956 } 2957 2958 domains.clear(); 2959 for (PackageParser.Activity a : pkg.activities) { 2960 for (ActivityIntentInfo filter : a.intents) { 2961 if (hasValidDomains(filter)) { 2962 domains.addAll(filter.getHostsList()); 2963 } 2964 } 2965 } 2966 2967 if (domains.size() > 0) { 2968 if (DEBUG_DOMAIN_VERIFICATION) { 2969 Slog.v(TAG, " + " + packageName); 2970 } 2971 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2972 // state w.r.t. the formal app-linkage "no verification attempted" state; 2973 // and then 'always' in the per-user state actually used for intent resolution. 2974 final IntentFilterVerificationInfo ivi; 2975 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2976 new ArrayList<String>(domains)); 2977 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2978 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2979 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2980 } else { 2981 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2982 + "' does not handle web links"); 2983 } 2984 } else { 2985 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2986 } 2987 } 2988 2989 scheduleWritePackageRestrictionsLocked(userId); 2990 scheduleWriteSettingsLocked(); 2991 } 2992 2993 private void applyFactoryDefaultBrowserLPw(int userId) { 2994 // The default browser app's package name is stored in a string resource, 2995 // with a product-specific overlay used for vendor customization. 2996 String browserPkg = mContext.getResources().getString( 2997 com.android.internal.R.string.default_browser); 2998 if (!TextUtils.isEmpty(browserPkg)) { 2999 // non-empty string => required to be a known package 3000 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3001 if (ps == null) { 3002 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3003 browserPkg = null; 3004 } else { 3005 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3006 } 3007 } 3008 3009 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3010 // default. If there's more than one, just leave everything alone. 3011 if (browserPkg == null) { 3012 calculateDefaultBrowserLPw(userId); 3013 } 3014 } 3015 3016 private void calculateDefaultBrowserLPw(int userId) { 3017 List<String> allBrowsers = resolveAllBrowserApps(userId); 3018 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3019 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3020 } 3021 3022 private List<String> resolveAllBrowserApps(int userId) { 3023 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3024 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3025 PackageManager.MATCH_ALL, userId); 3026 3027 final int count = list.size(); 3028 List<String> result = new ArrayList<String>(count); 3029 for (int i=0; i<count; i++) { 3030 ResolveInfo info = list.get(i); 3031 if (info.activityInfo == null 3032 || !info.handleAllWebDataURI 3033 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3034 || result.contains(info.activityInfo.packageName)) { 3035 continue; 3036 } 3037 result.add(info.activityInfo.packageName); 3038 } 3039 3040 return result; 3041 } 3042 3043 private boolean packageIsBrowser(String packageName, int userId) { 3044 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3045 PackageManager.MATCH_ALL, userId); 3046 final int N = list.size(); 3047 for (int i = 0; i < N; i++) { 3048 ResolveInfo info = list.get(i); 3049 if (packageName.equals(info.activityInfo.packageName)) { 3050 return true; 3051 } 3052 } 3053 return false; 3054 } 3055 3056 private void checkDefaultBrowser() { 3057 final int myUserId = UserHandle.myUserId(); 3058 final String packageName = getDefaultBrowserPackageName(myUserId); 3059 if (packageName != null) { 3060 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3061 if (info == null) { 3062 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3063 synchronized (mPackages) { 3064 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3065 } 3066 } 3067 } 3068 } 3069 3070 @Override 3071 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3072 throws RemoteException { 3073 try { 3074 return super.onTransact(code, data, reply, flags); 3075 } catch (RuntimeException e) { 3076 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3077 Slog.wtf(TAG, "Package Manager Crash", e); 3078 } 3079 throw e; 3080 } 3081 } 3082 3083 static int[] appendInts(int[] cur, int[] add) { 3084 if (add == null) return cur; 3085 if (cur == null) return add; 3086 final int N = add.length; 3087 for (int i=0; i<N; i++) { 3088 cur = appendInt(cur, add[i]); 3089 } 3090 return cur; 3091 } 3092 3093 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3094 if (!sUserManager.exists(userId)) return null; 3095 if (ps == null) { 3096 return null; 3097 } 3098 final PackageParser.Package p = ps.pkg; 3099 if (p == null) { 3100 return null; 3101 } 3102 3103 final PermissionsState permissionsState = ps.getPermissionsState(); 3104 3105 // Compute GIDs only if requested 3106 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3107 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3108 // Compute granted permissions only if package has requested permissions 3109 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3110 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3111 final PackageUserState state = ps.readUserState(userId); 3112 3113 return PackageParser.generatePackageInfo(p, gids, flags, 3114 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3115 } 3116 3117 @Override 3118 public void checkPackageStartable(String packageName, int userId) { 3119 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3120 3121 synchronized (mPackages) { 3122 final PackageSetting ps = mSettings.mPackages.get(packageName); 3123 if (ps == null) { 3124 throw new SecurityException("Package " + packageName + " was not found!"); 3125 } 3126 3127 if (!ps.getInstalled(userId)) { 3128 throw new SecurityException( 3129 "Package " + packageName + " was not installed for user " + userId + "!"); 3130 } 3131 3132 if (mSafeMode && !ps.isSystem()) { 3133 throw new SecurityException("Package " + packageName + " not a system app!"); 3134 } 3135 3136 if (mFrozenPackages.contains(packageName)) { 3137 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3138 } 3139 3140 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3141 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3142 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3143 } 3144 } 3145 } 3146 3147 @Override 3148 public boolean isPackageAvailable(String packageName, int userId) { 3149 if (!sUserManager.exists(userId)) return false; 3150 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3151 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3152 synchronized (mPackages) { 3153 PackageParser.Package p = mPackages.get(packageName); 3154 if (p != null) { 3155 final PackageSetting ps = (PackageSetting) p.mExtras; 3156 if (ps != null) { 3157 final PackageUserState state = ps.readUserState(userId); 3158 if (state != null) { 3159 return PackageParser.isAvailable(state); 3160 } 3161 } 3162 } 3163 } 3164 return false; 3165 } 3166 3167 @Override 3168 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3169 if (!sUserManager.exists(userId)) return null; 3170 flags = updateFlagsForPackage(flags, userId, packageName); 3171 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3172 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3173 // reader 3174 synchronized (mPackages) { 3175 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3176 PackageParser.Package p = null; 3177 if (matchFactoryOnly) { 3178 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3179 if (ps != null) { 3180 return generatePackageInfo(ps, flags, userId); 3181 } 3182 } 3183 if (p == null) { 3184 p = mPackages.get(packageName); 3185 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3186 return null; 3187 } 3188 } 3189 if (DEBUG_PACKAGE_INFO) 3190 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3191 if (p != null) { 3192 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3193 } 3194 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3195 final PackageSetting ps = mSettings.mPackages.get(packageName); 3196 return generatePackageInfo(ps, flags, userId); 3197 } 3198 } 3199 return null; 3200 } 3201 3202 @Override 3203 public String[] currentToCanonicalPackageNames(String[] names) { 3204 String[] out = new String[names.length]; 3205 // reader 3206 synchronized (mPackages) { 3207 for (int i=names.length-1; i>=0; i--) { 3208 PackageSetting ps = mSettings.mPackages.get(names[i]); 3209 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3210 } 3211 } 3212 return out; 3213 } 3214 3215 @Override 3216 public String[] canonicalToCurrentPackageNames(String[] names) { 3217 String[] out = new String[names.length]; 3218 // reader 3219 synchronized (mPackages) { 3220 for (int i=names.length-1; i>=0; i--) { 3221 String cur = mSettings.mRenamedPackages.get(names[i]); 3222 out[i] = cur != null ? cur : names[i]; 3223 } 3224 } 3225 return out; 3226 } 3227 3228 @Override 3229 public int getPackageUid(String packageName, int flags, int userId) { 3230 if (!sUserManager.exists(userId)) return -1; 3231 flags = updateFlagsForPackage(flags, userId, packageName); 3232 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3233 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3234 3235 // reader 3236 synchronized (mPackages) { 3237 final PackageParser.Package p = mPackages.get(packageName); 3238 if (p != null && p.isMatch(flags)) { 3239 return UserHandle.getUid(userId, p.applicationInfo.uid); 3240 } 3241 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3242 final PackageSetting ps = mSettings.mPackages.get(packageName); 3243 if (ps != null && ps.isMatch(flags)) { 3244 return UserHandle.getUid(userId, ps.appId); 3245 } 3246 } 3247 } 3248 3249 return -1; 3250 } 3251 3252 @Override 3253 public int[] getPackageGids(String packageName, int flags, int userId) { 3254 if (!sUserManager.exists(userId)) return null; 3255 flags = updateFlagsForPackage(flags, userId, packageName); 3256 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3257 false /* requireFullPermission */, false /* checkShell */, 3258 "getPackageGids"); 3259 3260 // reader 3261 synchronized (mPackages) { 3262 final PackageParser.Package p = mPackages.get(packageName); 3263 if (p != null && p.isMatch(flags)) { 3264 PackageSetting ps = (PackageSetting) p.mExtras; 3265 return ps.getPermissionsState().computeGids(userId); 3266 } 3267 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3268 final PackageSetting ps = mSettings.mPackages.get(packageName); 3269 if (ps != null && ps.isMatch(flags)) { 3270 return ps.getPermissionsState().computeGids(userId); 3271 } 3272 } 3273 } 3274 3275 return null; 3276 } 3277 3278 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3279 if (bp.perm != null) { 3280 return PackageParser.generatePermissionInfo(bp.perm, flags); 3281 } 3282 PermissionInfo pi = new PermissionInfo(); 3283 pi.name = bp.name; 3284 pi.packageName = bp.sourcePackage; 3285 pi.nonLocalizedLabel = bp.name; 3286 pi.protectionLevel = bp.protectionLevel; 3287 return pi; 3288 } 3289 3290 @Override 3291 public PermissionInfo getPermissionInfo(String name, int flags) { 3292 // reader 3293 synchronized (mPackages) { 3294 final BasePermission p = mSettings.mPermissions.get(name); 3295 if (p != null) { 3296 return generatePermissionInfo(p, flags); 3297 } 3298 return null; 3299 } 3300 } 3301 3302 @Override 3303 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3304 int flags) { 3305 // reader 3306 synchronized (mPackages) { 3307 if (group != null && !mPermissionGroups.containsKey(group)) { 3308 // This is thrown as NameNotFoundException 3309 return null; 3310 } 3311 3312 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3313 for (BasePermission p : mSettings.mPermissions.values()) { 3314 if (group == null) { 3315 if (p.perm == null || p.perm.info.group == null) { 3316 out.add(generatePermissionInfo(p, flags)); 3317 } 3318 } else { 3319 if (p.perm != null && group.equals(p.perm.info.group)) { 3320 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3321 } 3322 } 3323 } 3324 return new ParceledListSlice<>(out); 3325 } 3326 } 3327 3328 @Override 3329 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3330 // reader 3331 synchronized (mPackages) { 3332 return PackageParser.generatePermissionGroupInfo( 3333 mPermissionGroups.get(name), flags); 3334 } 3335 } 3336 3337 @Override 3338 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3339 // reader 3340 synchronized (mPackages) { 3341 final int N = mPermissionGroups.size(); 3342 ArrayList<PermissionGroupInfo> out 3343 = new ArrayList<PermissionGroupInfo>(N); 3344 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3345 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3346 } 3347 return new ParceledListSlice<>(out); 3348 } 3349 } 3350 3351 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3352 int userId) { 3353 if (!sUserManager.exists(userId)) return null; 3354 PackageSetting ps = mSettings.mPackages.get(packageName); 3355 if (ps != null) { 3356 if (ps.pkg == null) { 3357 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3358 if (pInfo != null) { 3359 return pInfo.applicationInfo; 3360 } 3361 return null; 3362 } 3363 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3364 ps.readUserState(userId), userId); 3365 } 3366 return null; 3367 } 3368 3369 @Override 3370 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3371 if (!sUserManager.exists(userId)) return null; 3372 flags = updateFlagsForApplication(flags, userId, packageName); 3373 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3374 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3375 // writer 3376 synchronized (mPackages) { 3377 PackageParser.Package p = mPackages.get(packageName); 3378 if (DEBUG_PACKAGE_INFO) Log.v( 3379 TAG, "getApplicationInfo " + packageName 3380 + ": " + p); 3381 if (p != null) { 3382 PackageSetting ps = mSettings.mPackages.get(packageName); 3383 if (ps == null) return null; 3384 // Note: isEnabledLP() does not apply here - always return info 3385 return PackageParser.generateApplicationInfo( 3386 p, flags, ps.readUserState(userId), userId); 3387 } 3388 if ("android".equals(packageName)||"system".equals(packageName)) { 3389 return mAndroidApplication; 3390 } 3391 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3392 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3393 } 3394 } 3395 return null; 3396 } 3397 3398 @Override 3399 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3400 final IPackageDataObserver observer) { 3401 mContext.enforceCallingOrSelfPermission( 3402 android.Manifest.permission.CLEAR_APP_CACHE, null); 3403 // Queue up an async operation since clearing cache may take a little while. 3404 mHandler.post(new Runnable() { 3405 public void run() { 3406 mHandler.removeCallbacks(this); 3407 boolean success = true; 3408 synchronized (mInstallLock) { 3409 try { 3410 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3411 } catch (InstallerException e) { 3412 Slog.w(TAG, "Couldn't clear application caches: " + e); 3413 success = false; 3414 } 3415 } 3416 if (observer != null) { 3417 try { 3418 observer.onRemoveCompleted(null, success); 3419 } catch (RemoteException e) { 3420 Slog.w(TAG, "RemoveException when invoking call back"); 3421 } 3422 } 3423 } 3424 }); 3425 } 3426 3427 @Override 3428 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3429 final IntentSender pi) { 3430 mContext.enforceCallingOrSelfPermission( 3431 android.Manifest.permission.CLEAR_APP_CACHE, null); 3432 // Queue up an async operation since clearing cache may take a little while. 3433 mHandler.post(new Runnable() { 3434 public void run() { 3435 mHandler.removeCallbacks(this); 3436 boolean success = true; 3437 synchronized (mInstallLock) { 3438 try { 3439 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3440 } catch (InstallerException e) { 3441 Slog.w(TAG, "Couldn't clear application caches: " + e); 3442 success = false; 3443 } 3444 } 3445 if(pi != null) { 3446 try { 3447 // Callback via pending intent 3448 int code = success ? 1 : 0; 3449 pi.sendIntent(null, code, null, 3450 null, null); 3451 } catch (SendIntentException e1) { 3452 Slog.i(TAG, "Failed to send pending intent"); 3453 } 3454 } 3455 } 3456 }); 3457 } 3458 3459 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3460 synchronized (mInstallLock) { 3461 try { 3462 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3463 } catch (InstallerException e) { 3464 throw new IOException("Failed to free enough space", e); 3465 } 3466 } 3467 } 3468 3469 /** 3470 * Update given flags based on encryption status of current user. 3471 */ 3472 private int updateFlags(int flags, int userId) { 3473 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3474 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3475 // Caller expressed an explicit opinion about what encryption 3476 // aware/unaware components they want to see, so fall through and 3477 // give them what they want 3478 } else { 3479 // Caller expressed no opinion, so match based on user state 3480 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3481 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3482 } else { 3483 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3484 } 3485 } 3486 return flags; 3487 } 3488 3489 private UserManagerInternal getUserManagerInternal() { 3490 if (mUserManagerInternal == null) { 3491 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3492 } 3493 return mUserManagerInternal; 3494 } 3495 3496 /** 3497 * Update given flags when being used to request {@link PackageInfo}. 3498 */ 3499 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3500 boolean triaged = true; 3501 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3502 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3503 // Caller is asking for component details, so they'd better be 3504 // asking for specific encryption matching behavior, or be triaged 3505 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3506 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3507 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3508 triaged = false; 3509 } 3510 } 3511 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3512 | PackageManager.MATCH_SYSTEM_ONLY 3513 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3514 triaged = false; 3515 } 3516 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3517 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3518 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3519 } 3520 return updateFlags(flags, userId); 3521 } 3522 3523 /** 3524 * Update given flags when being used to request {@link ApplicationInfo}. 3525 */ 3526 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3527 return updateFlagsForPackage(flags, userId, cookie); 3528 } 3529 3530 /** 3531 * Update given flags when being used to request {@link ComponentInfo}. 3532 */ 3533 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3534 if (cookie instanceof Intent) { 3535 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3536 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3537 } 3538 } 3539 3540 boolean triaged = true; 3541 // Caller is asking for component details, so they'd better be 3542 // asking for specific encryption matching behavior, or be triaged 3543 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3544 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3545 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3546 triaged = false; 3547 } 3548 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3549 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3550 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3551 } 3552 3553 return updateFlags(flags, userId); 3554 } 3555 3556 /** 3557 * Update given flags when being used to request {@link ResolveInfo}. 3558 */ 3559 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3560 // Safe mode means we shouldn't match any third-party components 3561 if (mSafeMode) { 3562 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3563 } 3564 3565 return updateFlagsForComponent(flags, userId, cookie); 3566 } 3567 3568 @Override 3569 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3570 if (!sUserManager.exists(userId)) return null; 3571 flags = updateFlagsForComponent(flags, userId, component); 3572 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3573 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3574 synchronized (mPackages) { 3575 PackageParser.Activity a = mActivities.mActivities.get(component); 3576 3577 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3578 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3579 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3580 if (ps == null) return null; 3581 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3582 userId); 3583 } 3584 if (mResolveComponentName.equals(component)) { 3585 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3586 new PackageUserState(), userId); 3587 } 3588 } 3589 return null; 3590 } 3591 3592 @Override 3593 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3594 String resolvedType) { 3595 synchronized (mPackages) { 3596 if (component.equals(mResolveComponentName)) { 3597 // The resolver supports EVERYTHING! 3598 return true; 3599 } 3600 PackageParser.Activity a = mActivities.mActivities.get(component); 3601 if (a == null) { 3602 return false; 3603 } 3604 for (int i=0; i<a.intents.size(); i++) { 3605 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3606 intent.getData(), intent.getCategories(), TAG) >= 0) { 3607 return true; 3608 } 3609 } 3610 return false; 3611 } 3612 } 3613 3614 @Override 3615 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3616 if (!sUserManager.exists(userId)) return null; 3617 flags = updateFlagsForComponent(flags, userId, component); 3618 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3619 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3620 synchronized (mPackages) { 3621 PackageParser.Activity a = mReceivers.mActivities.get(component); 3622 if (DEBUG_PACKAGE_INFO) Log.v( 3623 TAG, "getReceiverInfo " + component + ": " + a); 3624 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3625 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3626 if (ps == null) return null; 3627 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3628 userId); 3629 } 3630 } 3631 return null; 3632 } 3633 3634 @Override 3635 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3636 if (!sUserManager.exists(userId)) return null; 3637 flags = updateFlagsForComponent(flags, userId, component); 3638 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3639 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3640 synchronized (mPackages) { 3641 PackageParser.Service s = mServices.mServices.get(component); 3642 if (DEBUG_PACKAGE_INFO) Log.v( 3643 TAG, "getServiceInfo " + component + ": " + s); 3644 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3645 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3646 if (ps == null) return null; 3647 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3648 userId); 3649 } 3650 } 3651 return null; 3652 } 3653 3654 @Override 3655 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3656 if (!sUserManager.exists(userId)) return null; 3657 flags = updateFlagsForComponent(flags, userId, component); 3658 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3659 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3660 synchronized (mPackages) { 3661 PackageParser.Provider p = mProviders.mProviders.get(component); 3662 if (DEBUG_PACKAGE_INFO) Log.v( 3663 TAG, "getProviderInfo " + component + ": " + p); 3664 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3665 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3666 if (ps == null) return null; 3667 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3668 userId); 3669 } 3670 } 3671 return null; 3672 } 3673 3674 @Override 3675 public String[] getSystemSharedLibraryNames() { 3676 Set<String> libSet; 3677 synchronized (mPackages) { 3678 libSet = mSharedLibraries.keySet(); 3679 int size = libSet.size(); 3680 if (size > 0) { 3681 String[] libs = new String[size]; 3682 libSet.toArray(libs); 3683 return libs; 3684 } 3685 } 3686 return null; 3687 } 3688 3689 @Override 3690 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3691 synchronized (mPackages) { 3692 return mServicesSystemSharedLibraryPackageName; 3693 } 3694 } 3695 3696 @Override 3697 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3698 synchronized (mPackages) { 3699 return mSharedSystemSharedLibraryPackageName; 3700 } 3701 } 3702 3703 @Override 3704 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3705 synchronized (mPackages) { 3706 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3707 3708 final FeatureInfo fi = new FeatureInfo(); 3709 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3710 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3711 res.add(fi); 3712 3713 return new ParceledListSlice<>(res); 3714 } 3715 } 3716 3717 @Override 3718 public boolean hasSystemFeature(String name, int version) { 3719 synchronized (mPackages) { 3720 final FeatureInfo feat = mAvailableFeatures.get(name); 3721 if (feat == null) { 3722 return false; 3723 } else { 3724 return feat.version >= version; 3725 } 3726 } 3727 } 3728 3729 @Override 3730 public int checkPermission(String permName, String pkgName, int userId) { 3731 if (!sUserManager.exists(userId)) { 3732 return PackageManager.PERMISSION_DENIED; 3733 } 3734 3735 synchronized (mPackages) { 3736 final PackageParser.Package p = mPackages.get(pkgName); 3737 if (p != null && p.mExtras != null) { 3738 final PackageSetting ps = (PackageSetting) p.mExtras; 3739 final PermissionsState permissionsState = ps.getPermissionsState(); 3740 if (permissionsState.hasPermission(permName, userId)) { 3741 return PackageManager.PERMISSION_GRANTED; 3742 } 3743 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3744 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3745 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3746 return PackageManager.PERMISSION_GRANTED; 3747 } 3748 } 3749 } 3750 3751 return PackageManager.PERMISSION_DENIED; 3752 } 3753 3754 @Override 3755 public int checkUidPermission(String permName, int uid) { 3756 final int userId = UserHandle.getUserId(uid); 3757 3758 if (!sUserManager.exists(userId)) { 3759 return PackageManager.PERMISSION_DENIED; 3760 } 3761 3762 synchronized (mPackages) { 3763 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3764 if (obj != null) { 3765 final SettingBase ps = (SettingBase) obj; 3766 final PermissionsState permissionsState = ps.getPermissionsState(); 3767 if (permissionsState.hasPermission(permName, userId)) { 3768 return PackageManager.PERMISSION_GRANTED; 3769 } 3770 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3771 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3772 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3773 return PackageManager.PERMISSION_GRANTED; 3774 } 3775 } else { 3776 ArraySet<String> perms = mSystemPermissions.get(uid); 3777 if (perms != null) { 3778 if (perms.contains(permName)) { 3779 return PackageManager.PERMISSION_GRANTED; 3780 } 3781 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3782 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3783 return PackageManager.PERMISSION_GRANTED; 3784 } 3785 } 3786 } 3787 } 3788 3789 return PackageManager.PERMISSION_DENIED; 3790 } 3791 3792 @Override 3793 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3794 if (UserHandle.getCallingUserId() != userId) { 3795 mContext.enforceCallingPermission( 3796 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3797 "isPermissionRevokedByPolicy for user " + userId); 3798 } 3799 3800 if (checkPermission(permission, packageName, userId) 3801 == PackageManager.PERMISSION_GRANTED) { 3802 return false; 3803 } 3804 3805 final long identity = Binder.clearCallingIdentity(); 3806 try { 3807 final int flags = getPermissionFlags(permission, packageName, userId); 3808 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3809 } finally { 3810 Binder.restoreCallingIdentity(identity); 3811 } 3812 } 3813 3814 @Override 3815 public String getPermissionControllerPackageName() { 3816 synchronized (mPackages) { 3817 return mRequiredInstallerPackage; 3818 } 3819 } 3820 3821 /** 3822 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3823 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3824 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3825 * @param message the message to log on security exception 3826 */ 3827 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3828 boolean checkShell, String message) { 3829 if (userId < 0) { 3830 throw new IllegalArgumentException("Invalid userId " + userId); 3831 } 3832 if (checkShell) { 3833 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3834 } 3835 if (userId == UserHandle.getUserId(callingUid)) return; 3836 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3837 if (requireFullPermission) { 3838 mContext.enforceCallingOrSelfPermission( 3839 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3840 } else { 3841 try { 3842 mContext.enforceCallingOrSelfPermission( 3843 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3844 } catch (SecurityException se) { 3845 mContext.enforceCallingOrSelfPermission( 3846 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3847 } 3848 } 3849 } 3850 } 3851 3852 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3853 if (callingUid == Process.SHELL_UID) { 3854 if (userHandle >= 0 3855 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3856 throw new SecurityException("Shell does not have permission to access user " 3857 + userHandle); 3858 } else if (userHandle < 0) { 3859 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3860 + Debug.getCallers(3)); 3861 } 3862 } 3863 } 3864 3865 private BasePermission findPermissionTreeLP(String permName) { 3866 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3867 if (permName.startsWith(bp.name) && 3868 permName.length() > bp.name.length() && 3869 permName.charAt(bp.name.length()) == '.') { 3870 return bp; 3871 } 3872 } 3873 return null; 3874 } 3875 3876 private BasePermission checkPermissionTreeLP(String permName) { 3877 if (permName != null) { 3878 BasePermission bp = findPermissionTreeLP(permName); 3879 if (bp != null) { 3880 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3881 return bp; 3882 } 3883 throw new SecurityException("Calling uid " 3884 + Binder.getCallingUid() 3885 + " is not allowed to add to permission tree " 3886 + bp.name + " owned by uid " + bp.uid); 3887 } 3888 } 3889 throw new SecurityException("No permission tree found for " + permName); 3890 } 3891 3892 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3893 if (s1 == null) { 3894 return s2 == null; 3895 } 3896 if (s2 == null) { 3897 return false; 3898 } 3899 if (s1.getClass() != s2.getClass()) { 3900 return false; 3901 } 3902 return s1.equals(s2); 3903 } 3904 3905 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3906 if (pi1.icon != pi2.icon) return false; 3907 if (pi1.logo != pi2.logo) return false; 3908 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3909 if (!compareStrings(pi1.name, pi2.name)) return false; 3910 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3911 // We'll take care of setting this one. 3912 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3913 // These are not currently stored in settings. 3914 //if (!compareStrings(pi1.group, pi2.group)) return false; 3915 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3916 //if (pi1.labelRes != pi2.labelRes) return false; 3917 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3918 return true; 3919 } 3920 3921 int permissionInfoFootprint(PermissionInfo info) { 3922 int size = info.name.length(); 3923 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3924 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3925 return size; 3926 } 3927 3928 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3929 int size = 0; 3930 for (BasePermission perm : mSettings.mPermissions.values()) { 3931 if (perm.uid == tree.uid) { 3932 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3933 } 3934 } 3935 return size; 3936 } 3937 3938 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3939 // We calculate the max size of permissions defined by this uid and throw 3940 // if that plus the size of 'info' would exceed our stated maximum. 3941 if (tree.uid != Process.SYSTEM_UID) { 3942 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3943 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3944 throw new SecurityException("Permission tree size cap exceeded"); 3945 } 3946 } 3947 } 3948 3949 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3950 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3951 throw new SecurityException("Label must be specified in permission"); 3952 } 3953 BasePermission tree = checkPermissionTreeLP(info.name); 3954 BasePermission bp = mSettings.mPermissions.get(info.name); 3955 boolean added = bp == null; 3956 boolean changed = true; 3957 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3958 if (added) { 3959 enforcePermissionCapLocked(info, tree); 3960 bp = new BasePermission(info.name, tree.sourcePackage, 3961 BasePermission.TYPE_DYNAMIC); 3962 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3963 throw new SecurityException( 3964 "Not allowed to modify non-dynamic permission " 3965 + info.name); 3966 } else { 3967 if (bp.protectionLevel == fixedLevel 3968 && bp.perm.owner.equals(tree.perm.owner) 3969 && bp.uid == tree.uid 3970 && comparePermissionInfos(bp.perm.info, info)) { 3971 changed = false; 3972 } 3973 } 3974 bp.protectionLevel = fixedLevel; 3975 info = new PermissionInfo(info); 3976 info.protectionLevel = fixedLevel; 3977 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3978 bp.perm.info.packageName = tree.perm.info.packageName; 3979 bp.uid = tree.uid; 3980 if (added) { 3981 mSettings.mPermissions.put(info.name, bp); 3982 } 3983 if (changed) { 3984 if (!async) { 3985 mSettings.writeLPr(); 3986 } else { 3987 scheduleWriteSettingsLocked(); 3988 } 3989 } 3990 return added; 3991 } 3992 3993 @Override 3994 public boolean addPermission(PermissionInfo info) { 3995 synchronized (mPackages) { 3996 return addPermissionLocked(info, false); 3997 } 3998 } 3999 4000 @Override 4001 public boolean addPermissionAsync(PermissionInfo info) { 4002 synchronized (mPackages) { 4003 return addPermissionLocked(info, true); 4004 } 4005 } 4006 4007 @Override 4008 public void removePermission(String name) { 4009 synchronized (mPackages) { 4010 checkPermissionTreeLP(name); 4011 BasePermission bp = mSettings.mPermissions.get(name); 4012 if (bp != null) { 4013 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4014 throw new SecurityException( 4015 "Not allowed to modify non-dynamic permission " 4016 + name); 4017 } 4018 mSettings.mPermissions.remove(name); 4019 mSettings.writeLPr(); 4020 } 4021 } 4022 } 4023 4024 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4025 BasePermission bp) { 4026 int index = pkg.requestedPermissions.indexOf(bp.name); 4027 if (index == -1) { 4028 throw new SecurityException("Package " + pkg.packageName 4029 + " has not requested permission " + bp.name); 4030 } 4031 if (!bp.isRuntime() && !bp.isDevelopment()) { 4032 throw new SecurityException("Permission " + bp.name 4033 + " is not a changeable permission type"); 4034 } 4035 } 4036 4037 @Override 4038 public void grantRuntimePermission(String packageName, String name, final int userId) { 4039 if (!sUserManager.exists(userId)) { 4040 Log.e(TAG, "No such user:" + userId); 4041 return; 4042 } 4043 4044 mContext.enforceCallingOrSelfPermission( 4045 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4046 "grantRuntimePermission"); 4047 4048 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4049 true /* requireFullPermission */, true /* checkShell */, 4050 "grantRuntimePermission"); 4051 4052 final int uid; 4053 final SettingBase sb; 4054 4055 synchronized (mPackages) { 4056 final PackageParser.Package pkg = mPackages.get(packageName); 4057 if (pkg == null) { 4058 throw new IllegalArgumentException("Unknown package: " + packageName); 4059 } 4060 4061 final BasePermission bp = mSettings.mPermissions.get(name); 4062 if (bp == null) { 4063 throw new IllegalArgumentException("Unknown permission: " + name); 4064 } 4065 4066 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4067 4068 // If a permission review is required for legacy apps we represent 4069 // their permissions as always granted runtime ones since we need 4070 // to keep the review required permission flag per user while an 4071 // install permission's state is shared across all users. 4072 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) 4073 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4074 && bp.isRuntime()) { 4075 return; 4076 } 4077 4078 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4079 sb = (SettingBase) pkg.mExtras; 4080 if (sb == null) { 4081 throw new IllegalArgumentException("Unknown package: " + packageName); 4082 } 4083 4084 final PermissionsState permissionsState = sb.getPermissionsState(); 4085 4086 final int flags = permissionsState.getPermissionFlags(name, userId); 4087 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4088 throw new SecurityException("Cannot grant system fixed permission " 4089 + name + " for package " + packageName); 4090 } 4091 4092 if (bp.isDevelopment()) { 4093 // Development permissions must be handled specially, since they are not 4094 // normal runtime permissions. For now they apply to all users. 4095 if (permissionsState.grantInstallPermission(bp) != 4096 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4097 scheduleWriteSettingsLocked(); 4098 } 4099 return; 4100 } 4101 4102 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4103 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4104 return; 4105 } 4106 4107 final int result = permissionsState.grantRuntimePermission(bp, userId); 4108 switch (result) { 4109 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4110 return; 4111 } 4112 4113 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4114 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4115 mHandler.post(new Runnable() { 4116 @Override 4117 public void run() { 4118 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4119 } 4120 }); 4121 } 4122 break; 4123 } 4124 4125 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4126 4127 // Not critical if that is lost - app has to request again. 4128 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4129 } 4130 4131 // Only need to do this if user is initialized. Otherwise it's a new user 4132 // and there are no processes running as the user yet and there's no need 4133 // to make an expensive call to remount processes for the changed permissions. 4134 if (READ_EXTERNAL_STORAGE.equals(name) 4135 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4136 final long token = Binder.clearCallingIdentity(); 4137 try { 4138 if (sUserManager.isInitialized(userId)) { 4139 MountServiceInternal mountServiceInternal = LocalServices.getService( 4140 MountServiceInternal.class); 4141 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4142 } 4143 } finally { 4144 Binder.restoreCallingIdentity(token); 4145 } 4146 } 4147 } 4148 4149 @Override 4150 public void revokeRuntimePermission(String packageName, String name, int userId) { 4151 if (!sUserManager.exists(userId)) { 4152 Log.e(TAG, "No such user:" + userId); 4153 return; 4154 } 4155 4156 mContext.enforceCallingOrSelfPermission( 4157 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4158 "revokeRuntimePermission"); 4159 4160 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4161 true /* requireFullPermission */, true /* checkShell */, 4162 "revokeRuntimePermission"); 4163 4164 final int appId; 4165 4166 synchronized (mPackages) { 4167 final PackageParser.Package pkg = mPackages.get(packageName); 4168 if (pkg == null) { 4169 throw new IllegalArgumentException("Unknown package: " + packageName); 4170 } 4171 4172 final BasePermission bp = mSettings.mPermissions.get(name); 4173 if (bp == null) { 4174 throw new IllegalArgumentException("Unknown permission: " + name); 4175 } 4176 4177 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4178 4179 // If a permission review is required for legacy apps we represent 4180 // their permissions as always granted runtime ones since we need 4181 // to keep the review required permission flag per user while an 4182 // install permission's state is shared across all users. 4183 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) 4184 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4185 && bp.isRuntime()) { 4186 return; 4187 } 4188 4189 SettingBase sb = (SettingBase) pkg.mExtras; 4190 if (sb == null) { 4191 throw new IllegalArgumentException("Unknown package: " + packageName); 4192 } 4193 4194 final PermissionsState permissionsState = sb.getPermissionsState(); 4195 4196 final int flags = permissionsState.getPermissionFlags(name, userId); 4197 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4198 throw new SecurityException("Cannot revoke system fixed permission " 4199 + name + " for package " + packageName); 4200 } 4201 4202 if (bp.isDevelopment()) { 4203 // Development permissions must be handled specially, since they are not 4204 // normal runtime permissions. For now they apply to all users. 4205 if (permissionsState.revokeInstallPermission(bp) != 4206 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4207 scheduleWriteSettingsLocked(); 4208 } 4209 return; 4210 } 4211 4212 if (permissionsState.revokeRuntimePermission(bp, userId) == 4213 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4214 return; 4215 } 4216 4217 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4218 4219 // Critical, after this call app should never have the permission. 4220 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4221 4222 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4223 } 4224 4225 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4226 } 4227 4228 @Override 4229 public void resetRuntimePermissions() { 4230 mContext.enforceCallingOrSelfPermission( 4231 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4232 "revokeRuntimePermission"); 4233 4234 int callingUid = Binder.getCallingUid(); 4235 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4236 mContext.enforceCallingOrSelfPermission( 4237 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4238 "resetRuntimePermissions"); 4239 } 4240 4241 synchronized (mPackages) { 4242 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4243 for (int userId : UserManagerService.getInstance().getUserIds()) { 4244 final int packageCount = mPackages.size(); 4245 for (int i = 0; i < packageCount; i++) { 4246 PackageParser.Package pkg = mPackages.valueAt(i); 4247 if (!(pkg.mExtras instanceof PackageSetting)) { 4248 continue; 4249 } 4250 PackageSetting ps = (PackageSetting) pkg.mExtras; 4251 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4252 } 4253 } 4254 } 4255 } 4256 4257 @Override 4258 public int getPermissionFlags(String name, String packageName, int userId) { 4259 if (!sUserManager.exists(userId)) { 4260 return 0; 4261 } 4262 4263 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4264 4265 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4266 true /* requireFullPermission */, false /* checkShell */, 4267 "getPermissionFlags"); 4268 4269 synchronized (mPackages) { 4270 final PackageParser.Package pkg = mPackages.get(packageName); 4271 if (pkg == null) { 4272 return 0; 4273 } 4274 4275 final BasePermission bp = mSettings.mPermissions.get(name); 4276 if (bp == null) { 4277 return 0; 4278 } 4279 4280 SettingBase sb = (SettingBase) pkg.mExtras; 4281 if (sb == null) { 4282 return 0; 4283 } 4284 4285 PermissionsState permissionsState = sb.getPermissionsState(); 4286 return permissionsState.getPermissionFlags(name, userId); 4287 } 4288 } 4289 4290 @Override 4291 public void updatePermissionFlags(String name, String packageName, int flagMask, 4292 int flagValues, int userId) { 4293 if (!sUserManager.exists(userId)) { 4294 return; 4295 } 4296 4297 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4298 4299 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4300 true /* requireFullPermission */, true /* checkShell */, 4301 "updatePermissionFlags"); 4302 4303 // Only the system can change these flags and nothing else. 4304 if (getCallingUid() != Process.SYSTEM_UID) { 4305 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4306 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4307 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4308 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4309 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4310 } 4311 4312 synchronized (mPackages) { 4313 final PackageParser.Package pkg = mPackages.get(packageName); 4314 if (pkg == null) { 4315 throw new IllegalArgumentException("Unknown package: " + packageName); 4316 } 4317 4318 final BasePermission bp = mSettings.mPermissions.get(name); 4319 if (bp == null) { 4320 throw new IllegalArgumentException("Unknown permission: " + name); 4321 } 4322 4323 SettingBase sb = (SettingBase) pkg.mExtras; 4324 if (sb == null) { 4325 throw new IllegalArgumentException("Unknown package: " + packageName); 4326 } 4327 4328 PermissionsState permissionsState = sb.getPermissionsState(); 4329 4330 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4331 4332 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4333 // Install and runtime permissions are stored in different places, 4334 // so figure out what permission changed and persist the change. 4335 if (permissionsState.getInstallPermissionState(name) != null) { 4336 scheduleWriteSettingsLocked(); 4337 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4338 || hadState) { 4339 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4340 } 4341 } 4342 } 4343 } 4344 4345 /** 4346 * Update the permission flags for all packages and runtime permissions of a user in order 4347 * to allow device or profile owner to remove POLICY_FIXED. 4348 */ 4349 @Override 4350 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4351 if (!sUserManager.exists(userId)) { 4352 return; 4353 } 4354 4355 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4356 4357 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4358 true /* requireFullPermission */, true /* checkShell */, 4359 "updatePermissionFlagsForAllApps"); 4360 4361 // Only the system can change system fixed flags. 4362 if (getCallingUid() != Process.SYSTEM_UID) { 4363 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4364 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4365 } 4366 4367 synchronized (mPackages) { 4368 boolean changed = false; 4369 final int packageCount = mPackages.size(); 4370 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4371 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4372 SettingBase sb = (SettingBase) pkg.mExtras; 4373 if (sb == null) { 4374 continue; 4375 } 4376 PermissionsState permissionsState = sb.getPermissionsState(); 4377 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4378 userId, flagMask, flagValues); 4379 } 4380 if (changed) { 4381 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4382 } 4383 } 4384 } 4385 4386 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4387 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4388 != PackageManager.PERMISSION_GRANTED 4389 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4390 != PackageManager.PERMISSION_GRANTED) { 4391 throw new SecurityException(message + " requires " 4392 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4393 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4394 } 4395 } 4396 4397 @Override 4398 public boolean shouldShowRequestPermissionRationale(String permissionName, 4399 String packageName, int userId) { 4400 if (UserHandle.getCallingUserId() != userId) { 4401 mContext.enforceCallingPermission( 4402 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4403 "canShowRequestPermissionRationale for user " + userId); 4404 } 4405 4406 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4407 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4408 return false; 4409 } 4410 4411 if (checkPermission(permissionName, packageName, userId) 4412 == PackageManager.PERMISSION_GRANTED) { 4413 return false; 4414 } 4415 4416 final int flags; 4417 4418 final long identity = Binder.clearCallingIdentity(); 4419 try { 4420 flags = getPermissionFlags(permissionName, 4421 packageName, userId); 4422 } finally { 4423 Binder.restoreCallingIdentity(identity); 4424 } 4425 4426 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4427 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4428 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4429 4430 if ((flags & fixedFlags) != 0) { 4431 return false; 4432 } 4433 4434 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4435 } 4436 4437 @Override 4438 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4439 mContext.enforceCallingOrSelfPermission( 4440 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4441 "addOnPermissionsChangeListener"); 4442 4443 synchronized (mPackages) { 4444 mOnPermissionChangeListeners.addListenerLocked(listener); 4445 } 4446 } 4447 4448 @Override 4449 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4450 synchronized (mPackages) { 4451 mOnPermissionChangeListeners.removeListenerLocked(listener); 4452 } 4453 } 4454 4455 @Override 4456 public boolean isProtectedBroadcast(String actionName) { 4457 synchronized (mPackages) { 4458 if (mProtectedBroadcasts.contains(actionName)) { 4459 return true; 4460 } else if (actionName != null) { 4461 // TODO: remove these terrible hacks 4462 if (actionName.startsWith("android.net.netmon.lingerExpired") 4463 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4464 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4465 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4466 return true; 4467 } 4468 } 4469 } 4470 return false; 4471 } 4472 4473 @Override 4474 public int checkSignatures(String pkg1, String pkg2) { 4475 synchronized (mPackages) { 4476 final PackageParser.Package p1 = mPackages.get(pkg1); 4477 final PackageParser.Package p2 = mPackages.get(pkg2); 4478 if (p1 == null || p1.mExtras == null 4479 || p2 == null || p2.mExtras == null) { 4480 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4481 } 4482 return compareSignatures(p1.mSignatures, p2.mSignatures); 4483 } 4484 } 4485 4486 @Override 4487 public int checkUidSignatures(int uid1, int uid2) { 4488 // Map to base uids. 4489 uid1 = UserHandle.getAppId(uid1); 4490 uid2 = UserHandle.getAppId(uid2); 4491 // reader 4492 synchronized (mPackages) { 4493 Signature[] s1; 4494 Signature[] s2; 4495 Object obj = mSettings.getUserIdLPr(uid1); 4496 if (obj != null) { 4497 if (obj instanceof SharedUserSetting) { 4498 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4499 } else if (obj instanceof PackageSetting) { 4500 s1 = ((PackageSetting)obj).signatures.mSignatures; 4501 } else { 4502 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4503 } 4504 } else { 4505 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4506 } 4507 obj = mSettings.getUserIdLPr(uid2); 4508 if (obj != null) { 4509 if (obj instanceof SharedUserSetting) { 4510 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4511 } else if (obj instanceof PackageSetting) { 4512 s2 = ((PackageSetting)obj).signatures.mSignatures; 4513 } else { 4514 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4515 } 4516 } else { 4517 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4518 } 4519 return compareSignatures(s1, s2); 4520 } 4521 } 4522 4523 /** 4524 * This method should typically only be used when granting or revoking 4525 * permissions, since the app may immediately restart after this call. 4526 * <p> 4527 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4528 * guard your work against the app being relaunched. 4529 */ 4530 private void killUid(int appId, int userId, String reason) { 4531 final long identity = Binder.clearCallingIdentity(); 4532 try { 4533 IActivityManager am = ActivityManagerNative.getDefault(); 4534 if (am != null) { 4535 try { 4536 am.killUid(appId, userId, reason); 4537 } catch (RemoteException e) { 4538 /* ignore - same process */ 4539 } 4540 } 4541 } finally { 4542 Binder.restoreCallingIdentity(identity); 4543 } 4544 } 4545 4546 /** 4547 * Compares two sets of signatures. Returns: 4548 * <br /> 4549 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4550 * <br /> 4551 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4552 * <br /> 4553 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4554 * <br /> 4555 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4556 * <br /> 4557 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4558 */ 4559 static int compareSignatures(Signature[] s1, Signature[] s2) { 4560 if (s1 == null) { 4561 return s2 == null 4562 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4563 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4564 } 4565 4566 if (s2 == null) { 4567 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4568 } 4569 4570 if (s1.length != s2.length) { 4571 return PackageManager.SIGNATURE_NO_MATCH; 4572 } 4573 4574 // Since both signature sets are of size 1, we can compare without HashSets. 4575 if (s1.length == 1) { 4576 return s1[0].equals(s2[0]) ? 4577 PackageManager.SIGNATURE_MATCH : 4578 PackageManager.SIGNATURE_NO_MATCH; 4579 } 4580 4581 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4582 for (Signature sig : s1) { 4583 set1.add(sig); 4584 } 4585 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4586 for (Signature sig : s2) { 4587 set2.add(sig); 4588 } 4589 // Make sure s2 contains all signatures in s1. 4590 if (set1.equals(set2)) { 4591 return PackageManager.SIGNATURE_MATCH; 4592 } 4593 return PackageManager.SIGNATURE_NO_MATCH; 4594 } 4595 4596 /** 4597 * If the database version for this type of package (internal storage or 4598 * external storage) is less than the version where package signatures 4599 * were updated, return true. 4600 */ 4601 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4602 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4603 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4604 } 4605 4606 /** 4607 * Used for backward compatibility to make sure any packages with 4608 * certificate chains get upgraded to the new style. {@code existingSigs} 4609 * will be in the old format (since they were stored on disk from before the 4610 * system upgrade) and {@code scannedSigs} will be in the newer format. 4611 */ 4612 private int compareSignaturesCompat(PackageSignatures existingSigs, 4613 PackageParser.Package scannedPkg) { 4614 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4615 return PackageManager.SIGNATURE_NO_MATCH; 4616 } 4617 4618 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4619 for (Signature sig : existingSigs.mSignatures) { 4620 existingSet.add(sig); 4621 } 4622 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4623 for (Signature sig : scannedPkg.mSignatures) { 4624 try { 4625 Signature[] chainSignatures = sig.getChainSignatures(); 4626 for (Signature chainSig : chainSignatures) { 4627 scannedCompatSet.add(chainSig); 4628 } 4629 } catch (CertificateEncodingException e) { 4630 scannedCompatSet.add(sig); 4631 } 4632 } 4633 /* 4634 * Make sure the expanded scanned set contains all signatures in the 4635 * existing one. 4636 */ 4637 if (scannedCompatSet.equals(existingSet)) { 4638 // Migrate the old signatures to the new scheme. 4639 existingSigs.assignSignatures(scannedPkg.mSignatures); 4640 // The new KeySets will be re-added later in the scanning process. 4641 synchronized (mPackages) { 4642 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4643 } 4644 return PackageManager.SIGNATURE_MATCH; 4645 } 4646 return PackageManager.SIGNATURE_NO_MATCH; 4647 } 4648 4649 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4650 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4651 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4652 } 4653 4654 private int compareSignaturesRecover(PackageSignatures existingSigs, 4655 PackageParser.Package scannedPkg) { 4656 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4657 return PackageManager.SIGNATURE_NO_MATCH; 4658 } 4659 4660 String msg = null; 4661 try { 4662 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4663 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4664 + scannedPkg.packageName); 4665 return PackageManager.SIGNATURE_MATCH; 4666 } 4667 } catch (CertificateException e) { 4668 msg = e.getMessage(); 4669 } 4670 4671 logCriticalInfo(Log.INFO, 4672 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4673 return PackageManager.SIGNATURE_NO_MATCH; 4674 } 4675 4676 @Override 4677 public List<String> getAllPackages() { 4678 synchronized (mPackages) { 4679 return new ArrayList<String>(mPackages.keySet()); 4680 } 4681 } 4682 4683 @Override 4684 public String[] getPackagesForUid(int uid) { 4685 final int userId = UserHandle.getUserId(uid); 4686 uid = UserHandle.getAppId(uid); 4687 // reader 4688 synchronized (mPackages) { 4689 Object obj = mSettings.getUserIdLPr(uid); 4690 if (obj instanceof SharedUserSetting) { 4691 final SharedUserSetting sus = (SharedUserSetting) obj; 4692 final int N = sus.packages.size(); 4693 String[] res = new String[N]; 4694 final Iterator<PackageSetting> it = sus.packages.iterator(); 4695 int i = 0; 4696 while (it.hasNext()) { 4697 PackageSetting ps = it.next(); 4698 if (ps.getInstalled(userId)) { 4699 res[i++] = ps.name; 4700 } else { 4701 res = ArrayUtils.removeElement(String.class, res, res[i]); 4702 } 4703 } 4704 return res; 4705 } else if (obj instanceof PackageSetting) { 4706 final PackageSetting ps = (PackageSetting) obj; 4707 return new String[] { ps.name }; 4708 } 4709 } 4710 return null; 4711 } 4712 4713 @Override 4714 public String getNameForUid(int uid) { 4715 // reader 4716 synchronized (mPackages) { 4717 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4718 if (obj instanceof SharedUserSetting) { 4719 final SharedUserSetting sus = (SharedUserSetting) obj; 4720 return sus.name + ":" + sus.userId; 4721 } else if (obj instanceof PackageSetting) { 4722 final PackageSetting ps = (PackageSetting) obj; 4723 return ps.name; 4724 } 4725 } 4726 return null; 4727 } 4728 4729 @Override 4730 public int getUidForSharedUser(String sharedUserName) { 4731 if(sharedUserName == null) { 4732 return -1; 4733 } 4734 // reader 4735 synchronized (mPackages) { 4736 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4737 if (suid == null) { 4738 return -1; 4739 } 4740 return suid.userId; 4741 } 4742 } 4743 4744 @Override 4745 public int getFlagsForUid(int uid) { 4746 synchronized (mPackages) { 4747 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4748 if (obj instanceof SharedUserSetting) { 4749 final SharedUserSetting sus = (SharedUserSetting) obj; 4750 return sus.pkgFlags; 4751 } else if (obj instanceof PackageSetting) { 4752 final PackageSetting ps = (PackageSetting) obj; 4753 return ps.pkgFlags; 4754 } 4755 } 4756 return 0; 4757 } 4758 4759 @Override 4760 public int getPrivateFlagsForUid(int uid) { 4761 synchronized (mPackages) { 4762 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4763 if (obj instanceof SharedUserSetting) { 4764 final SharedUserSetting sus = (SharedUserSetting) obj; 4765 return sus.pkgPrivateFlags; 4766 } else if (obj instanceof PackageSetting) { 4767 final PackageSetting ps = (PackageSetting) obj; 4768 return ps.pkgPrivateFlags; 4769 } 4770 } 4771 return 0; 4772 } 4773 4774 @Override 4775 public boolean isUidPrivileged(int uid) { 4776 uid = UserHandle.getAppId(uid); 4777 // reader 4778 synchronized (mPackages) { 4779 Object obj = mSettings.getUserIdLPr(uid); 4780 if (obj instanceof SharedUserSetting) { 4781 final SharedUserSetting sus = (SharedUserSetting) obj; 4782 final Iterator<PackageSetting> it = sus.packages.iterator(); 4783 while (it.hasNext()) { 4784 if (it.next().isPrivileged()) { 4785 return true; 4786 } 4787 } 4788 } else if (obj instanceof PackageSetting) { 4789 final PackageSetting ps = (PackageSetting) obj; 4790 return ps.isPrivileged(); 4791 } 4792 } 4793 return false; 4794 } 4795 4796 @Override 4797 public String[] getAppOpPermissionPackages(String permissionName) { 4798 synchronized (mPackages) { 4799 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4800 if (pkgs == null) { 4801 return null; 4802 } 4803 return pkgs.toArray(new String[pkgs.size()]); 4804 } 4805 } 4806 4807 @Override 4808 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4809 int flags, int userId) { 4810 try { 4811 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4812 4813 if (!sUserManager.exists(userId)) return null; 4814 flags = updateFlagsForResolve(flags, userId, intent); 4815 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4816 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4817 4818 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4819 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4820 flags, userId); 4821 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4822 4823 final ResolveInfo bestChoice = 4824 chooseBestActivity(intent, resolvedType, flags, query, userId); 4825 return bestChoice; 4826 } finally { 4827 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4828 } 4829 } 4830 4831 @Override 4832 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4833 IntentFilter filter, int match, ComponentName activity) { 4834 final int userId = UserHandle.getCallingUserId(); 4835 if (DEBUG_PREFERRED) { 4836 Log.v(TAG, "setLastChosenActivity intent=" + intent 4837 + " resolvedType=" + resolvedType 4838 + " flags=" + flags 4839 + " filter=" + filter 4840 + " match=" + match 4841 + " activity=" + activity); 4842 filter.dump(new PrintStreamPrinter(System.out), " "); 4843 } 4844 intent.setComponent(null); 4845 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4846 userId); 4847 // Find any earlier preferred or last chosen entries and nuke them 4848 findPreferredActivity(intent, resolvedType, 4849 flags, query, 0, false, true, false, userId); 4850 // Add the new activity as the last chosen for this filter 4851 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4852 "Setting last chosen"); 4853 } 4854 4855 @Override 4856 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4857 final int userId = UserHandle.getCallingUserId(); 4858 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4859 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4860 userId); 4861 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4862 false, false, false, userId); 4863 } 4864 4865 private boolean isEphemeralDisabled() { 4866 // ephemeral apps have been disabled across the board 4867 if (DISABLE_EPHEMERAL_APPS) { 4868 return true; 4869 } 4870 // system isn't up yet; can't read settings, so, assume no ephemeral apps 4871 if (!mSystemReady) { 4872 return true; 4873 } 4874 // we can't get a content resolver until the system is ready; these checks must happen last 4875 final ContentResolver resolver = mContext.getContentResolver(); 4876 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 4877 return true; 4878 } 4879 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 4880 } 4881 4882 private boolean isEphemeralAllowed( 4883 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 4884 boolean skipPackageCheck) { 4885 // Short circuit and return early if possible. 4886 if (isEphemeralDisabled()) { 4887 return false; 4888 } 4889 final int callingUser = UserHandle.getCallingUserId(); 4890 if (callingUser != UserHandle.USER_SYSTEM) { 4891 return false; 4892 } 4893 if (mEphemeralResolverConnection == null) { 4894 return false; 4895 } 4896 if (intent.getComponent() != null) { 4897 return false; 4898 } 4899 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 4900 return false; 4901 } 4902 if (!skipPackageCheck && intent.getPackage() != null) { 4903 return false; 4904 } 4905 final boolean isWebUri = hasWebURI(intent); 4906 if (!isWebUri || intent.getData().getHost() == null) { 4907 return false; 4908 } 4909 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4910 synchronized (mPackages) { 4911 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 4912 for (int n = 0; n < count; n++) { 4913 ResolveInfo info = resolvedActivities.get(n); 4914 String packageName = info.activityInfo.packageName; 4915 PackageSetting ps = mSettings.mPackages.get(packageName); 4916 if (ps != null) { 4917 // Try to get the status from User settings first 4918 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4919 int status = (int) (packedStatus >> 32); 4920 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4921 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4922 if (DEBUG_EPHEMERAL) { 4923 Slog.v(TAG, "DENY ephemeral apps;" 4924 + " pkg: " + packageName + ", status: " + status); 4925 } 4926 return false; 4927 } 4928 } 4929 } 4930 } 4931 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4932 return true; 4933 } 4934 4935 private static EphemeralResolveInfo getEphemeralResolveInfo( 4936 Context context, EphemeralResolverConnection resolverConnection, Intent intent, 4937 String resolvedType, int userId, String packageName) { 4938 final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(), 4939 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 4940 final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(), 4941 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 4942 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 4943 ephemeralPrefixCount); 4944 final int[] shaPrefix = digest.getDigestPrefix(); 4945 final byte[][] digestBytes = digest.getDigestBytes(); 4946 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4947 resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask); 4948 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4949 // No hash prefix match; there are no ephemeral apps for this domain. 4950 return null; 4951 } 4952 4953 // Go in reverse order so we match the narrowest scope first. 4954 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 4955 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 4956 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 4957 continue; 4958 } 4959 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4960 // No filters; this should never happen. 4961 if (filters.isEmpty()) { 4962 continue; 4963 } 4964 if (packageName != null 4965 && !packageName.equals(ephemeralApplication.getPackageName())) { 4966 continue; 4967 } 4968 // We have a domain match; resolve the filters to see if anything matches. 4969 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4970 for (int j = filters.size() - 1; j >= 0; --j) { 4971 final EphemeralResolveIntentInfo intentInfo = 4972 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4973 ephemeralResolver.addFilter(intentInfo); 4974 } 4975 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4976 intent, resolvedType, false /*defaultOnly*/, userId); 4977 if (!matchedResolveInfoList.isEmpty()) { 4978 return matchedResolveInfoList.get(0); 4979 } 4980 } 4981 } 4982 // Hash or filter mis-match; no ephemeral apps for this domain. 4983 return null; 4984 } 4985 4986 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4987 int flags, List<ResolveInfo> query, int userId) { 4988 if (query != null) { 4989 final int N = query.size(); 4990 if (N == 1) { 4991 return query.get(0); 4992 } else if (N > 1) { 4993 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4994 // If there is more than one activity with the same priority, 4995 // then let the user decide between them. 4996 ResolveInfo r0 = query.get(0); 4997 ResolveInfo r1 = query.get(1); 4998 if (DEBUG_INTENT_MATCHING || debug) { 4999 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5000 + r1.activityInfo.name + "=" + r1.priority); 5001 } 5002 // If the first activity has a higher priority, or a different 5003 // default, then it is always desirable to pick it. 5004 if (r0.priority != r1.priority 5005 || r0.preferredOrder != r1.preferredOrder 5006 || r0.isDefault != r1.isDefault) { 5007 return query.get(0); 5008 } 5009 // If we have saved a preference for a preferred activity for 5010 // this Intent, use that. 5011 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5012 flags, query, r0.priority, true, false, debug, userId); 5013 if (ri != null) { 5014 return ri; 5015 } 5016 ri = new ResolveInfo(mResolveInfo); 5017 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5018 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5019 // If all of the options come from the same package, show the application's 5020 // label and icon instead of the generic resolver's. 5021 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5022 // and then throw away the ResolveInfo itself, meaning that the caller loses 5023 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5024 // a fallback for this case; we only set the target package's resources on 5025 // the ResolveInfo, not the ActivityInfo. 5026 final String intentPackage = intent.getPackage(); 5027 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5028 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5029 ri.resolvePackageName = intentPackage; 5030 if (userNeedsBadging(userId)) { 5031 ri.noResourceId = true; 5032 } else { 5033 ri.icon = appi.icon; 5034 } 5035 ri.iconResourceId = appi.icon; 5036 ri.labelRes = appi.labelRes; 5037 } 5038 ri.activityInfo.applicationInfo = new ApplicationInfo( 5039 ri.activityInfo.applicationInfo); 5040 if (userId != 0) { 5041 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5042 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5043 } 5044 // Make sure that the resolver is displayable in car mode 5045 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5046 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5047 return ri; 5048 } 5049 } 5050 return null; 5051 } 5052 5053 /** 5054 * Return true if the given list is not empty and all of its contents have 5055 * an activityInfo with the given package name. 5056 */ 5057 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5058 if (ArrayUtils.isEmpty(list)) { 5059 return false; 5060 } 5061 for (int i = 0, N = list.size(); i < N; i++) { 5062 final ResolveInfo ri = list.get(i); 5063 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5064 if (ai == null || !packageName.equals(ai.packageName)) { 5065 return false; 5066 } 5067 } 5068 return true; 5069 } 5070 5071 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5072 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5073 final int N = query.size(); 5074 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5075 .get(userId); 5076 // Get the list of persistent preferred activities that handle the intent 5077 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5078 List<PersistentPreferredActivity> pprefs = ppir != null 5079 ? ppir.queryIntent(intent, resolvedType, 5080 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5081 : null; 5082 if (pprefs != null && pprefs.size() > 0) { 5083 final int M = pprefs.size(); 5084 for (int i=0; i<M; i++) { 5085 final PersistentPreferredActivity ppa = pprefs.get(i); 5086 if (DEBUG_PREFERRED || debug) { 5087 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5088 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5089 + "\n component=" + ppa.mComponent); 5090 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5091 } 5092 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5093 flags | MATCH_DISABLED_COMPONENTS, userId); 5094 if (DEBUG_PREFERRED || debug) { 5095 Slog.v(TAG, "Found persistent preferred activity:"); 5096 if (ai != null) { 5097 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5098 } else { 5099 Slog.v(TAG, " null"); 5100 } 5101 } 5102 if (ai == null) { 5103 // This previously registered persistent preferred activity 5104 // component is no longer known. Ignore it and do NOT remove it. 5105 continue; 5106 } 5107 for (int j=0; j<N; j++) { 5108 final ResolveInfo ri = query.get(j); 5109 if (!ri.activityInfo.applicationInfo.packageName 5110 .equals(ai.applicationInfo.packageName)) { 5111 continue; 5112 } 5113 if (!ri.activityInfo.name.equals(ai.name)) { 5114 continue; 5115 } 5116 // Found a persistent preference that can handle the intent. 5117 if (DEBUG_PREFERRED || debug) { 5118 Slog.v(TAG, "Returning persistent preferred activity: " + 5119 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5120 } 5121 return ri; 5122 } 5123 } 5124 } 5125 return null; 5126 } 5127 5128 // TODO: handle preferred activities missing while user has amnesia 5129 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5130 List<ResolveInfo> query, int priority, boolean always, 5131 boolean removeMatches, boolean debug, int userId) { 5132 if (!sUserManager.exists(userId)) return null; 5133 flags = updateFlagsForResolve(flags, userId, intent); 5134 // writer 5135 synchronized (mPackages) { 5136 if (intent.getSelector() != null) { 5137 intent = intent.getSelector(); 5138 } 5139 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5140 5141 // Try to find a matching persistent preferred activity. 5142 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5143 debug, userId); 5144 5145 // If a persistent preferred activity matched, use it. 5146 if (pri != null) { 5147 return pri; 5148 } 5149 5150 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5151 // Get the list of preferred activities that handle the intent 5152 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5153 List<PreferredActivity> prefs = pir != null 5154 ? pir.queryIntent(intent, resolvedType, 5155 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5156 : null; 5157 if (prefs != null && prefs.size() > 0) { 5158 boolean changed = false; 5159 try { 5160 // First figure out how good the original match set is. 5161 // We will only allow preferred activities that came 5162 // from the same match quality. 5163 int match = 0; 5164 5165 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5166 5167 final int N = query.size(); 5168 for (int j=0; j<N; j++) { 5169 final ResolveInfo ri = query.get(j); 5170 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5171 + ": 0x" + Integer.toHexString(match)); 5172 if (ri.match > match) { 5173 match = ri.match; 5174 } 5175 } 5176 5177 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5178 + Integer.toHexString(match)); 5179 5180 match &= IntentFilter.MATCH_CATEGORY_MASK; 5181 final int M = prefs.size(); 5182 for (int i=0; i<M; i++) { 5183 final PreferredActivity pa = prefs.get(i); 5184 if (DEBUG_PREFERRED || debug) { 5185 Slog.v(TAG, "Checking PreferredActivity ds=" 5186 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5187 + "\n component=" + pa.mPref.mComponent); 5188 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5189 } 5190 if (pa.mPref.mMatch != match) { 5191 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5192 + Integer.toHexString(pa.mPref.mMatch)); 5193 continue; 5194 } 5195 // If it's not an "always" type preferred activity and that's what we're 5196 // looking for, skip it. 5197 if (always && !pa.mPref.mAlways) { 5198 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5199 continue; 5200 } 5201 final ActivityInfo ai = getActivityInfo( 5202 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5203 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5204 userId); 5205 if (DEBUG_PREFERRED || debug) { 5206 Slog.v(TAG, "Found preferred activity:"); 5207 if (ai != null) { 5208 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5209 } else { 5210 Slog.v(TAG, " null"); 5211 } 5212 } 5213 if (ai == null) { 5214 // This previously registered preferred activity 5215 // component is no longer known. Most likely an update 5216 // to the app was installed and in the new version this 5217 // component no longer exists. Clean it up by removing 5218 // it from the preferred activities list, and skip it. 5219 Slog.w(TAG, "Removing dangling preferred activity: " 5220 + pa.mPref.mComponent); 5221 pir.removeFilter(pa); 5222 changed = true; 5223 continue; 5224 } 5225 for (int j=0; j<N; j++) { 5226 final ResolveInfo ri = query.get(j); 5227 if (!ri.activityInfo.applicationInfo.packageName 5228 .equals(ai.applicationInfo.packageName)) { 5229 continue; 5230 } 5231 if (!ri.activityInfo.name.equals(ai.name)) { 5232 continue; 5233 } 5234 5235 if (removeMatches) { 5236 pir.removeFilter(pa); 5237 changed = true; 5238 if (DEBUG_PREFERRED) { 5239 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5240 } 5241 break; 5242 } 5243 5244 // Okay we found a previously set preferred or last chosen app. 5245 // If the result set is different from when this 5246 // was created, we need to clear it and re-ask the 5247 // user their preference, if we're looking for an "always" type entry. 5248 if (always && !pa.mPref.sameSet(query)) { 5249 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5250 + intent + " type " + resolvedType); 5251 if (DEBUG_PREFERRED) { 5252 Slog.v(TAG, "Removing preferred activity since set changed " 5253 + pa.mPref.mComponent); 5254 } 5255 pir.removeFilter(pa); 5256 // Re-add the filter as a "last chosen" entry (!always) 5257 PreferredActivity lastChosen = new PreferredActivity( 5258 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5259 pir.addFilter(lastChosen); 5260 changed = true; 5261 return null; 5262 } 5263 5264 // Yay! Either the set matched or we're looking for the last chosen 5265 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5266 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5267 return ri; 5268 } 5269 } 5270 } finally { 5271 if (changed) { 5272 if (DEBUG_PREFERRED) { 5273 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5274 } 5275 scheduleWritePackageRestrictionsLocked(userId); 5276 } 5277 } 5278 } 5279 } 5280 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5281 return null; 5282 } 5283 5284 /* 5285 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5286 */ 5287 @Override 5288 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5289 int targetUserId) { 5290 mContext.enforceCallingOrSelfPermission( 5291 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5292 List<CrossProfileIntentFilter> matches = 5293 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5294 if (matches != null) { 5295 int size = matches.size(); 5296 for (int i = 0; i < size; i++) { 5297 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5298 } 5299 } 5300 if (hasWebURI(intent)) { 5301 // cross-profile app linking works only towards the parent. 5302 final UserInfo parent = getProfileParent(sourceUserId); 5303 synchronized(mPackages) { 5304 int flags = updateFlagsForResolve(0, parent.id, intent); 5305 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5306 intent, resolvedType, flags, sourceUserId, parent.id); 5307 return xpDomainInfo != null; 5308 } 5309 } 5310 return false; 5311 } 5312 5313 private UserInfo getProfileParent(int userId) { 5314 final long identity = Binder.clearCallingIdentity(); 5315 try { 5316 return sUserManager.getProfileParent(userId); 5317 } finally { 5318 Binder.restoreCallingIdentity(identity); 5319 } 5320 } 5321 5322 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5323 String resolvedType, int userId) { 5324 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5325 if (resolver != null) { 5326 return resolver.queryIntent(intent, resolvedType, false, userId); 5327 } 5328 return null; 5329 } 5330 5331 @Override 5332 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5333 String resolvedType, int flags, int userId) { 5334 try { 5335 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5336 5337 return new ParceledListSlice<>( 5338 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5339 } finally { 5340 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5341 } 5342 } 5343 5344 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5345 String resolvedType, int flags, int userId) { 5346 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5347 flags = updateFlagsForResolve(flags, userId, intent); 5348 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5349 false /* requireFullPermission */, false /* checkShell */, 5350 "query intent activities"); 5351 ComponentName comp = intent.getComponent(); 5352 if (comp == null) { 5353 if (intent.getSelector() != null) { 5354 intent = intent.getSelector(); 5355 comp = intent.getComponent(); 5356 } 5357 } 5358 5359 if (comp != null) { 5360 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5361 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5362 if (ai != null) { 5363 final ResolveInfo ri = new ResolveInfo(); 5364 ri.activityInfo = ai; 5365 list.add(ri); 5366 } 5367 return list; 5368 } 5369 5370 // reader 5371 boolean sortResult = false; 5372 boolean addEphemeral = false; 5373 boolean matchEphemeralPackage = false; 5374 List<ResolveInfo> result; 5375 final String pkgName = intent.getPackage(); 5376 synchronized (mPackages) { 5377 if (pkgName == null) { 5378 List<CrossProfileIntentFilter> matchingFilters = 5379 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5380 // Check for results that need to skip the current profile. 5381 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5382 resolvedType, flags, userId); 5383 if (xpResolveInfo != null) { 5384 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5385 xpResult.add(xpResolveInfo); 5386 return filterIfNotSystemUser(xpResult, userId); 5387 } 5388 5389 // Check for results in the current profile. 5390 result = filterIfNotSystemUser(mActivities.queryIntent( 5391 intent, resolvedType, flags, userId), userId); 5392 addEphemeral = 5393 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5394 5395 // Check for cross profile results. 5396 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5397 xpResolveInfo = queryCrossProfileIntents( 5398 matchingFilters, intent, resolvedType, flags, userId, 5399 hasNonNegativePriorityResult); 5400 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5401 boolean isVisibleToUser = filterIfNotSystemUser( 5402 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5403 if (isVisibleToUser) { 5404 result.add(xpResolveInfo); 5405 sortResult = true; 5406 } 5407 } 5408 if (hasWebURI(intent)) { 5409 CrossProfileDomainInfo xpDomainInfo = null; 5410 final UserInfo parent = getProfileParent(userId); 5411 if (parent != null) { 5412 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5413 flags, userId, parent.id); 5414 } 5415 if (xpDomainInfo != null) { 5416 if (xpResolveInfo != null) { 5417 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5418 // in the result. 5419 result.remove(xpResolveInfo); 5420 } 5421 if (result.size() == 0 && !addEphemeral) { 5422 result.add(xpDomainInfo.resolveInfo); 5423 return result; 5424 } 5425 } 5426 if (result.size() > 1 || addEphemeral) { 5427 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5428 intent, flags, result, xpDomainInfo, userId); 5429 sortResult = true; 5430 } 5431 } 5432 } else { 5433 final PackageParser.Package pkg = mPackages.get(pkgName); 5434 if (pkg != null) { 5435 result = filterIfNotSystemUser( 5436 mActivities.queryIntentForPackage( 5437 intent, resolvedType, flags, pkg.activities, userId), 5438 userId); 5439 } else { 5440 // the caller wants to resolve for a particular package; however, there 5441 // were no installed results, so, try to find an ephemeral result 5442 addEphemeral = isEphemeralAllowed( 5443 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5444 matchEphemeralPackage = true; 5445 result = new ArrayList<ResolveInfo>(); 5446 } 5447 } 5448 } 5449 if (addEphemeral) { 5450 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5451 final EphemeralResolveInfo ai = getEphemeralResolveInfo( 5452 mContext, mEphemeralResolverConnection, intent, resolvedType, userId, 5453 matchEphemeralPackage ? pkgName : null); 5454 if (ai != null) { 5455 if (DEBUG_EPHEMERAL) { 5456 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5457 } 5458 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5459 ephemeralInstaller.ephemeralResolveInfo = ai; 5460 // make sure this resolver is the default 5461 ephemeralInstaller.isDefault = true; 5462 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5463 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5464 // add a non-generic filter 5465 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5466 ephemeralInstaller.filter.addDataPath( 5467 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5468 result.add(ephemeralInstaller); 5469 } 5470 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5471 } 5472 if (sortResult) { 5473 Collections.sort(result, mResolvePrioritySorter); 5474 } 5475 return result; 5476 } 5477 5478 private static class CrossProfileDomainInfo { 5479 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5480 ResolveInfo resolveInfo; 5481 /* Best domain verification status of the activities found in the other profile */ 5482 int bestDomainVerificationStatus; 5483 } 5484 5485 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5486 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5487 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5488 sourceUserId)) { 5489 return null; 5490 } 5491 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5492 resolvedType, flags, parentUserId); 5493 5494 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5495 return null; 5496 } 5497 CrossProfileDomainInfo result = null; 5498 int size = resultTargetUser.size(); 5499 for (int i = 0; i < size; i++) { 5500 ResolveInfo riTargetUser = resultTargetUser.get(i); 5501 // Intent filter verification is only for filters that specify a host. So don't return 5502 // those that handle all web uris. 5503 if (riTargetUser.handleAllWebDataURI) { 5504 continue; 5505 } 5506 String packageName = riTargetUser.activityInfo.packageName; 5507 PackageSetting ps = mSettings.mPackages.get(packageName); 5508 if (ps == null) { 5509 continue; 5510 } 5511 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5512 int status = (int)(verificationState >> 32); 5513 if (result == null) { 5514 result = new CrossProfileDomainInfo(); 5515 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5516 sourceUserId, parentUserId); 5517 result.bestDomainVerificationStatus = status; 5518 } else { 5519 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5520 result.bestDomainVerificationStatus); 5521 } 5522 } 5523 // Don't consider matches with status NEVER across profiles. 5524 if (result != null && result.bestDomainVerificationStatus 5525 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5526 return null; 5527 } 5528 return result; 5529 } 5530 5531 /** 5532 * Verification statuses are ordered from the worse to the best, except for 5533 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5534 */ 5535 private int bestDomainVerificationStatus(int status1, int status2) { 5536 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5537 return status2; 5538 } 5539 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5540 return status1; 5541 } 5542 return (int) MathUtils.max(status1, status2); 5543 } 5544 5545 private boolean isUserEnabled(int userId) { 5546 long callingId = Binder.clearCallingIdentity(); 5547 try { 5548 UserInfo userInfo = sUserManager.getUserInfo(userId); 5549 return userInfo != null && userInfo.isEnabled(); 5550 } finally { 5551 Binder.restoreCallingIdentity(callingId); 5552 } 5553 } 5554 5555 /** 5556 * Filter out activities with systemUserOnly flag set, when current user is not System. 5557 * 5558 * @return filtered list 5559 */ 5560 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5561 if (userId == UserHandle.USER_SYSTEM) { 5562 return resolveInfos; 5563 } 5564 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5565 ResolveInfo info = resolveInfos.get(i); 5566 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5567 resolveInfos.remove(i); 5568 } 5569 } 5570 return resolveInfos; 5571 } 5572 5573 /** 5574 * @param resolveInfos list of resolve infos in descending priority order 5575 * @return if the list contains a resolve info with non-negative priority 5576 */ 5577 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5578 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5579 } 5580 5581 private static boolean hasWebURI(Intent intent) { 5582 if (intent.getData() == null) { 5583 return false; 5584 } 5585 final String scheme = intent.getScheme(); 5586 if (TextUtils.isEmpty(scheme)) { 5587 return false; 5588 } 5589 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5590 } 5591 5592 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5593 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5594 int userId) { 5595 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5596 5597 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5598 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5599 candidates.size()); 5600 } 5601 5602 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5603 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5604 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5605 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5606 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5607 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5608 5609 synchronized (mPackages) { 5610 final int count = candidates.size(); 5611 // First, try to use linked apps. Partition the candidates into four lists: 5612 // one for the final results, one for the "do not use ever", one for "undefined status" 5613 // and finally one for "browser app type". 5614 for (int n=0; n<count; n++) { 5615 ResolveInfo info = candidates.get(n); 5616 String packageName = info.activityInfo.packageName; 5617 PackageSetting ps = mSettings.mPackages.get(packageName); 5618 if (ps != null) { 5619 // Add to the special match all list (Browser use case) 5620 if (info.handleAllWebDataURI) { 5621 matchAllList.add(info); 5622 continue; 5623 } 5624 // Try to get the status from User settings first 5625 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5626 int status = (int)(packedStatus >> 32); 5627 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5628 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5629 if (DEBUG_DOMAIN_VERIFICATION) { 5630 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5631 + " : linkgen=" + linkGeneration); 5632 } 5633 // Use link-enabled generation as preferredOrder, i.e. 5634 // prefer newly-enabled over earlier-enabled. 5635 info.preferredOrder = linkGeneration; 5636 alwaysList.add(info); 5637 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5638 if (DEBUG_DOMAIN_VERIFICATION) { 5639 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5640 } 5641 neverList.add(info); 5642 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5643 if (DEBUG_DOMAIN_VERIFICATION) { 5644 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5645 } 5646 alwaysAskList.add(info); 5647 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5648 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5649 if (DEBUG_DOMAIN_VERIFICATION) { 5650 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5651 } 5652 undefinedList.add(info); 5653 } 5654 } 5655 } 5656 5657 // We'll want to include browser possibilities in a few cases 5658 boolean includeBrowser = false; 5659 5660 // First try to add the "always" resolution(s) for the current user, if any 5661 if (alwaysList.size() > 0) { 5662 result.addAll(alwaysList); 5663 } else { 5664 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5665 result.addAll(undefinedList); 5666 // Maybe add one for the other profile. 5667 if (xpDomainInfo != null && ( 5668 xpDomainInfo.bestDomainVerificationStatus 5669 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5670 result.add(xpDomainInfo.resolveInfo); 5671 } 5672 includeBrowser = true; 5673 } 5674 5675 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5676 // If there were 'always' entries their preferred order has been set, so we also 5677 // back that off to make the alternatives equivalent 5678 if (alwaysAskList.size() > 0) { 5679 for (ResolveInfo i : result) { 5680 i.preferredOrder = 0; 5681 } 5682 result.addAll(alwaysAskList); 5683 includeBrowser = true; 5684 } 5685 5686 if (includeBrowser) { 5687 // Also add browsers (all of them or only the default one) 5688 if (DEBUG_DOMAIN_VERIFICATION) { 5689 Slog.v(TAG, " ...including browsers in candidate set"); 5690 } 5691 if ((matchFlags & MATCH_ALL) != 0) { 5692 result.addAll(matchAllList); 5693 } else { 5694 // Browser/generic handling case. If there's a default browser, go straight 5695 // to that (but only if there is no other higher-priority match). 5696 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5697 int maxMatchPrio = 0; 5698 ResolveInfo defaultBrowserMatch = null; 5699 final int numCandidates = matchAllList.size(); 5700 for (int n = 0; n < numCandidates; n++) { 5701 ResolveInfo info = matchAllList.get(n); 5702 // track the highest overall match priority... 5703 if (info.priority > maxMatchPrio) { 5704 maxMatchPrio = info.priority; 5705 } 5706 // ...and the highest-priority default browser match 5707 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5708 if (defaultBrowserMatch == null 5709 || (defaultBrowserMatch.priority < info.priority)) { 5710 if (debug) { 5711 Slog.v(TAG, "Considering default browser match " + info); 5712 } 5713 defaultBrowserMatch = info; 5714 } 5715 } 5716 } 5717 if (defaultBrowserMatch != null 5718 && defaultBrowserMatch.priority >= maxMatchPrio 5719 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5720 { 5721 if (debug) { 5722 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5723 } 5724 result.add(defaultBrowserMatch); 5725 } else { 5726 result.addAll(matchAllList); 5727 } 5728 } 5729 5730 // If there is nothing selected, add all candidates and remove the ones that the user 5731 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5732 if (result.size() == 0) { 5733 result.addAll(candidates); 5734 result.removeAll(neverList); 5735 } 5736 } 5737 } 5738 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5739 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5740 result.size()); 5741 for (ResolveInfo info : result) { 5742 Slog.v(TAG, " + " + info.activityInfo); 5743 } 5744 } 5745 return result; 5746 } 5747 5748 // Returns a packed value as a long: 5749 // 5750 // high 'int'-sized word: link status: undefined/ask/never/always. 5751 // low 'int'-sized word: relative priority among 'always' results. 5752 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5753 long result = ps.getDomainVerificationStatusForUser(userId); 5754 // if none available, get the master status 5755 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5756 if (ps.getIntentFilterVerificationInfo() != null) { 5757 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5758 } 5759 } 5760 return result; 5761 } 5762 5763 private ResolveInfo querySkipCurrentProfileIntents( 5764 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5765 int flags, int sourceUserId) { 5766 if (matchingFilters != null) { 5767 int size = matchingFilters.size(); 5768 for (int i = 0; i < size; i ++) { 5769 CrossProfileIntentFilter filter = matchingFilters.get(i); 5770 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5771 // Checking if there are activities in the target user that can handle the 5772 // intent. 5773 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5774 resolvedType, flags, sourceUserId); 5775 if (resolveInfo != null) { 5776 return resolveInfo; 5777 } 5778 } 5779 } 5780 } 5781 return null; 5782 } 5783 5784 // Return matching ResolveInfo in target user if any. 5785 private ResolveInfo queryCrossProfileIntents( 5786 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5787 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5788 if (matchingFilters != null) { 5789 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5790 // match the same intent. For performance reasons, it is better not to 5791 // run queryIntent twice for the same userId 5792 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5793 int size = matchingFilters.size(); 5794 for (int i = 0; i < size; i++) { 5795 CrossProfileIntentFilter filter = matchingFilters.get(i); 5796 int targetUserId = filter.getTargetUserId(); 5797 boolean skipCurrentProfile = 5798 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5799 boolean skipCurrentProfileIfNoMatchFound = 5800 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5801 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5802 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5803 // Checking if there are activities in the target user that can handle the 5804 // intent. 5805 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5806 resolvedType, flags, sourceUserId); 5807 if (resolveInfo != null) return resolveInfo; 5808 alreadyTriedUserIds.put(targetUserId, true); 5809 } 5810 } 5811 } 5812 return null; 5813 } 5814 5815 /** 5816 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5817 * will forward the intent to the filter's target user. 5818 * Otherwise, returns null. 5819 */ 5820 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5821 String resolvedType, int flags, int sourceUserId) { 5822 int targetUserId = filter.getTargetUserId(); 5823 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5824 resolvedType, flags, targetUserId); 5825 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5826 // If all the matches in the target profile are suspended, return null. 5827 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5828 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5829 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5830 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5831 targetUserId); 5832 } 5833 } 5834 } 5835 return null; 5836 } 5837 5838 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5839 int sourceUserId, int targetUserId) { 5840 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5841 long ident = Binder.clearCallingIdentity(); 5842 boolean targetIsProfile; 5843 try { 5844 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5845 } finally { 5846 Binder.restoreCallingIdentity(ident); 5847 } 5848 String className; 5849 if (targetIsProfile) { 5850 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5851 } else { 5852 className = FORWARD_INTENT_TO_PARENT; 5853 } 5854 ComponentName forwardingActivityComponentName = new ComponentName( 5855 mAndroidApplication.packageName, className); 5856 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5857 sourceUserId); 5858 if (!targetIsProfile) { 5859 forwardingActivityInfo.showUserIcon = targetUserId; 5860 forwardingResolveInfo.noResourceId = true; 5861 } 5862 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5863 forwardingResolveInfo.priority = 0; 5864 forwardingResolveInfo.preferredOrder = 0; 5865 forwardingResolveInfo.match = 0; 5866 forwardingResolveInfo.isDefault = true; 5867 forwardingResolveInfo.filter = filter; 5868 forwardingResolveInfo.targetUserId = targetUserId; 5869 return forwardingResolveInfo; 5870 } 5871 5872 @Override 5873 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5874 Intent[] specifics, String[] specificTypes, Intent intent, 5875 String resolvedType, int flags, int userId) { 5876 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5877 specificTypes, intent, resolvedType, flags, userId)); 5878 } 5879 5880 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5881 Intent[] specifics, String[] specificTypes, Intent intent, 5882 String resolvedType, int flags, int userId) { 5883 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5884 flags = updateFlagsForResolve(flags, userId, intent); 5885 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5886 false /* requireFullPermission */, false /* checkShell */, 5887 "query intent activity options"); 5888 final String resultsAction = intent.getAction(); 5889 5890 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5891 | PackageManager.GET_RESOLVED_FILTER, userId); 5892 5893 if (DEBUG_INTENT_MATCHING) { 5894 Log.v(TAG, "Query " + intent + ": " + results); 5895 } 5896 5897 int specificsPos = 0; 5898 int N; 5899 5900 // todo: note that the algorithm used here is O(N^2). This 5901 // isn't a problem in our current environment, but if we start running 5902 // into situations where we have more than 5 or 10 matches then this 5903 // should probably be changed to something smarter... 5904 5905 // First we go through and resolve each of the specific items 5906 // that were supplied, taking care of removing any corresponding 5907 // duplicate items in the generic resolve list. 5908 if (specifics != null) { 5909 for (int i=0; i<specifics.length; i++) { 5910 final Intent sintent = specifics[i]; 5911 if (sintent == null) { 5912 continue; 5913 } 5914 5915 if (DEBUG_INTENT_MATCHING) { 5916 Log.v(TAG, "Specific #" + i + ": " + sintent); 5917 } 5918 5919 String action = sintent.getAction(); 5920 if (resultsAction != null && resultsAction.equals(action)) { 5921 // If this action was explicitly requested, then don't 5922 // remove things that have it. 5923 action = null; 5924 } 5925 5926 ResolveInfo ri = null; 5927 ActivityInfo ai = null; 5928 5929 ComponentName comp = sintent.getComponent(); 5930 if (comp == null) { 5931 ri = resolveIntent( 5932 sintent, 5933 specificTypes != null ? specificTypes[i] : null, 5934 flags, userId); 5935 if (ri == null) { 5936 continue; 5937 } 5938 if (ri == mResolveInfo) { 5939 // ACK! Must do something better with this. 5940 } 5941 ai = ri.activityInfo; 5942 comp = new ComponentName(ai.applicationInfo.packageName, 5943 ai.name); 5944 } else { 5945 ai = getActivityInfo(comp, flags, userId); 5946 if (ai == null) { 5947 continue; 5948 } 5949 } 5950 5951 // Look for any generic query activities that are duplicates 5952 // of this specific one, and remove them from the results. 5953 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5954 N = results.size(); 5955 int j; 5956 for (j=specificsPos; j<N; j++) { 5957 ResolveInfo sri = results.get(j); 5958 if ((sri.activityInfo.name.equals(comp.getClassName()) 5959 && sri.activityInfo.applicationInfo.packageName.equals( 5960 comp.getPackageName())) 5961 || (action != null && sri.filter.matchAction(action))) { 5962 results.remove(j); 5963 if (DEBUG_INTENT_MATCHING) Log.v( 5964 TAG, "Removing duplicate item from " + j 5965 + " due to specific " + specificsPos); 5966 if (ri == null) { 5967 ri = sri; 5968 } 5969 j--; 5970 N--; 5971 } 5972 } 5973 5974 // Add this specific item to its proper place. 5975 if (ri == null) { 5976 ri = new ResolveInfo(); 5977 ri.activityInfo = ai; 5978 } 5979 results.add(specificsPos, ri); 5980 ri.specificIndex = i; 5981 specificsPos++; 5982 } 5983 } 5984 5985 // Now we go through the remaining generic results and remove any 5986 // duplicate actions that are found here. 5987 N = results.size(); 5988 for (int i=specificsPos; i<N-1; i++) { 5989 final ResolveInfo rii = results.get(i); 5990 if (rii.filter == null) { 5991 continue; 5992 } 5993 5994 // Iterate over all of the actions of this result's intent 5995 // filter... typically this should be just one. 5996 final Iterator<String> it = rii.filter.actionsIterator(); 5997 if (it == null) { 5998 continue; 5999 } 6000 while (it.hasNext()) { 6001 final String action = it.next(); 6002 if (resultsAction != null && resultsAction.equals(action)) { 6003 // If this action was explicitly requested, then don't 6004 // remove things that have it. 6005 continue; 6006 } 6007 for (int j=i+1; j<N; j++) { 6008 final ResolveInfo rij = results.get(j); 6009 if (rij.filter != null && rij.filter.hasAction(action)) { 6010 results.remove(j); 6011 if (DEBUG_INTENT_MATCHING) Log.v( 6012 TAG, "Removing duplicate item from " + j 6013 + " due to action " + action + " at " + i); 6014 j--; 6015 N--; 6016 } 6017 } 6018 } 6019 6020 // If the caller didn't request filter information, drop it now 6021 // so we don't have to marshall/unmarshall it. 6022 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6023 rii.filter = null; 6024 } 6025 } 6026 6027 // Filter out the caller activity if so requested. 6028 if (caller != null) { 6029 N = results.size(); 6030 for (int i=0; i<N; i++) { 6031 ActivityInfo ainfo = results.get(i).activityInfo; 6032 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6033 && caller.getClassName().equals(ainfo.name)) { 6034 results.remove(i); 6035 break; 6036 } 6037 } 6038 } 6039 6040 // If the caller didn't request filter information, 6041 // drop them now so we don't have to 6042 // marshall/unmarshall it. 6043 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6044 N = results.size(); 6045 for (int i=0; i<N; i++) { 6046 results.get(i).filter = null; 6047 } 6048 } 6049 6050 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6051 return results; 6052 } 6053 6054 @Override 6055 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6056 String resolvedType, int flags, int userId) { 6057 return new ParceledListSlice<>( 6058 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6059 } 6060 6061 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6062 String resolvedType, int flags, int userId) { 6063 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6064 flags = updateFlagsForResolve(flags, userId, intent); 6065 ComponentName comp = intent.getComponent(); 6066 if (comp == null) { 6067 if (intent.getSelector() != null) { 6068 intent = intent.getSelector(); 6069 comp = intent.getComponent(); 6070 } 6071 } 6072 if (comp != null) { 6073 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6074 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6075 if (ai != null) { 6076 ResolveInfo ri = new ResolveInfo(); 6077 ri.activityInfo = ai; 6078 list.add(ri); 6079 } 6080 return list; 6081 } 6082 6083 // reader 6084 synchronized (mPackages) { 6085 String pkgName = intent.getPackage(); 6086 if (pkgName == null) { 6087 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6088 } 6089 final PackageParser.Package pkg = mPackages.get(pkgName); 6090 if (pkg != null) { 6091 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6092 userId); 6093 } 6094 return Collections.emptyList(); 6095 } 6096 } 6097 6098 @Override 6099 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6100 if (!sUserManager.exists(userId)) return null; 6101 flags = updateFlagsForResolve(flags, userId, intent); 6102 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6103 if (query != null) { 6104 if (query.size() >= 1) { 6105 // If there is more than one service with the same priority, 6106 // just arbitrarily pick the first one. 6107 return query.get(0); 6108 } 6109 } 6110 return null; 6111 } 6112 6113 @Override 6114 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6115 String resolvedType, int flags, int userId) { 6116 return new ParceledListSlice<>( 6117 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6118 } 6119 6120 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6121 String resolvedType, int flags, int userId) { 6122 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6123 flags = updateFlagsForResolve(flags, userId, intent); 6124 ComponentName comp = intent.getComponent(); 6125 if (comp == null) { 6126 if (intent.getSelector() != null) { 6127 intent = intent.getSelector(); 6128 comp = intent.getComponent(); 6129 } 6130 } 6131 if (comp != null) { 6132 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6133 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6134 if (si != null) { 6135 final ResolveInfo ri = new ResolveInfo(); 6136 ri.serviceInfo = si; 6137 list.add(ri); 6138 } 6139 return list; 6140 } 6141 6142 // reader 6143 synchronized (mPackages) { 6144 String pkgName = intent.getPackage(); 6145 if (pkgName == null) { 6146 return mServices.queryIntent(intent, resolvedType, flags, userId); 6147 } 6148 final PackageParser.Package pkg = mPackages.get(pkgName); 6149 if (pkg != null) { 6150 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6151 userId); 6152 } 6153 return Collections.emptyList(); 6154 } 6155 } 6156 6157 @Override 6158 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6159 String resolvedType, int flags, int userId) { 6160 return new ParceledListSlice<>( 6161 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6162 } 6163 6164 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6165 Intent intent, String resolvedType, int flags, int userId) { 6166 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6167 flags = updateFlagsForResolve(flags, userId, intent); 6168 ComponentName comp = intent.getComponent(); 6169 if (comp == null) { 6170 if (intent.getSelector() != null) { 6171 intent = intent.getSelector(); 6172 comp = intent.getComponent(); 6173 } 6174 } 6175 if (comp != null) { 6176 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6177 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6178 if (pi != null) { 6179 final ResolveInfo ri = new ResolveInfo(); 6180 ri.providerInfo = pi; 6181 list.add(ri); 6182 } 6183 return list; 6184 } 6185 6186 // reader 6187 synchronized (mPackages) { 6188 String pkgName = intent.getPackage(); 6189 if (pkgName == null) { 6190 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6191 } 6192 final PackageParser.Package pkg = mPackages.get(pkgName); 6193 if (pkg != null) { 6194 return mProviders.queryIntentForPackage( 6195 intent, resolvedType, flags, pkg.providers, userId); 6196 } 6197 return Collections.emptyList(); 6198 } 6199 } 6200 6201 @Override 6202 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6203 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6204 flags = updateFlagsForPackage(flags, userId, null); 6205 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6206 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6207 true /* requireFullPermission */, false /* checkShell */, 6208 "get installed packages"); 6209 6210 // writer 6211 synchronized (mPackages) { 6212 ArrayList<PackageInfo> list; 6213 if (listUninstalled) { 6214 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6215 for (PackageSetting ps : mSettings.mPackages.values()) { 6216 final PackageInfo pi; 6217 if (ps.pkg != null) { 6218 pi = generatePackageInfo(ps, flags, userId); 6219 } else { 6220 pi = generatePackageInfo(ps, flags, userId); 6221 } 6222 if (pi != null) { 6223 list.add(pi); 6224 } 6225 } 6226 } else { 6227 list = new ArrayList<PackageInfo>(mPackages.size()); 6228 for (PackageParser.Package p : mPackages.values()) { 6229 final PackageInfo pi = 6230 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6231 if (pi != null) { 6232 list.add(pi); 6233 } 6234 } 6235 } 6236 6237 return new ParceledListSlice<PackageInfo>(list); 6238 } 6239 } 6240 6241 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6242 String[] permissions, boolean[] tmp, int flags, int userId) { 6243 int numMatch = 0; 6244 final PermissionsState permissionsState = ps.getPermissionsState(); 6245 for (int i=0; i<permissions.length; i++) { 6246 final String permission = permissions[i]; 6247 if (permissionsState.hasPermission(permission, userId)) { 6248 tmp[i] = true; 6249 numMatch++; 6250 } else { 6251 tmp[i] = false; 6252 } 6253 } 6254 if (numMatch == 0) { 6255 return; 6256 } 6257 final PackageInfo pi; 6258 if (ps.pkg != null) { 6259 pi = generatePackageInfo(ps, flags, userId); 6260 } else { 6261 pi = generatePackageInfo(ps, flags, userId); 6262 } 6263 // The above might return null in cases of uninstalled apps or install-state 6264 // skew across users/profiles. 6265 if (pi != null) { 6266 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6267 if (numMatch == permissions.length) { 6268 pi.requestedPermissions = permissions; 6269 } else { 6270 pi.requestedPermissions = new String[numMatch]; 6271 numMatch = 0; 6272 for (int i=0; i<permissions.length; i++) { 6273 if (tmp[i]) { 6274 pi.requestedPermissions[numMatch] = permissions[i]; 6275 numMatch++; 6276 } 6277 } 6278 } 6279 } 6280 list.add(pi); 6281 } 6282 } 6283 6284 @Override 6285 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6286 String[] permissions, int flags, int userId) { 6287 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6288 flags = updateFlagsForPackage(flags, userId, permissions); 6289 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6290 6291 // writer 6292 synchronized (mPackages) { 6293 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6294 boolean[] tmpBools = new boolean[permissions.length]; 6295 if (listUninstalled) { 6296 for (PackageSetting ps : mSettings.mPackages.values()) { 6297 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6298 } 6299 } else { 6300 for (PackageParser.Package pkg : mPackages.values()) { 6301 PackageSetting ps = (PackageSetting)pkg.mExtras; 6302 if (ps != null) { 6303 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6304 userId); 6305 } 6306 } 6307 } 6308 6309 return new ParceledListSlice<PackageInfo>(list); 6310 } 6311 } 6312 6313 @Override 6314 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6315 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6316 flags = updateFlagsForApplication(flags, userId, null); 6317 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6318 6319 // writer 6320 synchronized (mPackages) { 6321 ArrayList<ApplicationInfo> list; 6322 if (listUninstalled) { 6323 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6324 for (PackageSetting ps : mSettings.mPackages.values()) { 6325 ApplicationInfo ai; 6326 if (ps.pkg != null) { 6327 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6328 ps.readUserState(userId), userId); 6329 } else { 6330 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6331 } 6332 if (ai != null) { 6333 list.add(ai); 6334 } 6335 } 6336 } else { 6337 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6338 for (PackageParser.Package p : mPackages.values()) { 6339 if (p.mExtras != null) { 6340 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6341 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6342 if (ai != null) { 6343 list.add(ai); 6344 } 6345 } 6346 } 6347 } 6348 6349 return new ParceledListSlice<ApplicationInfo>(list); 6350 } 6351 } 6352 6353 @Override 6354 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6355 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6356 return null; 6357 } 6358 6359 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6360 "getEphemeralApplications"); 6361 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6362 true /* requireFullPermission */, false /* checkShell */, 6363 "getEphemeralApplications"); 6364 synchronized (mPackages) { 6365 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6366 .getEphemeralApplicationsLPw(userId); 6367 if (ephemeralApps != null) { 6368 return new ParceledListSlice<>(ephemeralApps); 6369 } 6370 } 6371 return null; 6372 } 6373 6374 @Override 6375 public boolean isEphemeralApplication(String packageName, int userId) { 6376 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6377 true /* requireFullPermission */, false /* checkShell */, 6378 "isEphemeral"); 6379 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6380 return false; 6381 } 6382 6383 if (!isCallerSameApp(packageName)) { 6384 return false; 6385 } 6386 synchronized (mPackages) { 6387 PackageParser.Package pkg = mPackages.get(packageName); 6388 if (pkg != null) { 6389 return pkg.applicationInfo.isEphemeralApp(); 6390 } 6391 } 6392 return false; 6393 } 6394 6395 @Override 6396 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6397 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6398 return null; 6399 } 6400 6401 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6402 true /* requireFullPermission */, false /* checkShell */, 6403 "getCookie"); 6404 if (!isCallerSameApp(packageName)) { 6405 return null; 6406 } 6407 synchronized (mPackages) { 6408 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6409 packageName, userId); 6410 } 6411 } 6412 6413 @Override 6414 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6415 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6416 return true; 6417 } 6418 6419 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6420 true /* requireFullPermission */, true /* checkShell */, 6421 "setCookie"); 6422 if (!isCallerSameApp(packageName)) { 6423 return false; 6424 } 6425 synchronized (mPackages) { 6426 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6427 packageName, cookie, userId); 6428 } 6429 } 6430 6431 @Override 6432 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6433 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6434 return null; 6435 } 6436 6437 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6438 "getEphemeralApplicationIcon"); 6439 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6440 true /* requireFullPermission */, false /* checkShell */, 6441 "getEphemeralApplicationIcon"); 6442 synchronized (mPackages) { 6443 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6444 packageName, userId); 6445 } 6446 } 6447 6448 private boolean isCallerSameApp(String packageName) { 6449 PackageParser.Package pkg = mPackages.get(packageName); 6450 return pkg != null 6451 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6452 } 6453 6454 @Override 6455 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6456 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6457 } 6458 6459 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6460 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6461 6462 // reader 6463 synchronized (mPackages) { 6464 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6465 final int userId = UserHandle.getCallingUserId(); 6466 while (i.hasNext()) { 6467 final PackageParser.Package p = i.next(); 6468 if (p.applicationInfo == null) continue; 6469 6470 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6471 && !p.applicationInfo.isDirectBootAware(); 6472 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6473 && p.applicationInfo.isDirectBootAware(); 6474 6475 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6476 && (!mSafeMode || isSystemApp(p)) 6477 && (matchesUnaware || matchesAware)) { 6478 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6479 if (ps != null) { 6480 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6481 ps.readUserState(userId), userId); 6482 if (ai != null) { 6483 finalList.add(ai); 6484 } 6485 } 6486 } 6487 } 6488 } 6489 6490 return finalList; 6491 } 6492 6493 @Override 6494 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6495 if (!sUserManager.exists(userId)) return null; 6496 flags = updateFlagsForComponent(flags, userId, name); 6497 // reader 6498 synchronized (mPackages) { 6499 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6500 PackageSetting ps = provider != null 6501 ? mSettings.mPackages.get(provider.owner.packageName) 6502 : null; 6503 return ps != null 6504 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6505 ? PackageParser.generateProviderInfo(provider, flags, 6506 ps.readUserState(userId), userId) 6507 : null; 6508 } 6509 } 6510 6511 /** 6512 * @deprecated 6513 */ 6514 @Deprecated 6515 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6516 // reader 6517 synchronized (mPackages) { 6518 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6519 .entrySet().iterator(); 6520 final int userId = UserHandle.getCallingUserId(); 6521 while (i.hasNext()) { 6522 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6523 PackageParser.Provider p = entry.getValue(); 6524 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6525 6526 if (ps != null && p.syncable 6527 && (!mSafeMode || (p.info.applicationInfo.flags 6528 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6529 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6530 ps.readUserState(userId), userId); 6531 if (info != null) { 6532 outNames.add(entry.getKey()); 6533 outInfo.add(info); 6534 } 6535 } 6536 } 6537 } 6538 } 6539 6540 @Override 6541 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6542 int uid, int flags) { 6543 final int userId = processName != null ? UserHandle.getUserId(uid) 6544 : UserHandle.getCallingUserId(); 6545 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6546 flags = updateFlagsForComponent(flags, userId, processName); 6547 6548 ArrayList<ProviderInfo> finalList = null; 6549 // reader 6550 synchronized (mPackages) { 6551 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6552 while (i.hasNext()) { 6553 final PackageParser.Provider p = i.next(); 6554 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6555 if (ps != null && p.info.authority != null 6556 && (processName == null 6557 || (p.info.processName.equals(processName) 6558 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6559 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6560 if (finalList == null) { 6561 finalList = new ArrayList<ProviderInfo>(3); 6562 } 6563 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6564 ps.readUserState(userId), userId); 6565 if (info != null) { 6566 finalList.add(info); 6567 } 6568 } 6569 } 6570 } 6571 6572 if (finalList != null) { 6573 Collections.sort(finalList, mProviderInitOrderSorter); 6574 return new ParceledListSlice<ProviderInfo>(finalList); 6575 } 6576 6577 return ParceledListSlice.emptyList(); 6578 } 6579 6580 @Override 6581 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6582 // reader 6583 synchronized (mPackages) { 6584 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6585 return PackageParser.generateInstrumentationInfo(i, flags); 6586 } 6587 } 6588 6589 @Override 6590 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6591 String targetPackage, int flags) { 6592 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6593 } 6594 6595 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6596 int flags) { 6597 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6598 6599 // reader 6600 synchronized (mPackages) { 6601 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6602 while (i.hasNext()) { 6603 final PackageParser.Instrumentation p = i.next(); 6604 if (targetPackage == null 6605 || targetPackage.equals(p.info.targetPackage)) { 6606 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6607 flags); 6608 if (ii != null) { 6609 finalList.add(ii); 6610 } 6611 } 6612 } 6613 } 6614 6615 return finalList; 6616 } 6617 6618 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6619 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6620 if (overlays == null) { 6621 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6622 return; 6623 } 6624 for (PackageParser.Package opkg : overlays.values()) { 6625 // Not much to do if idmap fails: we already logged the error 6626 // and we certainly don't want to abort installation of pkg simply 6627 // because an overlay didn't fit properly. For these reasons, 6628 // ignore the return value of createIdmapForPackagePairLI. 6629 createIdmapForPackagePairLI(pkg, opkg); 6630 } 6631 } 6632 6633 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6634 PackageParser.Package opkg) { 6635 if (!opkg.mTrustedOverlay) { 6636 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6637 opkg.baseCodePath + ": overlay not trusted"); 6638 return false; 6639 } 6640 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6641 if (overlaySet == null) { 6642 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6643 opkg.baseCodePath + " but target package has no known overlays"); 6644 return false; 6645 } 6646 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6647 // TODO: generate idmap for split APKs 6648 try { 6649 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6650 } catch (InstallerException e) { 6651 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6652 + opkg.baseCodePath); 6653 return false; 6654 } 6655 PackageParser.Package[] overlayArray = 6656 overlaySet.values().toArray(new PackageParser.Package[0]); 6657 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6658 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6659 return p1.mOverlayPriority - p2.mOverlayPriority; 6660 } 6661 }; 6662 Arrays.sort(overlayArray, cmp); 6663 6664 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6665 int i = 0; 6666 for (PackageParser.Package p : overlayArray) { 6667 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6668 } 6669 return true; 6670 } 6671 6672 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6673 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6674 try { 6675 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6676 } finally { 6677 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6678 } 6679 } 6680 6681 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6682 final File[] files = dir.listFiles(); 6683 if (ArrayUtils.isEmpty(files)) { 6684 Log.d(TAG, "No files in app dir " + dir); 6685 return; 6686 } 6687 6688 if (DEBUG_PACKAGE_SCANNING) { 6689 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6690 + " flags=0x" + Integer.toHexString(parseFlags)); 6691 } 6692 6693 for (File file : files) { 6694 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6695 && !PackageInstallerService.isStageName(file.getName()); 6696 if (!isPackage) { 6697 // Ignore entries which are not packages 6698 continue; 6699 } 6700 try { 6701 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6702 scanFlags, currentTime, null); 6703 } catch (PackageManagerException e) { 6704 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6705 6706 // Delete invalid userdata apps 6707 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6708 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6709 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6710 removeCodePathLI(file); 6711 } 6712 } 6713 } 6714 } 6715 6716 private static File getSettingsProblemFile() { 6717 File dataDir = Environment.getDataDirectory(); 6718 File systemDir = new File(dataDir, "system"); 6719 File fname = new File(systemDir, "uiderrors.txt"); 6720 return fname; 6721 } 6722 6723 static void reportSettingsProblem(int priority, String msg) { 6724 logCriticalInfo(priority, msg); 6725 } 6726 6727 static void logCriticalInfo(int priority, String msg) { 6728 Slog.println(priority, TAG, msg); 6729 EventLogTags.writePmCriticalInfo(msg); 6730 try { 6731 File fname = getSettingsProblemFile(); 6732 FileOutputStream out = new FileOutputStream(fname, true); 6733 PrintWriter pw = new FastPrintWriter(out); 6734 SimpleDateFormat formatter = new SimpleDateFormat(); 6735 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6736 pw.println(dateString + ": " + msg); 6737 pw.close(); 6738 FileUtils.setPermissions( 6739 fname.toString(), 6740 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6741 -1, -1); 6742 } catch (java.io.IOException e) { 6743 } 6744 } 6745 6746 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6747 if (srcFile.isDirectory()) { 6748 final File baseFile = new File(pkg.baseCodePath); 6749 long maxModifiedTime = baseFile.lastModified(); 6750 if (pkg.splitCodePaths != null) { 6751 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6752 final File splitFile = new File(pkg.splitCodePaths[i]); 6753 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6754 } 6755 } 6756 return maxModifiedTime; 6757 } 6758 return srcFile.lastModified(); 6759 } 6760 6761 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6762 final int policyFlags) throws PackageManagerException { 6763 // When upgrading from pre-N MR1, verify the package time stamp using the package 6764 // directory and not the APK file. 6765 final long lastModifiedTime = mIsPreNMR1Upgrade 6766 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 6767 if (ps != null 6768 && ps.codePath.equals(srcFile) 6769 && ps.timeStamp == lastModifiedTime 6770 && !isCompatSignatureUpdateNeeded(pkg) 6771 && !isRecoverSignatureUpdateNeeded(pkg)) { 6772 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6773 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6774 ArraySet<PublicKey> signingKs; 6775 synchronized (mPackages) { 6776 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6777 } 6778 if (ps.signatures.mSignatures != null 6779 && ps.signatures.mSignatures.length != 0 6780 && signingKs != null) { 6781 // Optimization: reuse the existing cached certificates 6782 // if the package appears to be unchanged. 6783 pkg.mSignatures = ps.signatures.mSignatures; 6784 pkg.mSigningKeys = signingKs; 6785 return; 6786 } 6787 6788 Slog.w(TAG, "PackageSetting for " + ps.name 6789 + " is missing signatures. Collecting certs again to recover them."); 6790 } else { 6791 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 6792 } 6793 6794 try { 6795 PackageParser.collectCertificates(pkg, policyFlags); 6796 } catch (PackageParserException e) { 6797 throw PackageManagerException.from(e); 6798 } 6799 } 6800 6801 /** 6802 * Traces a package scan. 6803 * @see #scanPackageLI(File, int, int, long, UserHandle) 6804 */ 6805 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6806 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6807 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6808 try { 6809 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6810 } finally { 6811 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6812 } 6813 } 6814 6815 /** 6816 * Scans a package and returns the newly parsed package. 6817 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6818 */ 6819 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6820 long currentTime, UserHandle user) throws PackageManagerException { 6821 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6822 PackageParser pp = new PackageParser(); 6823 pp.setSeparateProcesses(mSeparateProcesses); 6824 pp.setOnlyCoreApps(mOnlyCore); 6825 pp.setDisplayMetrics(mMetrics); 6826 6827 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6828 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6829 } 6830 6831 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6832 final PackageParser.Package pkg; 6833 try { 6834 pkg = pp.parsePackage(scanFile, parseFlags); 6835 } catch (PackageParserException e) { 6836 throw PackageManagerException.from(e); 6837 } finally { 6838 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6839 } 6840 6841 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6842 } 6843 6844 /** 6845 * Scans a package and returns the newly parsed package. 6846 * @throws PackageManagerException on a parse error. 6847 */ 6848 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6849 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6850 throws PackageManagerException { 6851 // If the package has children and this is the first dive in the function 6852 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6853 // packages (parent and children) would be successfully scanned before the 6854 // actual scan since scanning mutates internal state and we want to atomically 6855 // install the package and its children. 6856 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6857 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6858 scanFlags |= SCAN_CHECK_ONLY; 6859 } 6860 } else { 6861 scanFlags &= ~SCAN_CHECK_ONLY; 6862 } 6863 6864 // Scan the parent 6865 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6866 scanFlags, currentTime, user); 6867 6868 // Scan the children 6869 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6870 for (int i = 0; i < childCount; i++) { 6871 PackageParser.Package childPackage = pkg.childPackages.get(i); 6872 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6873 currentTime, user); 6874 } 6875 6876 6877 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6878 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6879 } 6880 6881 return scannedPkg; 6882 } 6883 6884 /** 6885 * Scans a package and returns the newly parsed package. 6886 * @throws PackageManagerException on a parse error. 6887 */ 6888 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6889 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6890 throws PackageManagerException { 6891 PackageSetting ps = null; 6892 PackageSetting updatedPkg; 6893 // reader 6894 synchronized (mPackages) { 6895 // Look to see if we already know about this package. 6896 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6897 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6898 // This package has been renamed to its original name. Let's 6899 // use that. 6900 ps = mSettings.peekPackageLPr(oldName); 6901 } 6902 // If there was no original package, see one for the real package name. 6903 if (ps == null) { 6904 ps = mSettings.peekPackageLPr(pkg.packageName); 6905 } 6906 // Check to see if this package could be hiding/updating a system 6907 // package. Must look for it either under the original or real 6908 // package name depending on our state. 6909 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6910 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6911 6912 // If this is a package we don't know about on the system partition, we 6913 // may need to remove disabled child packages on the system partition 6914 // or may need to not add child packages if the parent apk is updated 6915 // on the data partition and no longer defines this child package. 6916 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6917 // If this is a parent package for an updated system app and this system 6918 // app got an OTA update which no longer defines some of the child packages 6919 // we have to prune them from the disabled system packages. 6920 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6921 if (disabledPs != null) { 6922 final int scannedChildCount = (pkg.childPackages != null) 6923 ? pkg.childPackages.size() : 0; 6924 final int disabledChildCount = disabledPs.childPackageNames != null 6925 ? disabledPs.childPackageNames.size() : 0; 6926 for (int i = 0; i < disabledChildCount; i++) { 6927 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6928 boolean disabledPackageAvailable = false; 6929 for (int j = 0; j < scannedChildCount; j++) { 6930 PackageParser.Package childPkg = pkg.childPackages.get(j); 6931 if (childPkg.packageName.equals(disabledChildPackageName)) { 6932 disabledPackageAvailable = true; 6933 break; 6934 } 6935 } 6936 if (!disabledPackageAvailable) { 6937 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6938 } 6939 } 6940 } 6941 } 6942 } 6943 6944 boolean updatedPkgBetter = false; 6945 // First check if this is a system package that may involve an update 6946 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6947 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6948 // it needs to drop FLAG_PRIVILEGED. 6949 if (locationIsPrivileged(scanFile)) { 6950 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6951 } else { 6952 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6953 } 6954 6955 if (ps != null && !ps.codePath.equals(scanFile)) { 6956 // The path has changed from what was last scanned... check the 6957 // version of the new path against what we have stored to determine 6958 // what to do. 6959 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6960 if (pkg.mVersionCode <= ps.versionCode) { 6961 // The system package has been updated and the code path does not match 6962 // Ignore entry. Skip it. 6963 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6964 + " ignored: updated version " + ps.versionCode 6965 + " better than this " + pkg.mVersionCode); 6966 if (!updatedPkg.codePath.equals(scanFile)) { 6967 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6968 + ps.name + " changing from " + updatedPkg.codePathString 6969 + " to " + scanFile); 6970 updatedPkg.codePath = scanFile; 6971 updatedPkg.codePathString = scanFile.toString(); 6972 updatedPkg.resourcePath = scanFile; 6973 updatedPkg.resourcePathString = scanFile.toString(); 6974 } 6975 updatedPkg.pkg = pkg; 6976 updatedPkg.versionCode = pkg.mVersionCode; 6977 6978 // Update the disabled system child packages to point to the package too. 6979 final int childCount = updatedPkg.childPackageNames != null 6980 ? updatedPkg.childPackageNames.size() : 0; 6981 for (int i = 0; i < childCount; i++) { 6982 String childPackageName = updatedPkg.childPackageNames.get(i); 6983 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6984 childPackageName); 6985 if (updatedChildPkg != null) { 6986 updatedChildPkg.pkg = pkg; 6987 updatedChildPkg.versionCode = pkg.mVersionCode; 6988 } 6989 } 6990 6991 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6992 + scanFile + " ignored: updated version " + ps.versionCode 6993 + " better than this " + pkg.mVersionCode); 6994 } else { 6995 // The current app on the system partition is better than 6996 // what we have updated to on the data partition; switch 6997 // back to the system partition version. 6998 // At this point, its safely assumed that package installation for 6999 // apps in system partition will go through. If not there won't be a working 7000 // version of the app 7001 // writer 7002 synchronized (mPackages) { 7003 // Just remove the loaded entries from package lists. 7004 mPackages.remove(ps.name); 7005 } 7006 7007 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7008 + " reverting from " + ps.codePathString 7009 + ": new version " + pkg.mVersionCode 7010 + " better than installed " + ps.versionCode); 7011 7012 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7013 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7014 synchronized (mInstallLock) { 7015 args.cleanUpResourcesLI(); 7016 } 7017 synchronized (mPackages) { 7018 mSettings.enableSystemPackageLPw(ps.name); 7019 } 7020 updatedPkgBetter = true; 7021 } 7022 } 7023 } 7024 7025 if (updatedPkg != null) { 7026 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7027 // initially 7028 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7029 7030 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7031 // flag set initially 7032 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7033 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7034 } 7035 } 7036 7037 // Verify certificates against what was last scanned 7038 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7039 7040 /* 7041 * A new system app appeared, but we already had a non-system one of the 7042 * same name installed earlier. 7043 */ 7044 boolean shouldHideSystemApp = false; 7045 if (updatedPkg == null && ps != null 7046 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7047 /* 7048 * Check to make sure the signatures match first. If they don't, 7049 * wipe the installed application and its data. 7050 */ 7051 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7052 != PackageManager.SIGNATURE_MATCH) { 7053 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7054 + " signatures don't match existing userdata copy; removing"); 7055 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7056 "scanPackageInternalLI")) { 7057 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7058 } 7059 ps = null; 7060 } else { 7061 /* 7062 * If the newly-added system app is an older version than the 7063 * already installed version, hide it. It will be scanned later 7064 * and re-added like an update. 7065 */ 7066 if (pkg.mVersionCode <= ps.versionCode) { 7067 shouldHideSystemApp = true; 7068 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7069 + " but new version " + pkg.mVersionCode + " better than installed " 7070 + ps.versionCode + "; hiding system"); 7071 } else { 7072 /* 7073 * The newly found system app is a newer version that the 7074 * one previously installed. Simply remove the 7075 * already-installed application and replace it with our own 7076 * while keeping the application data. 7077 */ 7078 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7079 + " reverting from " + ps.codePathString + ": new version " 7080 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7081 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7082 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7083 synchronized (mInstallLock) { 7084 args.cleanUpResourcesLI(); 7085 } 7086 } 7087 } 7088 } 7089 7090 // The apk is forward locked (not public) if its code and resources 7091 // are kept in different files. (except for app in either system or 7092 // vendor path). 7093 // TODO grab this value from PackageSettings 7094 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7095 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7096 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7097 } 7098 } 7099 7100 // TODO: extend to support forward-locked splits 7101 String resourcePath = null; 7102 String baseResourcePath = null; 7103 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7104 if (ps != null && ps.resourcePathString != null) { 7105 resourcePath = ps.resourcePathString; 7106 baseResourcePath = ps.resourcePathString; 7107 } else { 7108 // Should not happen at all. Just log an error. 7109 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7110 } 7111 } else { 7112 resourcePath = pkg.codePath; 7113 baseResourcePath = pkg.baseCodePath; 7114 } 7115 7116 // Set application objects path explicitly. 7117 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7118 pkg.setApplicationInfoCodePath(pkg.codePath); 7119 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7120 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7121 pkg.setApplicationInfoResourcePath(resourcePath); 7122 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7123 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7124 7125 // Note that we invoke the following method only if we are about to unpack an application 7126 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7127 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7128 7129 /* 7130 * If the system app should be overridden by a previously installed 7131 * data, hide the system app now and let the /data/app scan pick it up 7132 * again. 7133 */ 7134 if (shouldHideSystemApp) { 7135 synchronized (mPackages) { 7136 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7137 } 7138 } 7139 7140 return scannedPkg; 7141 } 7142 7143 private static String fixProcessName(String defProcessName, 7144 String processName, int uid) { 7145 if (processName == null) { 7146 return defProcessName; 7147 } 7148 return processName; 7149 } 7150 7151 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7152 throws PackageManagerException { 7153 if (pkgSetting.signatures.mSignatures != null) { 7154 // Already existing package. Make sure signatures match 7155 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7156 == PackageManager.SIGNATURE_MATCH; 7157 if (!match) { 7158 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7159 == PackageManager.SIGNATURE_MATCH; 7160 } 7161 if (!match) { 7162 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7163 == PackageManager.SIGNATURE_MATCH; 7164 } 7165 if (!match) { 7166 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7167 + pkg.packageName + " signatures do not match the " 7168 + "previously installed version; ignoring!"); 7169 } 7170 } 7171 7172 // Check for shared user signatures 7173 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7174 // Already existing package. Make sure signatures match 7175 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7176 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7177 if (!match) { 7178 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7179 == PackageManager.SIGNATURE_MATCH; 7180 } 7181 if (!match) { 7182 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7183 == PackageManager.SIGNATURE_MATCH; 7184 } 7185 if (!match) { 7186 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7187 "Package " + pkg.packageName 7188 + " has no signatures that match those in shared user " 7189 + pkgSetting.sharedUser.name + "; ignoring!"); 7190 } 7191 } 7192 } 7193 7194 /** 7195 * Enforces that only the system UID or root's UID can call a method exposed 7196 * via Binder. 7197 * 7198 * @param message used as message if SecurityException is thrown 7199 * @throws SecurityException if the caller is not system or root 7200 */ 7201 private static final void enforceSystemOrRoot(String message) { 7202 final int uid = Binder.getCallingUid(); 7203 if (uid != Process.SYSTEM_UID && uid != 0) { 7204 throw new SecurityException(message); 7205 } 7206 } 7207 7208 @Override 7209 public void performFstrimIfNeeded() { 7210 enforceSystemOrRoot("Only the system can request fstrim"); 7211 7212 // Before everything else, see whether we need to fstrim. 7213 try { 7214 IMountService ms = PackageHelper.getMountService(); 7215 if (ms != null) { 7216 boolean doTrim = false; 7217 final long interval = android.provider.Settings.Global.getLong( 7218 mContext.getContentResolver(), 7219 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7220 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7221 if (interval > 0) { 7222 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7223 if (timeSinceLast > interval) { 7224 doTrim = true; 7225 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7226 + "; running immediately"); 7227 } 7228 } 7229 if (doTrim) { 7230 final boolean dexOptDialogShown; 7231 synchronized (mPackages) { 7232 dexOptDialogShown = mDexOptDialogShown; 7233 } 7234 if (!isFirstBoot() && dexOptDialogShown) { 7235 try { 7236 ActivityManagerNative.getDefault().showBootMessage( 7237 mContext.getResources().getString( 7238 R.string.android_upgrading_fstrim), true); 7239 } catch (RemoteException e) { 7240 } 7241 } 7242 ms.runMaintenance(); 7243 } 7244 } else { 7245 Slog.e(TAG, "Mount service unavailable!"); 7246 } 7247 } catch (RemoteException e) { 7248 // Can't happen; MountService is local 7249 } 7250 } 7251 7252 @Override 7253 public void updatePackagesIfNeeded() { 7254 enforceSystemOrRoot("Only the system can request package update"); 7255 7256 // We need to re-extract after an OTA. 7257 boolean causeUpgrade = isUpgrade(); 7258 7259 // First boot or factory reset. 7260 // Note: we also handle devices that are upgrading to N right now as if it is their 7261 // first boot, as they do not have profile data. 7262 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7263 7264 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7265 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7266 7267 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7268 return; 7269 } 7270 7271 List<PackageParser.Package> pkgs; 7272 synchronized (mPackages) { 7273 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7274 } 7275 7276 final long startTime = System.nanoTime(); 7277 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7278 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7279 7280 final int elapsedTimeSeconds = 7281 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7282 7283 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7284 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7285 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7286 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7287 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7288 } 7289 7290 /** 7291 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7292 * containing statistics about the invocation. The array consists of three elements, 7293 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7294 * and {@code numberOfPackagesFailed}. 7295 */ 7296 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7297 String compilerFilter) { 7298 7299 int numberOfPackagesVisited = 0; 7300 int numberOfPackagesOptimized = 0; 7301 int numberOfPackagesSkipped = 0; 7302 int numberOfPackagesFailed = 0; 7303 final int numberOfPackagesToDexopt = pkgs.size(); 7304 7305 for (PackageParser.Package pkg : pkgs) { 7306 numberOfPackagesVisited++; 7307 7308 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7309 if (DEBUG_DEXOPT) { 7310 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7311 } 7312 numberOfPackagesSkipped++; 7313 continue; 7314 } 7315 7316 if (DEBUG_DEXOPT) { 7317 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7318 numberOfPackagesToDexopt + ": " + pkg.packageName); 7319 } 7320 7321 if (showDialog) { 7322 try { 7323 ActivityManagerNative.getDefault().showBootMessage( 7324 mContext.getResources().getString(R.string.android_upgrading_apk, 7325 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7326 } catch (RemoteException e) { 7327 } 7328 synchronized (mPackages) { 7329 mDexOptDialogShown = true; 7330 } 7331 } 7332 7333 // If the OTA updates a system app which was previously preopted to a non-preopted state 7334 // the app might end up being verified at runtime. That's because by default the apps 7335 // are verify-profile but for preopted apps there's no profile. 7336 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7337 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7338 // filter (by default interpret-only). 7339 // Note that at this stage unused apps are already filtered. 7340 if (isSystemApp(pkg) && 7341 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7342 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7343 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7344 } 7345 7346 // If the OTA updates a system app which was previously preopted to a non-preopted state 7347 // the app might end up being verified at runtime. That's because by default the apps 7348 // are verify-profile but for preopted apps there's no profile. 7349 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7350 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7351 // filter (by default interpret-only). 7352 // Note that at this stage unused apps are already filtered. 7353 if (isSystemApp(pkg) && 7354 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7355 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7356 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7357 } 7358 7359 // checkProfiles is false to avoid merging profiles during boot which 7360 // might interfere with background compilation (b/28612421). 7361 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7362 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7363 // trade-off worth doing to save boot time work. 7364 int dexOptStatus = performDexOptTraced(pkg.packageName, 7365 false /* checkProfiles */, 7366 compilerFilter, 7367 false /* force */); 7368 switch (dexOptStatus) { 7369 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7370 numberOfPackagesOptimized++; 7371 break; 7372 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7373 numberOfPackagesSkipped++; 7374 break; 7375 case PackageDexOptimizer.DEX_OPT_FAILED: 7376 numberOfPackagesFailed++; 7377 break; 7378 default: 7379 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7380 break; 7381 } 7382 } 7383 7384 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7385 numberOfPackagesFailed }; 7386 } 7387 7388 @Override 7389 public void notifyPackageUse(String packageName, int reason) { 7390 synchronized (mPackages) { 7391 PackageParser.Package p = mPackages.get(packageName); 7392 if (p == null) { 7393 return; 7394 } 7395 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7396 } 7397 } 7398 7399 @Override 7400 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 7401 int userId = UserHandle.getCallingUserId(); 7402 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 7403 if (ai == null) { 7404 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 7405 + loadingPackageName + ", user=" + userId); 7406 return; 7407 } 7408 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 7409 } 7410 7411 // TODO: this is not used nor needed. Delete it. 7412 @Override 7413 public boolean performDexOptIfNeeded(String packageName) { 7414 int dexOptStatus = performDexOptTraced(packageName, 7415 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7416 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7417 } 7418 7419 @Override 7420 public boolean performDexOpt(String packageName, 7421 boolean checkProfiles, int compileReason, boolean force) { 7422 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7423 getCompilerFilterForReason(compileReason), force); 7424 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7425 } 7426 7427 @Override 7428 public boolean performDexOptMode(String packageName, 7429 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7430 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7431 targetCompilerFilter, force); 7432 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7433 } 7434 7435 private int performDexOptTraced(String packageName, 7436 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7437 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7438 try { 7439 return performDexOptInternal(packageName, checkProfiles, 7440 targetCompilerFilter, force); 7441 } finally { 7442 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7443 } 7444 } 7445 7446 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7447 // if the package can now be considered up to date for the given filter. 7448 private int performDexOptInternal(String packageName, 7449 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7450 PackageParser.Package p; 7451 synchronized (mPackages) { 7452 p = mPackages.get(packageName); 7453 if (p == null) { 7454 // Package could not be found. Report failure. 7455 return PackageDexOptimizer.DEX_OPT_FAILED; 7456 } 7457 mPackageUsage.maybeWriteAsync(mPackages); 7458 mCompilerStats.maybeWriteAsync(); 7459 } 7460 long callingId = Binder.clearCallingIdentity(); 7461 try { 7462 synchronized (mInstallLock) { 7463 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7464 targetCompilerFilter, force); 7465 } 7466 } finally { 7467 Binder.restoreCallingIdentity(callingId); 7468 } 7469 } 7470 7471 public ArraySet<String> getOptimizablePackages() { 7472 ArraySet<String> pkgs = new ArraySet<String>(); 7473 synchronized (mPackages) { 7474 for (PackageParser.Package p : mPackages.values()) { 7475 if (PackageDexOptimizer.canOptimizePackage(p)) { 7476 pkgs.add(p.packageName); 7477 } 7478 } 7479 } 7480 return pkgs; 7481 } 7482 7483 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7484 boolean checkProfiles, String targetCompilerFilter, 7485 boolean force) { 7486 // Select the dex optimizer based on the force parameter. 7487 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7488 // allocate an object here. 7489 PackageDexOptimizer pdo = force 7490 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7491 : mPackageDexOptimizer; 7492 7493 // Optimize all dependencies first. Note: we ignore the return value and march on 7494 // on errors. 7495 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7496 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7497 if (!deps.isEmpty()) { 7498 for (PackageParser.Package depPackage : deps) { 7499 // TODO: Analyze and investigate if we (should) profile libraries. 7500 // Currently this will do a full compilation of the library by default. 7501 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7502 false /* checkProfiles */, 7503 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7504 getOrCreateCompilerPackageStats(depPackage)); 7505 } 7506 } 7507 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7508 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7509 } 7510 7511 // Performs dexopt on the used secondary dex files belonging to the given package. 7512 // Returns true if all dex files were process successfully (which could mean either dexopt or 7513 // skip). Returns false if any of the files caused errors. 7514 @Override 7515 public boolean performDexOptSecondary(String packageName, String compilerFilter, 7516 boolean force) { 7517 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 7518 } 7519 7520 /** 7521 * Reconcile the information we have about the secondary dex files belonging to 7522 * {@code packagName} and the actual dex files. For all dex files that were 7523 * deleted, update the internal records and delete the generated oat files. 7524 */ 7525 @Override 7526 public void reconcileSecondaryDexFiles(String packageName) { 7527 mDexManager.reconcileSecondaryDexFiles(packageName); 7528 } 7529 7530 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 7531 // a reference there. 7532 /*package*/ DexManager getDexManager() { 7533 return mDexManager; 7534 } 7535 7536 /** 7537 * Execute the background dexopt job immediately. 7538 */ 7539 @Override 7540 public boolean runBackgroundDexoptJob() { 7541 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 7542 } 7543 7544 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7545 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7546 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7547 Set<String> collectedNames = new HashSet<>(); 7548 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7549 7550 retValue.remove(p); 7551 7552 return retValue; 7553 } else { 7554 return Collections.emptyList(); 7555 } 7556 } 7557 7558 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7559 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7560 if (!collectedNames.contains(p.packageName)) { 7561 collectedNames.add(p.packageName); 7562 collected.add(p); 7563 7564 if (p.usesLibraries != null) { 7565 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7566 } 7567 if (p.usesOptionalLibraries != null) { 7568 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7569 collectedNames); 7570 } 7571 } 7572 } 7573 7574 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7575 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7576 for (String libName : libs) { 7577 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7578 if (libPkg != null) { 7579 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7580 } 7581 } 7582 } 7583 7584 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7585 synchronized (mPackages) { 7586 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7587 if (lib != null && lib.apk != null) { 7588 return mPackages.get(lib.apk); 7589 } 7590 } 7591 return null; 7592 } 7593 7594 public void shutdown() { 7595 mPackageUsage.writeNow(mPackages); 7596 mCompilerStats.writeNow(); 7597 } 7598 7599 @Override 7600 public void dumpProfiles(String packageName) { 7601 PackageParser.Package pkg; 7602 synchronized (mPackages) { 7603 pkg = mPackages.get(packageName); 7604 if (pkg == null) { 7605 throw new IllegalArgumentException("Unknown package: " + packageName); 7606 } 7607 } 7608 /* Only the shell, root, or the app user should be able to dump profiles. */ 7609 int callingUid = Binder.getCallingUid(); 7610 if (callingUid != Process.SHELL_UID && 7611 callingUid != Process.ROOT_UID && 7612 callingUid != pkg.applicationInfo.uid) { 7613 throw new SecurityException("dumpProfiles"); 7614 } 7615 7616 synchronized (mInstallLock) { 7617 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7618 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7619 try { 7620 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7621 String codePaths = TextUtils.join(";", allCodePaths); 7622 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 7623 } catch (InstallerException e) { 7624 Slog.w(TAG, "Failed to dump profiles", e); 7625 } 7626 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7627 } 7628 } 7629 7630 @Override 7631 public void forceDexOpt(String packageName) { 7632 enforceSystemOrRoot("forceDexOpt"); 7633 7634 PackageParser.Package pkg; 7635 synchronized (mPackages) { 7636 pkg = mPackages.get(packageName); 7637 if (pkg == null) { 7638 throw new IllegalArgumentException("Unknown package: " + packageName); 7639 } 7640 } 7641 7642 synchronized (mInstallLock) { 7643 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7644 7645 // Whoever is calling forceDexOpt wants a fully compiled package. 7646 // Don't use profiles since that may cause compilation to be skipped. 7647 final int res = performDexOptInternalWithDependenciesLI(pkg, 7648 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7649 true /* force */); 7650 7651 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7652 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7653 throw new IllegalStateException("Failed to dexopt: " + res); 7654 } 7655 } 7656 } 7657 7658 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7659 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7660 Slog.w(TAG, "Unable to update from " + oldPkg.name 7661 + " to " + newPkg.packageName 7662 + ": old package not in system partition"); 7663 return false; 7664 } else if (mPackages.get(oldPkg.name) != null) { 7665 Slog.w(TAG, "Unable to update from " + oldPkg.name 7666 + " to " + newPkg.packageName 7667 + ": old package still exists"); 7668 return false; 7669 } 7670 return true; 7671 } 7672 7673 void removeCodePathLI(File codePath) { 7674 if (codePath.isDirectory()) { 7675 try { 7676 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7677 } catch (InstallerException e) { 7678 Slog.w(TAG, "Failed to remove code path", e); 7679 } 7680 } else { 7681 codePath.delete(); 7682 } 7683 } 7684 7685 private int[] resolveUserIds(int userId) { 7686 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7687 } 7688 7689 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7690 if (pkg == null) { 7691 Slog.wtf(TAG, "Package was null!", new Throwable()); 7692 return; 7693 } 7694 clearAppDataLeafLIF(pkg, userId, flags); 7695 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7696 for (int i = 0; i < childCount; i++) { 7697 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7698 } 7699 } 7700 7701 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7702 final PackageSetting ps; 7703 synchronized (mPackages) { 7704 ps = mSettings.mPackages.get(pkg.packageName); 7705 } 7706 for (int realUserId : resolveUserIds(userId)) { 7707 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7708 try { 7709 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7710 ceDataInode); 7711 } catch (InstallerException e) { 7712 Slog.w(TAG, String.valueOf(e)); 7713 } 7714 } 7715 } 7716 7717 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7718 if (pkg == null) { 7719 Slog.wtf(TAG, "Package was null!", new Throwable()); 7720 return; 7721 } 7722 destroyAppDataLeafLIF(pkg, userId, flags); 7723 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7724 for (int i = 0; i < childCount; i++) { 7725 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7726 } 7727 } 7728 7729 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7730 final PackageSetting ps; 7731 synchronized (mPackages) { 7732 ps = mSettings.mPackages.get(pkg.packageName); 7733 } 7734 for (int realUserId : resolveUserIds(userId)) { 7735 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7736 try { 7737 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7738 ceDataInode); 7739 } catch (InstallerException e) { 7740 Slog.w(TAG, String.valueOf(e)); 7741 } 7742 } 7743 } 7744 7745 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7746 if (pkg == null) { 7747 Slog.wtf(TAG, "Package was null!", new Throwable()); 7748 return; 7749 } 7750 destroyAppProfilesLeafLIF(pkg); 7751 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7752 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7753 for (int i = 0; i < childCount; i++) { 7754 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7755 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7756 true /* removeBaseMarker */); 7757 } 7758 } 7759 7760 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7761 boolean removeBaseMarker) { 7762 if (pkg.isForwardLocked()) { 7763 return; 7764 } 7765 7766 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7767 try { 7768 path = PackageManagerServiceUtils.realpath(new File(path)); 7769 } catch (IOException e) { 7770 // TODO: Should we return early here ? 7771 Slog.w(TAG, "Failed to get canonical path", e); 7772 continue; 7773 } 7774 7775 final String useMarker = path.replace('/', '@'); 7776 for (int realUserId : resolveUserIds(userId)) { 7777 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7778 if (removeBaseMarker) { 7779 File foreignUseMark = new File(profileDir, useMarker); 7780 if (foreignUseMark.exists()) { 7781 if (!foreignUseMark.delete()) { 7782 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7783 + pkg.packageName); 7784 } 7785 } 7786 } 7787 7788 File[] markers = profileDir.listFiles(); 7789 if (markers != null) { 7790 final String searchString = "@" + pkg.packageName + "@"; 7791 // We also delete all markers that contain the package name we're 7792 // uninstalling. These are associated with secondary dex-files belonging 7793 // to the package. Reconstructing the path of these dex files is messy 7794 // in general. 7795 for (File marker : markers) { 7796 if (marker.getName().indexOf(searchString) > 0) { 7797 if (!marker.delete()) { 7798 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7799 + pkg.packageName); 7800 } 7801 } 7802 } 7803 } 7804 } 7805 } 7806 } 7807 7808 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7809 try { 7810 mInstaller.destroyAppProfiles(pkg.packageName); 7811 } catch (InstallerException e) { 7812 Slog.w(TAG, String.valueOf(e)); 7813 } 7814 } 7815 7816 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7817 if (pkg == null) { 7818 Slog.wtf(TAG, "Package was null!", new Throwable()); 7819 return; 7820 } 7821 clearAppProfilesLeafLIF(pkg); 7822 // We don't remove the base foreign use marker when clearing profiles because 7823 // we will rename it when the app is updated. Unlike the actual profile contents, 7824 // the foreign use marker is good across installs. 7825 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7826 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7827 for (int i = 0; i < childCount; i++) { 7828 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7829 } 7830 } 7831 7832 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7833 try { 7834 mInstaller.clearAppProfiles(pkg.packageName); 7835 } catch (InstallerException e) { 7836 Slog.w(TAG, String.valueOf(e)); 7837 } 7838 } 7839 7840 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7841 long lastUpdateTime) { 7842 // Set parent install/update time 7843 PackageSetting ps = (PackageSetting) pkg.mExtras; 7844 if (ps != null) { 7845 ps.firstInstallTime = firstInstallTime; 7846 ps.lastUpdateTime = lastUpdateTime; 7847 } 7848 // Set children install/update time 7849 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7850 for (int i = 0; i < childCount; i++) { 7851 PackageParser.Package childPkg = pkg.childPackages.get(i); 7852 ps = (PackageSetting) childPkg.mExtras; 7853 if (ps != null) { 7854 ps.firstInstallTime = firstInstallTime; 7855 ps.lastUpdateTime = lastUpdateTime; 7856 } 7857 } 7858 } 7859 7860 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7861 PackageParser.Package changingLib) { 7862 if (file.path != null) { 7863 usesLibraryFiles.add(file.path); 7864 return; 7865 } 7866 PackageParser.Package p = mPackages.get(file.apk); 7867 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7868 // If we are doing this while in the middle of updating a library apk, 7869 // then we need to make sure to use that new apk for determining the 7870 // dependencies here. (We haven't yet finished committing the new apk 7871 // to the package manager state.) 7872 if (p == null || p.packageName.equals(changingLib.packageName)) { 7873 p = changingLib; 7874 } 7875 } 7876 if (p != null) { 7877 usesLibraryFiles.addAll(p.getAllCodePaths()); 7878 } 7879 } 7880 7881 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7882 PackageParser.Package changingLib) throws PackageManagerException { 7883 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7884 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7885 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7886 for (int i=0; i<N; i++) { 7887 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7888 if (file == null) { 7889 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7890 "Package " + pkg.packageName + " requires unavailable shared library " 7891 + pkg.usesLibraries.get(i) + "; failing!"); 7892 } 7893 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7894 } 7895 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7896 for (int i=0; i<N; i++) { 7897 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7898 if (file == null) { 7899 Slog.w(TAG, "Package " + pkg.packageName 7900 + " desires unavailable shared library " 7901 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7902 } else { 7903 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7904 } 7905 } 7906 N = usesLibraryFiles.size(); 7907 if (N > 0) { 7908 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7909 } else { 7910 pkg.usesLibraryFiles = null; 7911 } 7912 } 7913 } 7914 7915 private static boolean hasString(List<String> list, List<String> which) { 7916 if (list == null) { 7917 return false; 7918 } 7919 for (int i=list.size()-1; i>=0; i--) { 7920 for (int j=which.size()-1; j>=0; j--) { 7921 if (which.get(j).equals(list.get(i))) { 7922 return true; 7923 } 7924 } 7925 } 7926 return false; 7927 } 7928 7929 private void updateAllSharedLibrariesLPw() { 7930 for (PackageParser.Package pkg : mPackages.values()) { 7931 try { 7932 updateSharedLibrariesLPw(pkg, null); 7933 } catch (PackageManagerException e) { 7934 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7935 } 7936 } 7937 } 7938 7939 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7940 PackageParser.Package changingPkg) { 7941 ArrayList<PackageParser.Package> res = null; 7942 for (PackageParser.Package pkg : mPackages.values()) { 7943 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7944 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7945 if (res == null) { 7946 res = new ArrayList<PackageParser.Package>(); 7947 } 7948 res.add(pkg); 7949 try { 7950 updateSharedLibrariesLPw(pkg, changingPkg); 7951 } catch (PackageManagerException e) { 7952 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7953 } 7954 } 7955 } 7956 return res; 7957 } 7958 7959 /** 7960 * Derive the value of the {@code cpuAbiOverride} based on the provided 7961 * value and an optional stored value from the package settings. 7962 */ 7963 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7964 String cpuAbiOverride = null; 7965 7966 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7967 cpuAbiOverride = null; 7968 } else if (abiOverride != null) { 7969 cpuAbiOverride = abiOverride; 7970 } else if (settings != null) { 7971 cpuAbiOverride = settings.cpuAbiOverrideString; 7972 } 7973 7974 return cpuAbiOverride; 7975 } 7976 7977 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7978 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7979 throws PackageManagerException { 7980 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7981 // If the package has children and this is the first dive in the function 7982 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7983 // whether all packages (parent and children) would be successfully scanned 7984 // before the actual scan since scanning mutates internal state and we want 7985 // to atomically install the package and its children. 7986 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7987 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7988 scanFlags |= SCAN_CHECK_ONLY; 7989 } 7990 } else { 7991 scanFlags &= ~SCAN_CHECK_ONLY; 7992 } 7993 7994 final PackageParser.Package scannedPkg; 7995 try { 7996 // Scan the parent 7997 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7998 // Scan the children 7999 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8000 for (int i = 0; i < childCount; i++) { 8001 PackageParser.Package childPkg = pkg.childPackages.get(i); 8002 scanPackageLI(childPkg, policyFlags, 8003 scanFlags, currentTime, user); 8004 } 8005 } finally { 8006 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8007 } 8008 8009 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8010 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8011 } 8012 8013 return scannedPkg; 8014 } 8015 8016 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8017 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8018 boolean success = false; 8019 try { 8020 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8021 currentTime, user); 8022 success = true; 8023 return res; 8024 } finally { 8025 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8026 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8027 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8028 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8029 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8030 } 8031 } 8032 } 8033 8034 /** 8035 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8036 */ 8037 private static boolean apkHasCode(String fileName) { 8038 StrictJarFile jarFile = null; 8039 try { 8040 jarFile = new StrictJarFile(fileName, 8041 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8042 return jarFile.findEntry("classes.dex") != null; 8043 } catch (IOException ignore) { 8044 } finally { 8045 try { 8046 if (jarFile != null) { 8047 jarFile.close(); 8048 } 8049 } catch (IOException ignore) {} 8050 } 8051 return false; 8052 } 8053 8054 /** 8055 * Enforces code policy for the package. This ensures that if an APK has 8056 * declared hasCode="true" in its manifest that the APK actually contains 8057 * code. 8058 * 8059 * @throws PackageManagerException If bytecode could not be found when it should exist 8060 */ 8061 private static void enforceCodePolicy(PackageParser.Package pkg) 8062 throws PackageManagerException { 8063 final boolean shouldHaveCode = 8064 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8065 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8066 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8067 "Package " + pkg.baseCodePath + " code is missing"); 8068 } 8069 8070 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8071 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8072 final boolean splitShouldHaveCode = 8073 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8074 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8075 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8076 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8077 } 8078 } 8079 } 8080 } 8081 8082 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8083 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8084 throws PackageManagerException { 8085 final File scanFile = new File(pkg.codePath); 8086 if (pkg.applicationInfo.getCodePath() == null || 8087 pkg.applicationInfo.getResourcePath() == null) { 8088 // Bail out. The resource and code paths haven't been set. 8089 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8090 "Code and resource paths haven't been set correctly"); 8091 } 8092 8093 // Apply policy 8094 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8095 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8096 if (pkg.applicationInfo.isDirectBootAware()) { 8097 // we're direct boot aware; set for all components 8098 for (PackageParser.Service s : pkg.services) { 8099 s.info.encryptionAware = s.info.directBootAware = true; 8100 } 8101 for (PackageParser.Provider p : pkg.providers) { 8102 p.info.encryptionAware = p.info.directBootAware = true; 8103 } 8104 for (PackageParser.Activity a : pkg.activities) { 8105 a.info.encryptionAware = a.info.directBootAware = true; 8106 } 8107 for (PackageParser.Activity r : pkg.receivers) { 8108 r.info.encryptionAware = r.info.directBootAware = true; 8109 } 8110 } 8111 } else { 8112 // Only allow system apps to be flagged as core apps. 8113 pkg.coreApp = false; 8114 // clear flags not applicable to regular apps 8115 pkg.applicationInfo.privateFlags &= 8116 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8117 pkg.applicationInfo.privateFlags &= 8118 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8119 } 8120 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8121 8122 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8123 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8124 } 8125 8126 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8127 enforceCodePolicy(pkg); 8128 } 8129 8130 if (mCustomResolverComponentName != null && 8131 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8132 setUpCustomResolverActivity(pkg); 8133 } 8134 8135 if (pkg.packageName.equals("android")) { 8136 synchronized (mPackages) { 8137 if (mAndroidApplication != null) { 8138 Slog.w(TAG, "*************************************************"); 8139 Slog.w(TAG, "Core android package being redefined. Skipping."); 8140 Slog.w(TAG, " file=" + scanFile); 8141 Slog.w(TAG, "*************************************************"); 8142 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8143 "Core android package being redefined. Skipping."); 8144 } 8145 8146 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8147 // Set up information for our fall-back user intent resolution activity. 8148 mPlatformPackage = pkg; 8149 pkg.mVersionCode = mSdkVersion; 8150 mAndroidApplication = pkg.applicationInfo; 8151 8152 if (!mResolverReplaced) { 8153 mResolveActivity.applicationInfo = mAndroidApplication; 8154 mResolveActivity.name = ResolverActivity.class.getName(); 8155 mResolveActivity.packageName = mAndroidApplication.packageName; 8156 mResolveActivity.processName = "system:ui"; 8157 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8158 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8159 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8160 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8161 mResolveActivity.exported = true; 8162 mResolveActivity.enabled = true; 8163 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8164 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8165 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8166 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8167 | ActivityInfo.CONFIG_ORIENTATION 8168 | ActivityInfo.CONFIG_KEYBOARD 8169 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8170 mResolveInfo.activityInfo = mResolveActivity; 8171 mResolveInfo.priority = 0; 8172 mResolveInfo.preferredOrder = 0; 8173 mResolveInfo.match = 0; 8174 mResolveComponentName = new ComponentName( 8175 mAndroidApplication.packageName, mResolveActivity.name); 8176 } 8177 } 8178 } 8179 } 8180 8181 if (DEBUG_PACKAGE_SCANNING) { 8182 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8183 Log.d(TAG, "Scanning package " + pkg.packageName); 8184 } 8185 8186 synchronized (mPackages) { 8187 if (mPackages.containsKey(pkg.packageName) 8188 || mSharedLibraries.containsKey(pkg.packageName)) { 8189 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8190 "Application package " + pkg.packageName 8191 + " already installed. Skipping duplicate."); 8192 } 8193 8194 // If we're only installing presumed-existing packages, require that the 8195 // scanned APK is both already known and at the path previously established 8196 // for it. Previously unknown packages we pick up normally, but if we have an 8197 // a priori expectation about this package's install presence, enforce it. 8198 // With a singular exception for new system packages. When an OTA contains 8199 // a new system package, we allow the codepath to change from a system location 8200 // to the user-installed location. If we don't allow this change, any newer, 8201 // user-installed version of the application will be ignored. 8202 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8203 if (mExpectingBetter.containsKey(pkg.packageName)) { 8204 logCriticalInfo(Log.WARN, 8205 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8206 } else { 8207 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8208 if (known != null) { 8209 if (DEBUG_PACKAGE_SCANNING) { 8210 Log.d(TAG, "Examining " + pkg.codePath 8211 + " and requiring known paths " + known.codePathString 8212 + " & " + known.resourcePathString); 8213 } 8214 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8215 || !pkg.applicationInfo.getResourcePath().equals( 8216 known.resourcePathString)) { 8217 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8218 "Application package " + pkg.packageName 8219 + " found at " + pkg.applicationInfo.getCodePath() 8220 + " but expected at " + known.codePathString 8221 + "; ignoring."); 8222 } 8223 } 8224 } 8225 } 8226 } 8227 8228 // Initialize package source and resource directories 8229 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8230 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8231 8232 SharedUserSetting suid = null; 8233 PackageSetting pkgSetting = null; 8234 8235 if (!isSystemApp(pkg)) { 8236 // Only system apps can use these features. 8237 pkg.mOriginalPackages = null; 8238 pkg.mRealPackage = null; 8239 pkg.mAdoptPermissions = null; 8240 } 8241 8242 // Getting the package setting may have a side-effect, so if we 8243 // are only checking if scan would succeed, stash a copy of the 8244 // old setting to restore at the end. 8245 PackageSetting nonMutatedPs = null; 8246 8247 // writer 8248 synchronized (mPackages) { 8249 if (pkg.mSharedUserId != null) { 8250 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8251 if (suid == null) { 8252 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8253 "Creating application package " + pkg.packageName 8254 + " for shared user failed"); 8255 } 8256 if (DEBUG_PACKAGE_SCANNING) { 8257 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8258 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8259 + "): packages=" + suid.packages); 8260 } 8261 } 8262 8263 // Check if we are renaming from an original package name. 8264 PackageSetting origPackage = null; 8265 String realName = null; 8266 if (pkg.mOriginalPackages != null) { 8267 // This package may need to be renamed to a previously 8268 // installed name. Let's check on that... 8269 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8270 if (pkg.mOriginalPackages.contains(renamed)) { 8271 // This package had originally been installed as the 8272 // original name, and we have already taken care of 8273 // transitioning to the new one. Just update the new 8274 // one to continue using the old name. 8275 realName = pkg.mRealPackage; 8276 if (!pkg.packageName.equals(renamed)) { 8277 // Callers into this function may have already taken 8278 // care of renaming the package; only do it here if 8279 // it is not already done. 8280 pkg.setPackageName(renamed); 8281 } 8282 8283 } else { 8284 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8285 if ((origPackage = mSettings.peekPackageLPr( 8286 pkg.mOriginalPackages.get(i))) != null) { 8287 // We do have the package already installed under its 8288 // original name... should we use it? 8289 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8290 // New package is not compatible with original. 8291 origPackage = null; 8292 continue; 8293 } else if (origPackage.sharedUser != null) { 8294 // Make sure uid is compatible between packages. 8295 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8296 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8297 + " to " + pkg.packageName + ": old uid " 8298 + origPackage.sharedUser.name 8299 + " differs from " + pkg.mSharedUserId); 8300 origPackage = null; 8301 continue; 8302 } 8303 // TODO: Add case when shared user id is added [b/28144775] 8304 } else { 8305 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8306 + pkg.packageName + " to old name " + origPackage.name); 8307 } 8308 break; 8309 } 8310 } 8311 } 8312 } 8313 8314 if (mTransferedPackages.contains(pkg.packageName)) { 8315 Slog.w(TAG, "Package " + pkg.packageName 8316 + " was transferred to another, but its .apk remains"); 8317 } 8318 8319 // See comments in nonMutatedPs declaration 8320 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8321 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8322 if (foundPs != null) { 8323 nonMutatedPs = new PackageSetting(foundPs); 8324 } 8325 } 8326 8327 // Just create the setting, don't add it yet. For already existing packages 8328 // the PkgSetting exists already and doesn't have to be created. 8329 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8330 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8331 pkg.applicationInfo.primaryCpuAbi, 8332 pkg.applicationInfo.secondaryCpuAbi, 8333 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8334 user, false); 8335 if (pkgSetting == null) { 8336 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8337 "Creating application package " + pkg.packageName + " failed"); 8338 } 8339 8340 if (pkgSetting.origPackage != null) { 8341 // If we are first transitioning from an original package, 8342 // fix up the new package's name now. We need to do this after 8343 // looking up the package under its new name, so getPackageLP 8344 // can take care of fiddling things correctly. 8345 pkg.setPackageName(origPackage.name); 8346 8347 // File a report about this. 8348 String msg = "New package " + pkgSetting.realName 8349 + " renamed to replace old package " + pkgSetting.name; 8350 reportSettingsProblem(Log.WARN, msg); 8351 8352 // Make a note of it. 8353 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8354 mTransferedPackages.add(origPackage.name); 8355 } 8356 8357 // No longer need to retain this. 8358 pkgSetting.origPackage = null; 8359 } 8360 8361 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8362 // Make a note of it. 8363 mTransferedPackages.add(pkg.packageName); 8364 } 8365 8366 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8367 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8368 } 8369 8370 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8371 // Check all shared libraries and map to their actual file path. 8372 // We only do this here for apps not on a system dir, because those 8373 // are the only ones that can fail an install due to this. We 8374 // will take care of the system apps by updating all of their 8375 // library paths after the scan is done. 8376 updateSharedLibrariesLPw(pkg, null); 8377 } 8378 8379 if (mFoundPolicyFile) { 8380 SELinuxMMAC.assignSeinfoValue(pkg); 8381 } 8382 8383 pkg.applicationInfo.uid = pkgSetting.appId; 8384 pkg.mExtras = pkgSetting; 8385 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8386 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8387 // We just determined the app is signed correctly, so bring 8388 // over the latest parsed certs. 8389 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8390 } else { 8391 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8392 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8393 "Package " + pkg.packageName + " upgrade keys do not match the " 8394 + "previously installed version"); 8395 } else { 8396 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8397 String msg = "System package " + pkg.packageName 8398 + " signature changed; retaining data."; 8399 reportSettingsProblem(Log.WARN, msg); 8400 } 8401 } 8402 } else { 8403 try { 8404 verifySignaturesLP(pkgSetting, pkg); 8405 // We just determined the app is signed correctly, so bring 8406 // over the latest parsed certs. 8407 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8408 } catch (PackageManagerException e) { 8409 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8410 throw e; 8411 } 8412 // The signature has changed, but this package is in the system 8413 // image... let's recover! 8414 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8415 // However... if this package is part of a shared user, but it 8416 // doesn't match the signature of the shared user, let's fail. 8417 // What this means is that you can't change the signatures 8418 // associated with an overall shared user, which doesn't seem all 8419 // that unreasonable. 8420 if (pkgSetting.sharedUser != null) { 8421 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8422 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8423 throw new PackageManagerException( 8424 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8425 "Signature mismatch for shared user: " 8426 + pkgSetting.sharedUser); 8427 } 8428 } 8429 // File a report about this. 8430 String msg = "System package " + pkg.packageName 8431 + " signature changed; retaining data."; 8432 reportSettingsProblem(Log.WARN, msg); 8433 } 8434 } 8435 // Verify that this new package doesn't have any content providers 8436 // that conflict with existing packages. Only do this if the 8437 // package isn't already installed, since we don't want to break 8438 // things that are installed. 8439 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8440 final int N = pkg.providers.size(); 8441 int i; 8442 for (i=0; i<N; i++) { 8443 PackageParser.Provider p = pkg.providers.get(i); 8444 if (p.info.authority != null) { 8445 String names[] = p.info.authority.split(";"); 8446 for (int j = 0; j < names.length; j++) { 8447 if (mProvidersByAuthority.containsKey(names[j])) { 8448 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8449 final String otherPackageName = 8450 ((other != null && other.getComponentName() != null) ? 8451 other.getComponentName().getPackageName() : "?"); 8452 throw new PackageManagerException( 8453 INSTALL_FAILED_CONFLICTING_PROVIDER, 8454 "Can't install because provider name " + names[j] 8455 + " (in package " + pkg.applicationInfo.packageName 8456 + ") is already used by " + otherPackageName); 8457 } 8458 } 8459 } 8460 } 8461 } 8462 8463 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8464 // This package wants to adopt ownership of permissions from 8465 // another package. 8466 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8467 final String origName = pkg.mAdoptPermissions.get(i); 8468 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8469 if (orig != null) { 8470 if (verifyPackageUpdateLPr(orig, pkg)) { 8471 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8472 + pkg.packageName); 8473 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8474 } 8475 } 8476 } 8477 } 8478 } 8479 8480 final String pkgName = pkg.packageName; 8481 8482 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8483 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8484 pkg.applicationInfo.processName = fixProcessName( 8485 pkg.applicationInfo.packageName, 8486 pkg.applicationInfo.processName, 8487 pkg.applicationInfo.uid); 8488 8489 if (pkg != mPlatformPackage) { 8490 // Get all of our default paths setup 8491 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8492 } 8493 8494 final String path = scanFile.getPath(); 8495 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8496 8497 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8498 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8499 8500 // Some system apps still use directory structure for native libraries 8501 // in which case we might end up not detecting abi solely based on apk 8502 // structure. Try to detect abi based on directory structure. 8503 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8504 pkg.applicationInfo.primaryCpuAbi == null) { 8505 setBundledAppAbisAndRoots(pkg, pkgSetting); 8506 setNativeLibraryPaths(pkg); 8507 } 8508 8509 } else { 8510 if ((scanFlags & SCAN_MOVE) != 0) { 8511 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8512 // but we already have this packages package info in the PackageSetting. We just 8513 // use that and derive the native library path based on the new codepath. 8514 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8515 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8516 } 8517 8518 // Set native library paths again. For moves, the path will be updated based on the 8519 // ABIs we've determined above. For non-moves, the path will be updated based on the 8520 // ABIs we determined during compilation, but the path will depend on the final 8521 // package path (after the rename away from the stage path). 8522 setNativeLibraryPaths(pkg); 8523 } 8524 8525 // This is a special case for the "system" package, where the ABI is 8526 // dictated by the zygote configuration (and init.rc). We should keep track 8527 // of this ABI so that we can deal with "normal" applications that run under 8528 // the same UID correctly. 8529 if (mPlatformPackage == pkg) { 8530 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8531 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8532 } 8533 8534 // If there's a mismatch between the abi-override in the package setting 8535 // and the abiOverride specified for the install. Warn about this because we 8536 // would've already compiled the app without taking the package setting into 8537 // account. 8538 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8539 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8540 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8541 " for package " + pkg.packageName); 8542 } 8543 } 8544 8545 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8546 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8547 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8548 8549 // Copy the derived override back to the parsed package, so that we can 8550 // update the package settings accordingly. 8551 pkg.cpuAbiOverride = cpuAbiOverride; 8552 8553 if (DEBUG_ABI_SELECTION) { 8554 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8555 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8556 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8557 } 8558 8559 // Push the derived path down into PackageSettings so we know what to 8560 // clean up at uninstall time. 8561 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8562 8563 if (DEBUG_ABI_SELECTION) { 8564 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8565 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8566 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8567 } 8568 8569 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8570 // We don't do this here during boot because we can do it all 8571 // at once after scanning all existing packages. 8572 // 8573 // We also do this *before* we perform dexopt on this package, so that 8574 // we can avoid redundant dexopts, and also to make sure we've got the 8575 // code and package path correct. 8576 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8577 pkg, true /* boot complete */); 8578 } 8579 8580 if (mFactoryTest && pkg.requestedPermissions.contains( 8581 android.Manifest.permission.FACTORY_TEST)) { 8582 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8583 } 8584 8585 if (isSystemApp(pkg)) { 8586 pkgSetting.isOrphaned = true; 8587 } 8588 8589 ArrayList<PackageParser.Package> clientLibPkgs = null; 8590 8591 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8592 if (nonMutatedPs != null) { 8593 synchronized (mPackages) { 8594 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8595 } 8596 } 8597 return pkg; 8598 } 8599 8600 // Only privileged apps and updated privileged apps can add child packages. 8601 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8602 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8603 throw new PackageManagerException("Only privileged apps and updated " 8604 + "privileged apps can add child packages. Ignoring package " 8605 + pkg.packageName); 8606 } 8607 final int childCount = pkg.childPackages.size(); 8608 for (int i = 0; i < childCount; i++) { 8609 PackageParser.Package childPkg = pkg.childPackages.get(i); 8610 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8611 childPkg.packageName)) { 8612 throw new PackageManagerException("Cannot override a child package of " 8613 + "another disabled system app. Ignoring package " + pkg.packageName); 8614 } 8615 } 8616 } 8617 8618 // writer 8619 synchronized (mPackages) { 8620 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8621 // Only system apps can add new shared libraries. 8622 if (pkg.libraryNames != null) { 8623 for (int i=0; i<pkg.libraryNames.size(); i++) { 8624 String name = pkg.libraryNames.get(i); 8625 boolean allowed = false; 8626 if (pkg.isUpdatedSystemApp()) { 8627 // New library entries can only be added through the 8628 // system image. This is important to get rid of a lot 8629 // of nasty edge cases: for example if we allowed a non- 8630 // system update of the app to add a library, then uninstalling 8631 // the update would make the library go away, and assumptions 8632 // we made such as through app install filtering would now 8633 // have allowed apps on the device which aren't compatible 8634 // with it. Better to just have the restriction here, be 8635 // conservative, and create many fewer cases that can negatively 8636 // impact the user experience. 8637 final PackageSetting sysPs = mSettings 8638 .getDisabledSystemPkgLPr(pkg.packageName); 8639 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8640 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8641 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8642 allowed = true; 8643 break; 8644 } 8645 } 8646 } 8647 } else { 8648 allowed = true; 8649 } 8650 if (allowed) { 8651 if (!mSharedLibraries.containsKey(name)) { 8652 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8653 } else if (!name.equals(pkg.packageName)) { 8654 Slog.w(TAG, "Package " + pkg.packageName + " library " 8655 + name + " already exists; skipping"); 8656 } 8657 } else { 8658 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8659 + name + " that is not declared on system image; skipping"); 8660 } 8661 } 8662 if ((scanFlags & SCAN_BOOTING) == 0) { 8663 // If we are not booting, we need to update any applications 8664 // that are clients of our shared library. If we are booting, 8665 // this will all be done once the scan is complete. 8666 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8667 } 8668 } 8669 } 8670 } 8671 8672 if ((scanFlags & SCAN_BOOTING) != 0) { 8673 // No apps can run during boot scan, so they don't need to be frozen 8674 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8675 // Caller asked to not kill app, so it's probably not frozen 8676 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8677 // Caller asked us to ignore frozen check for some reason; they 8678 // probably didn't know the package name 8679 } else { 8680 // We're doing major surgery on this package, so it better be frozen 8681 // right now to keep it from launching 8682 checkPackageFrozen(pkgName); 8683 } 8684 8685 // Also need to kill any apps that are dependent on the library. 8686 if (clientLibPkgs != null) { 8687 for (int i=0; i<clientLibPkgs.size(); i++) { 8688 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8689 killApplication(clientPkg.applicationInfo.packageName, 8690 clientPkg.applicationInfo.uid, "update lib"); 8691 } 8692 } 8693 8694 // Make sure we're not adding any bogus keyset info 8695 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8696 ksms.assertScannedPackageValid(pkg); 8697 8698 // writer 8699 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8700 8701 boolean createIdmapFailed = false; 8702 synchronized (mPackages) { 8703 // We don't expect installation to fail beyond this point 8704 8705 if (pkgSetting.pkg != null) { 8706 // Note that |user| might be null during the initial boot scan. If a codePath 8707 // for an app has changed during a boot scan, it's due to an app update that's 8708 // part of the system partition and marker changes must be applied to all users. 8709 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8710 (user != null) ? user : UserHandle.ALL); 8711 } 8712 8713 // Add the new setting to mSettings 8714 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8715 // Add the new setting to mPackages 8716 mPackages.put(pkg.applicationInfo.packageName, pkg); 8717 // Make sure we don't accidentally delete its data. 8718 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8719 while (iter.hasNext()) { 8720 PackageCleanItem item = iter.next(); 8721 if (pkgName.equals(item.packageName)) { 8722 iter.remove(); 8723 } 8724 } 8725 8726 // Take care of first install / last update times. 8727 if (currentTime != 0) { 8728 if (pkgSetting.firstInstallTime == 0) { 8729 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8730 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8731 pkgSetting.lastUpdateTime = currentTime; 8732 } 8733 } else if (pkgSetting.firstInstallTime == 0) { 8734 // We need *something*. Take time time stamp of the file. 8735 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8736 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8737 if (scanFileTime != pkgSetting.timeStamp) { 8738 // A package on the system image has changed; consider this 8739 // to be an update. 8740 pkgSetting.lastUpdateTime = scanFileTime; 8741 } 8742 } 8743 8744 // Add the package's KeySets to the global KeySetManagerService 8745 ksms.addScannedPackageLPw(pkg); 8746 8747 int N = pkg.providers.size(); 8748 StringBuilder r = null; 8749 int i; 8750 for (i=0; i<N; i++) { 8751 PackageParser.Provider p = pkg.providers.get(i); 8752 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8753 p.info.processName, pkg.applicationInfo.uid); 8754 mProviders.addProvider(p); 8755 p.syncable = p.info.isSyncable; 8756 if (p.info.authority != null) { 8757 String names[] = p.info.authority.split(";"); 8758 p.info.authority = null; 8759 for (int j = 0; j < names.length; j++) { 8760 if (j == 1 && p.syncable) { 8761 // We only want the first authority for a provider to possibly be 8762 // syncable, so if we already added this provider using a different 8763 // authority clear the syncable flag. We copy the provider before 8764 // changing it because the mProviders object contains a reference 8765 // to a provider that we don't want to change. 8766 // Only do this for the second authority since the resulting provider 8767 // object can be the same for all future authorities for this provider. 8768 p = new PackageParser.Provider(p); 8769 p.syncable = false; 8770 } 8771 if (!mProvidersByAuthority.containsKey(names[j])) { 8772 mProvidersByAuthority.put(names[j], p); 8773 if (p.info.authority == null) { 8774 p.info.authority = names[j]; 8775 } else { 8776 p.info.authority = p.info.authority + ";" + names[j]; 8777 } 8778 if (DEBUG_PACKAGE_SCANNING) { 8779 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8780 Log.d(TAG, "Registered content provider: " + names[j] 8781 + ", className = " + p.info.name + ", isSyncable = " 8782 + p.info.isSyncable); 8783 } 8784 } else { 8785 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8786 Slog.w(TAG, "Skipping provider name " + names[j] + 8787 " (in package " + pkg.applicationInfo.packageName + 8788 "): name already used by " 8789 + ((other != null && other.getComponentName() != null) 8790 ? other.getComponentName().getPackageName() : "?")); 8791 } 8792 } 8793 } 8794 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8795 if (r == null) { 8796 r = new StringBuilder(256); 8797 } else { 8798 r.append(' '); 8799 } 8800 r.append(p.info.name); 8801 } 8802 } 8803 if (r != null) { 8804 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8805 } 8806 8807 N = pkg.services.size(); 8808 r = null; 8809 for (i=0; i<N; i++) { 8810 PackageParser.Service s = pkg.services.get(i); 8811 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8812 s.info.processName, pkg.applicationInfo.uid); 8813 mServices.addService(s); 8814 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8815 if (r == null) { 8816 r = new StringBuilder(256); 8817 } else { 8818 r.append(' '); 8819 } 8820 r.append(s.info.name); 8821 } 8822 } 8823 if (r != null) { 8824 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8825 } 8826 8827 N = pkg.receivers.size(); 8828 r = null; 8829 for (i=0; i<N; i++) { 8830 PackageParser.Activity a = pkg.receivers.get(i); 8831 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8832 a.info.processName, pkg.applicationInfo.uid); 8833 mReceivers.addActivity(a, "receiver"); 8834 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8835 if (r == null) { 8836 r = new StringBuilder(256); 8837 } else { 8838 r.append(' '); 8839 } 8840 r.append(a.info.name); 8841 } 8842 } 8843 if (r != null) { 8844 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8845 } 8846 8847 N = pkg.activities.size(); 8848 r = null; 8849 for (i=0; i<N; i++) { 8850 PackageParser.Activity a = pkg.activities.get(i); 8851 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8852 a.info.processName, pkg.applicationInfo.uid); 8853 mActivities.addActivity(a, "activity"); 8854 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8855 if (r == null) { 8856 r = new StringBuilder(256); 8857 } else { 8858 r.append(' '); 8859 } 8860 r.append(a.info.name); 8861 } 8862 } 8863 if (r != null) { 8864 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8865 } 8866 8867 N = pkg.permissionGroups.size(); 8868 r = null; 8869 for (i=0; i<N; i++) { 8870 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8871 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8872 final String curPackageName = cur == null ? null : cur.info.packageName; 8873 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 8874 if (cur == null || isPackageUpdate) { 8875 mPermissionGroups.put(pg.info.name, pg); 8876 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8877 if (r == null) { 8878 r = new StringBuilder(256); 8879 } else { 8880 r.append(' '); 8881 } 8882 if (isPackageUpdate) { 8883 r.append("UPD:"); 8884 } 8885 r.append(pg.info.name); 8886 } 8887 } else { 8888 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8889 + pg.info.packageName + " ignored: original from " 8890 + cur.info.packageName); 8891 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8892 if (r == null) { 8893 r = new StringBuilder(256); 8894 } else { 8895 r.append(' '); 8896 } 8897 r.append("DUP:"); 8898 r.append(pg.info.name); 8899 } 8900 } 8901 } 8902 if (r != null) { 8903 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8904 } 8905 8906 N = pkg.permissions.size(); 8907 r = null; 8908 for (i=0; i<N; i++) { 8909 PackageParser.Permission p = pkg.permissions.get(i); 8910 8911 // Assume by default that we did not install this permission into the system. 8912 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8913 8914 // Now that permission groups have a special meaning, we ignore permission 8915 // groups for legacy apps to prevent unexpected behavior. In particular, 8916 // permissions for one app being granted to someone just becase they happen 8917 // to be in a group defined by another app (before this had no implications). 8918 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8919 p.group = mPermissionGroups.get(p.info.group); 8920 // Warn for a permission in an unknown group. 8921 if (p.info.group != null && p.group == null) { 8922 Slog.w(TAG, "Permission " + p.info.name + " from package " 8923 + p.info.packageName + " in an unknown group " + p.info.group); 8924 } 8925 } 8926 8927 ArrayMap<String, BasePermission> permissionMap = 8928 p.tree ? mSettings.mPermissionTrees 8929 : mSettings.mPermissions; 8930 BasePermission bp = permissionMap.get(p.info.name); 8931 8932 // Allow system apps to redefine non-system permissions 8933 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8934 final boolean currentOwnerIsSystem = (bp.perm != null 8935 && isSystemApp(bp.perm.owner)); 8936 if (isSystemApp(p.owner)) { 8937 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8938 // It's a built-in permission and no owner, take ownership now 8939 bp.packageSetting = pkgSetting; 8940 bp.perm = p; 8941 bp.uid = pkg.applicationInfo.uid; 8942 bp.sourcePackage = p.info.packageName; 8943 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8944 } else if (!currentOwnerIsSystem) { 8945 String msg = "New decl " + p.owner + " of permission " 8946 + p.info.name + " is system; overriding " + bp.sourcePackage; 8947 reportSettingsProblem(Log.WARN, msg); 8948 bp = null; 8949 } 8950 } 8951 } 8952 8953 if (bp == null) { 8954 bp = new BasePermission(p.info.name, p.info.packageName, 8955 BasePermission.TYPE_NORMAL); 8956 permissionMap.put(p.info.name, bp); 8957 } 8958 8959 if (bp.perm == null) { 8960 if (bp.sourcePackage == null 8961 || bp.sourcePackage.equals(p.info.packageName)) { 8962 BasePermission tree = findPermissionTreeLP(p.info.name); 8963 if (tree == null 8964 || tree.sourcePackage.equals(p.info.packageName)) { 8965 bp.packageSetting = pkgSetting; 8966 bp.perm = p; 8967 bp.uid = pkg.applicationInfo.uid; 8968 bp.sourcePackage = p.info.packageName; 8969 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8970 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8971 if (r == null) { 8972 r = new StringBuilder(256); 8973 } else { 8974 r.append(' '); 8975 } 8976 r.append(p.info.name); 8977 } 8978 } else { 8979 Slog.w(TAG, "Permission " + p.info.name + " from package " 8980 + p.info.packageName + " ignored: base tree " 8981 + tree.name + " is from package " 8982 + tree.sourcePackage); 8983 } 8984 } else { 8985 Slog.w(TAG, "Permission " + p.info.name + " from package " 8986 + p.info.packageName + " ignored: original from " 8987 + bp.sourcePackage); 8988 } 8989 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8990 if (r == null) { 8991 r = new StringBuilder(256); 8992 } else { 8993 r.append(' '); 8994 } 8995 r.append("DUP:"); 8996 r.append(p.info.name); 8997 } 8998 if (bp.perm == p) { 8999 bp.protectionLevel = p.info.protectionLevel; 9000 } 9001 } 9002 9003 if (r != null) { 9004 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 9005 } 9006 9007 N = pkg.instrumentation.size(); 9008 r = null; 9009 for (i=0; i<N; i++) { 9010 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9011 a.info.packageName = pkg.applicationInfo.packageName; 9012 a.info.sourceDir = pkg.applicationInfo.sourceDir; 9013 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 9014 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 9015 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 9016 a.info.dataDir = pkg.applicationInfo.dataDir; 9017 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 9018 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 9019 9020 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 9021 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 9022 mInstrumentation.put(a.getComponentName(), a); 9023 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 9024 if (r == null) { 9025 r = new StringBuilder(256); 9026 } else { 9027 r.append(' '); 9028 } 9029 r.append(a.info.name); 9030 } 9031 } 9032 if (r != null) { 9033 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9034 } 9035 9036 if (pkg.protectedBroadcasts != null) { 9037 N = pkg.protectedBroadcasts.size(); 9038 for (i=0; i<N; i++) { 9039 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9040 } 9041 } 9042 9043 pkgSetting.setTimeStamp(scanFileTime); 9044 9045 // Create idmap files for pairs of (packages, overlay packages). 9046 // Note: "android", ie framework-res.apk, is handled by native layers. 9047 if (pkg.mOverlayTarget != null) { 9048 // This is an overlay package. 9049 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9050 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9051 mOverlays.put(pkg.mOverlayTarget, 9052 new ArrayMap<String, PackageParser.Package>()); 9053 } 9054 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9055 map.put(pkg.packageName, pkg); 9056 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9057 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9058 createIdmapFailed = true; 9059 } 9060 } 9061 } else if (mOverlays.containsKey(pkg.packageName) && 9062 !pkg.packageName.equals("android")) { 9063 // This is a regular package, with one or more known overlay packages. 9064 createIdmapsForPackageLI(pkg); 9065 } 9066 } 9067 9068 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9069 9070 if (createIdmapFailed) { 9071 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9072 "scanPackageLI failed to createIdmap"); 9073 } 9074 return pkg; 9075 } 9076 9077 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9078 PackageParser.Package update, UserHandle user) { 9079 if (existing.applicationInfo == null || update.applicationInfo == null) { 9080 // This isn't due to an app installation. 9081 return; 9082 } 9083 9084 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9085 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9086 9087 // The codePath hasn't changed, so there's nothing for us to do. 9088 if (Objects.equals(oldCodePath, newCodePath)) { 9089 return; 9090 } 9091 9092 File canonicalNewCodePath; 9093 try { 9094 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9095 } catch (IOException e) { 9096 Slog.w(TAG, "Failed to get canonical path.", e); 9097 return; 9098 } 9099 9100 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9101 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9102 // that the last component of the path (i.e, the name) doesn't need canonicalization 9103 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9104 // but may change in the future. Hopefully this function won't exist at that point. 9105 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9106 oldCodePath.getName()); 9107 9108 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9109 // with "@". 9110 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9111 if (!oldMarkerPrefix.endsWith("@")) { 9112 oldMarkerPrefix += "@"; 9113 } 9114 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9115 if (!newMarkerPrefix.endsWith("@")) { 9116 newMarkerPrefix += "@"; 9117 } 9118 9119 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9120 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9121 for (String updatedPath : updatedPaths) { 9122 String updatedPathName = new File(updatedPath).getName(); 9123 markerSuffixes.add(updatedPathName.replace('/', '@')); 9124 } 9125 9126 for (int userId : resolveUserIds(user.getIdentifier())) { 9127 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9128 9129 for (String markerSuffix : markerSuffixes) { 9130 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9131 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9132 if (oldForeignUseMark.exists()) { 9133 try { 9134 Os.rename(oldForeignUseMark.getAbsolutePath(), 9135 newForeignUseMark.getAbsolutePath()); 9136 } catch (ErrnoException e) { 9137 Slog.w(TAG, "Failed to rename foreign use marker", e); 9138 oldForeignUseMark.delete(); 9139 } 9140 } 9141 } 9142 } 9143 } 9144 9145 /** 9146 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9147 * is derived purely on the basis of the contents of {@code scanFile} and 9148 * {@code cpuAbiOverride}. 9149 * 9150 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9151 */ 9152 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9153 String cpuAbiOverride, boolean extractLibs) 9154 throws PackageManagerException { 9155 // TODO: We can probably be smarter about this stuff. For installed apps, 9156 // we can calculate this information at install time once and for all. For 9157 // system apps, we can probably assume that this information doesn't change 9158 // after the first boot scan. As things stand, we do lots of unnecessary work. 9159 9160 // Give ourselves some initial paths; we'll come back for another 9161 // pass once we've determined ABI below. 9162 setNativeLibraryPaths(pkg); 9163 9164 // We would never need to extract libs for forward-locked and external packages, 9165 // since the container service will do it for us. We shouldn't attempt to 9166 // extract libs from system app when it was not updated. 9167 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9168 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9169 extractLibs = false; 9170 } 9171 9172 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9173 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9174 9175 NativeLibraryHelper.Handle handle = null; 9176 try { 9177 handle = NativeLibraryHelper.Handle.create(pkg); 9178 // TODO(multiArch): This can be null for apps that didn't go through the 9179 // usual installation process. We can calculate it again, like we 9180 // do during install time. 9181 // 9182 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9183 // unnecessary. 9184 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9185 9186 // Null out the abis so that they can be recalculated. 9187 pkg.applicationInfo.primaryCpuAbi = null; 9188 pkg.applicationInfo.secondaryCpuAbi = null; 9189 if (isMultiArch(pkg.applicationInfo)) { 9190 // Warn if we've set an abiOverride for multi-lib packages.. 9191 // By definition, we need to copy both 32 and 64 bit libraries for 9192 // such packages. 9193 if (pkg.cpuAbiOverride != null 9194 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9195 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9196 } 9197 9198 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9199 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9200 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9201 if (extractLibs) { 9202 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9203 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9204 useIsaSpecificSubdirs); 9205 } else { 9206 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9207 } 9208 } 9209 9210 maybeThrowExceptionForMultiArchCopy( 9211 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9212 9213 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9214 if (extractLibs) { 9215 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9216 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9217 useIsaSpecificSubdirs); 9218 } else { 9219 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9220 } 9221 } 9222 9223 maybeThrowExceptionForMultiArchCopy( 9224 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9225 9226 if (abi64 >= 0) { 9227 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9228 } 9229 9230 if (abi32 >= 0) { 9231 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9232 if (abi64 >= 0) { 9233 if (pkg.use32bitAbi) { 9234 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9235 pkg.applicationInfo.primaryCpuAbi = abi; 9236 } else { 9237 pkg.applicationInfo.secondaryCpuAbi = abi; 9238 } 9239 } else { 9240 pkg.applicationInfo.primaryCpuAbi = abi; 9241 } 9242 } 9243 9244 } else { 9245 String[] abiList = (cpuAbiOverride != null) ? 9246 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9247 9248 // Enable gross and lame hacks for apps that are built with old 9249 // SDK tools. We must scan their APKs for renderscript bitcode and 9250 // not launch them if it's present. Don't bother checking on devices 9251 // that don't have 64 bit support. 9252 boolean needsRenderScriptOverride = false; 9253 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9254 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9255 abiList = Build.SUPPORTED_32_BIT_ABIS; 9256 needsRenderScriptOverride = true; 9257 } 9258 9259 final int copyRet; 9260 if (extractLibs) { 9261 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9262 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9263 } else { 9264 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9265 } 9266 9267 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9268 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9269 "Error unpackaging native libs for app, errorCode=" + copyRet); 9270 } 9271 9272 if (copyRet >= 0) { 9273 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9274 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9275 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9276 } else if (needsRenderScriptOverride) { 9277 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9278 } 9279 } 9280 } catch (IOException ioe) { 9281 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9282 } finally { 9283 IoUtils.closeQuietly(handle); 9284 } 9285 9286 // Now that we've calculated the ABIs and determined if it's an internal app, 9287 // we will go ahead and populate the nativeLibraryPath. 9288 setNativeLibraryPaths(pkg); 9289 } 9290 9291 /** 9292 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9293 * i.e, so that all packages can be run inside a single process if required. 9294 * 9295 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9296 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9297 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9298 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9299 * updating a package that belongs to a shared user. 9300 * 9301 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9302 * adds unnecessary complexity. 9303 */ 9304 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9305 PackageParser.Package scannedPackage, boolean bootComplete) { 9306 String requiredInstructionSet = null; 9307 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9308 requiredInstructionSet = VMRuntime.getInstructionSet( 9309 scannedPackage.applicationInfo.primaryCpuAbi); 9310 } 9311 9312 PackageSetting requirer = null; 9313 for (PackageSetting ps : packagesForUser) { 9314 // If packagesForUser contains scannedPackage, we skip it. This will happen 9315 // when scannedPackage is an update of an existing package. Without this check, 9316 // we will never be able to change the ABI of any package belonging to a shared 9317 // user, even if it's compatible with other packages. 9318 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9319 if (ps.primaryCpuAbiString == null) { 9320 continue; 9321 } 9322 9323 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9324 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9325 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9326 // this but there's not much we can do. 9327 String errorMessage = "Instruction set mismatch, " 9328 + ((requirer == null) ? "[caller]" : requirer) 9329 + " requires " + requiredInstructionSet + " whereas " + ps 9330 + " requires " + instructionSet; 9331 Slog.w(TAG, errorMessage); 9332 } 9333 9334 if (requiredInstructionSet == null) { 9335 requiredInstructionSet = instructionSet; 9336 requirer = ps; 9337 } 9338 } 9339 } 9340 9341 if (requiredInstructionSet != null) { 9342 String adjustedAbi; 9343 if (requirer != null) { 9344 // requirer != null implies that either scannedPackage was null or that scannedPackage 9345 // did not require an ABI, in which case we have to adjust scannedPackage to match 9346 // the ABI of the set (which is the same as requirer's ABI) 9347 adjustedAbi = requirer.primaryCpuAbiString; 9348 if (scannedPackage != null) { 9349 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9350 } 9351 } else { 9352 // requirer == null implies that we're updating all ABIs in the set to 9353 // match scannedPackage. 9354 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9355 } 9356 9357 for (PackageSetting ps : packagesForUser) { 9358 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9359 if (ps.primaryCpuAbiString != null) { 9360 continue; 9361 } 9362 9363 ps.primaryCpuAbiString = adjustedAbi; 9364 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9365 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9366 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9367 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9368 + " (requirer=" 9369 + (requirer == null ? "null" : requirer.pkg.packageName) 9370 + ", scannedPackage=" 9371 + (scannedPackage != null ? scannedPackage.packageName : "null") 9372 + ")"); 9373 try { 9374 mInstaller.rmdex(ps.codePathString, 9375 getDexCodeInstructionSet(getPreferredInstructionSet())); 9376 } catch (InstallerException ignored) { 9377 } 9378 } 9379 } 9380 } 9381 } 9382 } 9383 9384 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9385 synchronized (mPackages) { 9386 mResolverReplaced = true; 9387 // Set up information for custom user intent resolution activity. 9388 mResolveActivity.applicationInfo = pkg.applicationInfo; 9389 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9390 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9391 mResolveActivity.processName = pkg.applicationInfo.packageName; 9392 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9393 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9394 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9395 mResolveActivity.theme = 0; 9396 mResolveActivity.exported = true; 9397 mResolveActivity.enabled = true; 9398 mResolveInfo.activityInfo = mResolveActivity; 9399 mResolveInfo.priority = 0; 9400 mResolveInfo.preferredOrder = 0; 9401 mResolveInfo.match = 0; 9402 mResolveComponentName = mCustomResolverComponentName; 9403 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9404 mResolveComponentName); 9405 } 9406 } 9407 9408 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9409 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9410 9411 // Set up information for ephemeral installer activity 9412 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9413 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9414 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9415 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9416 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9417 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9418 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9419 mEphemeralInstallerActivity.theme = 0; 9420 mEphemeralInstallerActivity.exported = true; 9421 mEphemeralInstallerActivity.enabled = true; 9422 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9423 mEphemeralInstallerInfo.priority = 0; 9424 mEphemeralInstallerInfo.preferredOrder = 1; 9425 mEphemeralInstallerInfo.isDefault = true; 9426 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9427 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9428 9429 if (DEBUG_EPHEMERAL) { 9430 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9431 } 9432 } 9433 9434 private static String calculateBundledApkRoot(final String codePathString) { 9435 final File codePath = new File(codePathString); 9436 final File codeRoot; 9437 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9438 codeRoot = Environment.getRootDirectory(); 9439 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9440 codeRoot = Environment.getOemDirectory(); 9441 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9442 codeRoot = Environment.getVendorDirectory(); 9443 } else { 9444 // Unrecognized code path; take its top real segment as the apk root: 9445 // e.g. /something/app/blah.apk => /something 9446 try { 9447 File f = codePath.getCanonicalFile(); 9448 File parent = f.getParentFile(); // non-null because codePath is a file 9449 File tmp; 9450 while ((tmp = parent.getParentFile()) != null) { 9451 f = parent; 9452 parent = tmp; 9453 } 9454 codeRoot = f; 9455 Slog.w(TAG, "Unrecognized code path " 9456 + codePath + " - using " + codeRoot); 9457 } catch (IOException e) { 9458 // Can't canonicalize the code path -- shenanigans? 9459 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9460 return Environment.getRootDirectory().getPath(); 9461 } 9462 } 9463 return codeRoot.getPath(); 9464 } 9465 9466 /** 9467 * Derive and set the location of native libraries for the given package, 9468 * which varies depending on where and how the package was installed. 9469 */ 9470 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9471 final ApplicationInfo info = pkg.applicationInfo; 9472 final String codePath = pkg.codePath; 9473 final File codeFile = new File(codePath); 9474 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9475 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9476 9477 info.nativeLibraryRootDir = null; 9478 info.nativeLibraryRootRequiresIsa = false; 9479 info.nativeLibraryDir = null; 9480 info.secondaryNativeLibraryDir = null; 9481 9482 if (isApkFile(codeFile)) { 9483 // Monolithic install 9484 if (bundledApp) { 9485 // If "/system/lib64/apkname" exists, assume that is the per-package 9486 // native library directory to use; otherwise use "/system/lib/apkname". 9487 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9488 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9489 getPrimaryInstructionSet(info)); 9490 9491 // This is a bundled system app so choose the path based on the ABI. 9492 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9493 // is just the default path. 9494 final String apkName = deriveCodePathName(codePath); 9495 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9496 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9497 apkName).getAbsolutePath(); 9498 9499 if (info.secondaryCpuAbi != null) { 9500 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9501 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9502 secondaryLibDir, apkName).getAbsolutePath(); 9503 } 9504 } else if (asecApp) { 9505 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9506 .getAbsolutePath(); 9507 } else { 9508 final String apkName = deriveCodePathName(codePath); 9509 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9510 .getAbsolutePath(); 9511 } 9512 9513 info.nativeLibraryRootRequiresIsa = false; 9514 info.nativeLibraryDir = info.nativeLibraryRootDir; 9515 } else { 9516 // Cluster install 9517 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9518 info.nativeLibraryRootRequiresIsa = true; 9519 9520 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9521 getPrimaryInstructionSet(info)).getAbsolutePath(); 9522 9523 if (info.secondaryCpuAbi != null) { 9524 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9525 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9526 } 9527 } 9528 } 9529 9530 /** 9531 * Calculate the abis and roots for a bundled app. These can uniquely 9532 * be determined from the contents of the system partition, i.e whether 9533 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9534 * of this information, and instead assume that the system was built 9535 * sensibly. 9536 */ 9537 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9538 PackageSetting pkgSetting) { 9539 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9540 9541 // If "/system/lib64/apkname" exists, assume that is the per-package 9542 // native library directory to use; otherwise use "/system/lib/apkname". 9543 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9544 setBundledAppAbi(pkg, apkRoot, apkName); 9545 // pkgSetting might be null during rescan following uninstall of updates 9546 // to a bundled app, so accommodate that possibility. The settings in 9547 // that case will be established later from the parsed package. 9548 // 9549 // If the settings aren't null, sync them up with what we've just derived. 9550 // note that apkRoot isn't stored in the package settings. 9551 if (pkgSetting != null) { 9552 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9553 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9554 } 9555 } 9556 9557 /** 9558 * Deduces the ABI of a bundled app and sets the relevant fields on the 9559 * parsed pkg object. 9560 * 9561 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9562 * under which system libraries are installed. 9563 * @param apkName the name of the installed package. 9564 */ 9565 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9566 final File codeFile = new File(pkg.codePath); 9567 9568 final boolean has64BitLibs; 9569 final boolean has32BitLibs; 9570 if (isApkFile(codeFile)) { 9571 // Monolithic install 9572 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9573 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9574 } else { 9575 // Cluster install 9576 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9577 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9578 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9579 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9580 has64BitLibs = (new File(rootDir, isa)).exists(); 9581 } else { 9582 has64BitLibs = false; 9583 } 9584 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9585 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9586 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9587 has32BitLibs = (new File(rootDir, isa)).exists(); 9588 } else { 9589 has32BitLibs = false; 9590 } 9591 } 9592 9593 if (has64BitLibs && !has32BitLibs) { 9594 // The package has 64 bit libs, but not 32 bit libs. Its primary 9595 // ABI should be 64 bit. We can safely assume here that the bundled 9596 // native libraries correspond to the most preferred ABI in the list. 9597 9598 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9599 pkg.applicationInfo.secondaryCpuAbi = null; 9600 } else if (has32BitLibs && !has64BitLibs) { 9601 // The package has 32 bit libs but not 64 bit libs. Its primary 9602 // ABI should be 32 bit. 9603 9604 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9605 pkg.applicationInfo.secondaryCpuAbi = null; 9606 } else if (has32BitLibs && has64BitLibs) { 9607 // The application has both 64 and 32 bit bundled libraries. We check 9608 // here that the app declares multiArch support, and warn if it doesn't. 9609 // 9610 // We will be lenient here and record both ABIs. The primary will be the 9611 // ABI that's higher on the list, i.e, a device that's configured to prefer 9612 // 64 bit apps will see a 64 bit primary ABI, 9613 9614 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9615 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9616 } 9617 9618 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9619 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9620 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9621 } else { 9622 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9623 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9624 } 9625 } else { 9626 pkg.applicationInfo.primaryCpuAbi = null; 9627 pkg.applicationInfo.secondaryCpuAbi = null; 9628 } 9629 } 9630 9631 private void killApplication(String pkgName, int appId, String reason) { 9632 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9633 } 9634 9635 private void killApplication(String pkgName, int appId, int userId, String reason) { 9636 // Request the ActivityManager to kill the process(only for existing packages) 9637 // so that we do not end up in a confused state while the user is still using the older 9638 // version of the application while the new one gets installed. 9639 final long token = Binder.clearCallingIdentity(); 9640 try { 9641 IActivityManager am = ActivityManagerNative.getDefault(); 9642 if (am != null) { 9643 try { 9644 am.killApplication(pkgName, appId, userId, reason); 9645 } catch (RemoteException e) { 9646 } 9647 } 9648 } finally { 9649 Binder.restoreCallingIdentity(token); 9650 } 9651 } 9652 9653 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9654 // Remove the parent package setting 9655 PackageSetting ps = (PackageSetting) pkg.mExtras; 9656 if (ps != null) { 9657 removePackageLI(ps, chatty); 9658 } 9659 // Remove the child package setting 9660 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9661 for (int i = 0; i < childCount; i++) { 9662 PackageParser.Package childPkg = pkg.childPackages.get(i); 9663 ps = (PackageSetting) childPkg.mExtras; 9664 if (ps != null) { 9665 removePackageLI(ps, chatty); 9666 } 9667 } 9668 } 9669 9670 void removePackageLI(PackageSetting ps, boolean chatty) { 9671 if (DEBUG_INSTALL) { 9672 if (chatty) 9673 Log.d(TAG, "Removing package " + ps.name); 9674 } 9675 9676 // writer 9677 synchronized (mPackages) { 9678 mPackages.remove(ps.name); 9679 final PackageParser.Package pkg = ps.pkg; 9680 if (pkg != null) { 9681 cleanPackageDataStructuresLILPw(pkg, chatty); 9682 } 9683 } 9684 } 9685 9686 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9687 if (DEBUG_INSTALL) { 9688 if (chatty) 9689 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9690 } 9691 9692 // writer 9693 synchronized (mPackages) { 9694 // Remove the parent package 9695 mPackages.remove(pkg.applicationInfo.packageName); 9696 cleanPackageDataStructuresLILPw(pkg, chatty); 9697 9698 // Remove the child packages 9699 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9700 for (int i = 0; i < childCount; i++) { 9701 PackageParser.Package childPkg = pkg.childPackages.get(i); 9702 mPackages.remove(childPkg.applicationInfo.packageName); 9703 cleanPackageDataStructuresLILPw(childPkg, chatty); 9704 } 9705 } 9706 } 9707 9708 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9709 int N = pkg.providers.size(); 9710 StringBuilder r = null; 9711 int i; 9712 for (i=0; i<N; i++) { 9713 PackageParser.Provider p = pkg.providers.get(i); 9714 mProviders.removeProvider(p); 9715 if (p.info.authority == null) { 9716 9717 /* There was another ContentProvider with this authority when 9718 * this app was installed so this authority is null, 9719 * Ignore it as we don't have to unregister the provider. 9720 */ 9721 continue; 9722 } 9723 String names[] = p.info.authority.split(";"); 9724 for (int j = 0; j < names.length; j++) { 9725 if (mProvidersByAuthority.get(names[j]) == p) { 9726 mProvidersByAuthority.remove(names[j]); 9727 if (DEBUG_REMOVE) { 9728 if (chatty) 9729 Log.d(TAG, "Unregistered content provider: " + names[j] 9730 + ", className = " + p.info.name + ", isSyncable = " 9731 + p.info.isSyncable); 9732 } 9733 } 9734 } 9735 if (DEBUG_REMOVE && chatty) { 9736 if (r == null) { 9737 r = new StringBuilder(256); 9738 } else { 9739 r.append(' '); 9740 } 9741 r.append(p.info.name); 9742 } 9743 } 9744 if (r != null) { 9745 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9746 } 9747 9748 N = pkg.services.size(); 9749 r = null; 9750 for (i=0; i<N; i++) { 9751 PackageParser.Service s = pkg.services.get(i); 9752 mServices.removeService(s); 9753 if (chatty) { 9754 if (r == null) { 9755 r = new StringBuilder(256); 9756 } else { 9757 r.append(' '); 9758 } 9759 r.append(s.info.name); 9760 } 9761 } 9762 if (r != null) { 9763 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9764 } 9765 9766 N = pkg.receivers.size(); 9767 r = null; 9768 for (i=0; i<N; i++) { 9769 PackageParser.Activity a = pkg.receivers.get(i); 9770 mReceivers.removeActivity(a, "receiver"); 9771 if (DEBUG_REMOVE && chatty) { 9772 if (r == null) { 9773 r = new StringBuilder(256); 9774 } else { 9775 r.append(' '); 9776 } 9777 r.append(a.info.name); 9778 } 9779 } 9780 if (r != null) { 9781 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9782 } 9783 9784 N = pkg.activities.size(); 9785 r = null; 9786 for (i=0; i<N; i++) { 9787 PackageParser.Activity a = pkg.activities.get(i); 9788 mActivities.removeActivity(a, "activity"); 9789 if (DEBUG_REMOVE && chatty) { 9790 if (r == null) { 9791 r = new StringBuilder(256); 9792 } else { 9793 r.append(' '); 9794 } 9795 r.append(a.info.name); 9796 } 9797 } 9798 if (r != null) { 9799 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9800 } 9801 9802 N = pkg.permissions.size(); 9803 r = null; 9804 for (i=0; i<N; i++) { 9805 PackageParser.Permission p = pkg.permissions.get(i); 9806 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9807 if (bp == null) { 9808 bp = mSettings.mPermissionTrees.get(p.info.name); 9809 } 9810 if (bp != null && bp.perm == p) { 9811 bp.perm = null; 9812 if (DEBUG_REMOVE && chatty) { 9813 if (r == null) { 9814 r = new StringBuilder(256); 9815 } else { 9816 r.append(' '); 9817 } 9818 r.append(p.info.name); 9819 } 9820 } 9821 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9822 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9823 if (appOpPkgs != null) { 9824 appOpPkgs.remove(pkg.packageName); 9825 } 9826 } 9827 } 9828 if (r != null) { 9829 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9830 } 9831 9832 N = pkg.requestedPermissions.size(); 9833 r = null; 9834 for (i=0; i<N; i++) { 9835 String perm = pkg.requestedPermissions.get(i); 9836 BasePermission bp = mSettings.mPermissions.get(perm); 9837 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9838 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9839 if (appOpPkgs != null) { 9840 appOpPkgs.remove(pkg.packageName); 9841 if (appOpPkgs.isEmpty()) { 9842 mAppOpPermissionPackages.remove(perm); 9843 } 9844 } 9845 } 9846 } 9847 if (r != null) { 9848 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9849 } 9850 9851 N = pkg.instrumentation.size(); 9852 r = null; 9853 for (i=0; i<N; i++) { 9854 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9855 mInstrumentation.remove(a.getComponentName()); 9856 if (DEBUG_REMOVE && chatty) { 9857 if (r == null) { 9858 r = new StringBuilder(256); 9859 } else { 9860 r.append(' '); 9861 } 9862 r.append(a.info.name); 9863 } 9864 } 9865 if (r != null) { 9866 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9867 } 9868 9869 r = null; 9870 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9871 // Only system apps can hold shared libraries. 9872 if (pkg.libraryNames != null) { 9873 for (i=0; i<pkg.libraryNames.size(); i++) { 9874 String name = pkg.libraryNames.get(i); 9875 SharedLibraryEntry cur = mSharedLibraries.get(name); 9876 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9877 mSharedLibraries.remove(name); 9878 if (DEBUG_REMOVE && chatty) { 9879 if (r == null) { 9880 r = new StringBuilder(256); 9881 } else { 9882 r.append(' '); 9883 } 9884 r.append(name); 9885 } 9886 } 9887 } 9888 } 9889 } 9890 if (r != null) { 9891 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9892 } 9893 } 9894 9895 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9896 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9897 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9898 return true; 9899 } 9900 } 9901 return false; 9902 } 9903 9904 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9905 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9906 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9907 9908 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9909 // Update the parent permissions 9910 updatePermissionsLPw(pkg.packageName, pkg, flags); 9911 // Update the child permissions 9912 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9913 for (int i = 0; i < childCount; i++) { 9914 PackageParser.Package childPkg = pkg.childPackages.get(i); 9915 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9916 } 9917 } 9918 9919 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9920 int flags) { 9921 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9922 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9923 } 9924 9925 private void updatePermissionsLPw(String changingPkg, 9926 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9927 // Make sure there are no dangling permission trees. 9928 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9929 while (it.hasNext()) { 9930 final BasePermission bp = it.next(); 9931 if (bp.packageSetting == null) { 9932 // We may not yet have parsed the package, so just see if 9933 // we still know about its settings. 9934 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9935 } 9936 if (bp.packageSetting == null) { 9937 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9938 + " from package " + bp.sourcePackage); 9939 it.remove(); 9940 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9941 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9942 Slog.i(TAG, "Removing old permission tree: " + bp.name 9943 + " from package " + bp.sourcePackage); 9944 flags |= UPDATE_PERMISSIONS_ALL; 9945 it.remove(); 9946 } 9947 } 9948 } 9949 9950 // Make sure all dynamic permissions have been assigned to a package, 9951 // and make sure there are no dangling permissions. 9952 it = mSettings.mPermissions.values().iterator(); 9953 while (it.hasNext()) { 9954 final BasePermission bp = it.next(); 9955 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9956 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9957 + bp.name + " pkg=" + bp.sourcePackage 9958 + " info=" + bp.pendingInfo); 9959 if (bp.packageSetting == null && bp.pendingInfo != null) { 9960 final BasePermission tree = findPermissionTreeLP(bp.name); 9961 if (tree != null && tree.perm != null) { 9962 bp.packageSetting = tree.packageSetting; 9963 bp.perm = new PackageParser.Permission(tree.perm.owner, 9964 new PermissionInfo(bp.pendingInfo)); 9965 bp.perm.info.packageName = tree.perm.info.packageName; 9966 bp.perm.info.name = bp.name; 9967 bp.uid = tree.uid; 9968 } 9969 } 9970 } 9971 if (bp.packageSetting == null) { 9972 // We may not yet have parsed the package, so just see if 9973 // we still know about its settings. 9974 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9975 } 9976 if (bp.packageSetting == null) { 9977 Slog.w(TAG, "Removing dangling permission: " + bp.name 9978 + " from package " + bp.sourcePackage); 9979 it.remove(); 9980 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9981 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9982 Slog.i(TAG, "Removing old permission: " + bp.name 9983 + " from package " + bp.sourcePackage); 9984 flags |= UPDATE_PERMISSIONS_ALL; 9985 it.remove(); 9986 } 9987 } 9988 } 9989 9990 // Now update the permissions for all packages, in particular 9991 // replace the granted permissions of the system packages. 9992 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9993 for (PackageParser.Package pkg : mPackages.values()) { 9994 if (pkg != pkgInfo) { 9995 // Only replace for packages on requested volume 9996 final String volumeUuid = getVolumeUuidForPackage(pkg); 9997 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9998 && Objects.equals(replaceVolumeUuid, volumeUuid); 9999 grantPermissionsLPw(pkg, replace, changingPkg); 10000 } 10001 } 10002 } 10003 10004 if (pkgInfo != null) { 10005 // Only replace for packages on requested volume 10006 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 10007 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 10008 && Objects.equals(replaceVolumeUuid, volumeUuid); 10009 grantPermissionsLPw(pkgInfo, replace, changingPkg); 10010 } 10011 } 10012 10013 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 10014 String packageOfInterest) { 10015 // IMPORTANT: There are two types of permissions: install and runtime. 10016 // Install time permissions are granted when the app is installed to 10017 // all device users and users added in the future. Runtime permissions 10018 // are granted at runtime explicitly to specific users. Normal and signature 10019 // protected permissions are install time permissions. Dangerous permissions 10020 // are install permissions if the app's target SDK is Lollipop MR1 or older, 10021 // otherwise they are runtime permissions. This function does not manage 10022 // runtime permissions except for the case an app targeting Lollipop MR1 10023 // being upgraded to target a newer SDK, in which case dangerous permissions 10024 // are transformed from install time to runtime ones. 10025 10026 final PackageSetting ps = (PackageSetting) pkg.mExtras; 10027 if (ps == null) { 10028 return; 10029 } 10030 10031 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 10032 10033 PermissionsState permissionsState = ps.getPermissionsState(); 10034 PermissionsState origPermissions = permissionsState; 10035 10036 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10037 10038 boolean runtimePermissionsRevoked = false; 10039 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10040 10041 boolean changedInstallPermission = false; 10042 10043 if (replace) { 10044 ps.installPermissionsFixed = false; 10045 if (!ps.isSharedUser()) { 10046 origPermissions = new PermissionsState(permissionsState); 10047 permissionsState.reset(); 10048 } else { 10049 // We need to know only about runtime permission changes since the 10050 // calling code always writes the install permissions state but 10051 // the runtime ones are written only if changed. The only cases of 10052 // changed runtime permissions here are promotion of an install to 10053 // runtime and revocation of a runtime from a shared user. 10054 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10055 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10056 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10057 runtimePermissionsRevoked = true; 10058 } 10059 } 10060 } 10061 10062 permissionsState.setGlobalGids(mGlobalGids); 10063 10064 final int N = pkg.requestedPermissions.size(); 10065 for (int i=0; i<N; i++) { 10066 final String name = pkg.requestedPermissions.get(i); 10067 final BasePermission bp = mSettings.mPermissions.get(name); 10068 10069 if (DEBUG_INSTALL) { 10070 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10071 } 10072 10073 if (bp == null || bp.packageSetting == null) { 10074 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10075 Slog.w(TAG, "Unknown permission " + name 10076 + " in package " + pkg.packageName); 10077 } 10078 continue; 10079 } 10080 10081 final String perm = bp.name; 10082 boolean allowedSig = false; 10083 int grant = GRANT_DENIED; 10084 10085 // Keep track of app op permissions. 10086 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10087 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10088 if (pkgs == null) { 10089 pkgs = new ArraySet<>(); 10090 mAppOpPermissionPackages.put(bp.name, pkgs); 10091 } 10092 pkgs.add(pkg.packageName); 10093 } 10094 10095 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10096 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10097 >= Build.VERSION_CODES.M; 10098 switch (level) { 10099 case PermissionInfo.PROTECTION_NORMAL: { 10100 // For all apps normal permissions are install time ones. 10101 grant = GRANT_INSTALL; 10102 } break; 10103 10104 case PermissionInfo.PROTECTION_DANGEROUS: { 10105 // If a permission review is required for legacy apps we represent 10106 // their permissions as always granted runtime ones since we need 10107 // to keep the review required permission flag per user while an 10108 // install permission's state is shared across all users. 10109 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired 10110 && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10111 // For legacy apps dangerous permissions are install time ones. 10112 grant = GRANT_INSTALL; 10113 } else if (origPermissions.hasInstallPermission(bp.name)) { 10114 // For legacy apps that became modern, install becomes runtime. 10115 grant = GRANT_UPGRADE; 10116 } else if (mPromoteSystemApps 10117 && isSystemApp(ps) 10118 && mExistingSystemPackages.contains(ps.name)) { 10119 // For legacy system apps, install becomes runtime. 10120 // We cannot check hasInstallPermission() for system apps since those 10121 // permissions were granted implicitly and not persisted pre-M. 10122 grant = GRANT_UPGRADE; 10123 } else { 10124 // For modern apps keep runtime permissions unchanged. 10125 grant = GRANT_RUNTIME; 10126 } 10127 } break; 10128 10129 case PermissionInfo.PROTECTION_SIGNATURE: { 10130 // For all apps signature permissions are install time ones. 10131 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10132 if (allowedSig) { 10133 grant = GRANT_INSTALL; 10134 } 10135 } break; 10136 } 10137 10138 if (DEBUG_INSTALL) { 10139 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10140 } 10141 10142 if (grant != GRANT_DENIED) { 10143 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10144 // If this is an existing, non-system package, then 10145 // we can't add any new permissions to it. 10146 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10147 // Except... if this is a permission that was added 10148 // to the platform (note: need to only do this when 10149 // updating the platform). 10150 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10151 grant = GRANT_DENIED; 10152 } 10153 } 10154 } 10155 10156 switch (grant) { 10157 case GRANT_INSTALL: { 10158 // Revoke this as runtime permission to handle the case of 10159 // a runtime permission being downgraded to an install one. 10160 // Also in permission review mode we keep dangerous permissions 10161 // for legacy apps 10162 for (int userId : UserManagerService.getInstance().getUserIds()) { 10163 if (origPermissions.getRuntimePermissionState( 10164 bp.name, userId) != null) { 10165 // Revoke the runtime permission and clear the flags. 10166 origPermissions.revokeRuntimePermission(bp, userId); 10167 origPermissions.updatePermissionFlags(bp, userId, 10168 PackageManager.MASK_PERMISSION_FLAGS, 0); 10169 // If we revoked a permission permission, we have to write. 10170 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10171 changedRuntimePermissionUserIds, userId); 10172 } 10173 } 10174 // Grant an install permission. 10175 if (permissionsState.grantInstallPermission(bp) != 10176 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10177 changedInstallPermission = true; 10178 } 10179 } break; 10180 10181 case GRANT_RUNTIME: { 10182 // Grant previously granted runtime permissions. 10183 for (int userId : UserManagerService.getInstance().getUserIds()) { 10184 PermissionState permissionState = origPermissions 10185 .getRuntimePermissionState(bp.name, userId); 10186 int flags = permissionState != null 10187 ? permissionState.getFlags() : 0; 10188 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10189 if (permissionsState.grantRuntimePermission(bp, userId) == 10190 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10191 // If we cannot put the permission as it was, we have to write. 10192 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10193 changedRuntimePermissionUserIds, userId); 10194 } 10195 // If the app supports runtime permissions no need for a review. 10196 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) 10197 && appSupportsRuntimePermissions 10198 && (flags & PackageManager 10199 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10200 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10201 // Since we changed the flags, we have to write. 10202 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10203 changedRuntimePermissionUserIds, userId); 10204 } 10205 } else if ((mPermissionReviewRequired 10206 || Build.PERMISSIONS_REVIEW_REQUIRED) 10207 && !appSupportsRuntimePermissions) { 10208 // For legacy apps that need a permission review, every new 10209 // runtime permission is granted but it is pending a review. 10210 // We also need to review only platform defined runtime 10211 // permissions as these are the only ones the platform knows 10212 // how to disable the API to simulate revocation as legacy 10213 // apps don't expect to run with revoked permissions. 10214 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10215 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10216 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10217 // We changed the flags, hence have to write. 10218 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10219 changedRuntimePermissionUserIds, userId); 10220 } 10221 } 10222 if (permissionsState.grantRuntimePermission(bp, userId) 10223 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10224 // We changed the permission, hence have to write. 10225 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10226 changedRuntimePermissionUserIds, userId); 10227 } 10228 } 10229 // Propagate the permission flags. 10230 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10231 } 10232 } break; 10233 10234 case GRANT_UPGRADE: { 10235 // Grant runtime permissions for a previously held install permission. 10236 PermissionState permissionState = origPermissions 10237 .getInstallPermissionState(bp.name); 10238 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10239 10240 if (origPermissions.revokeInstallPermission(bp) 10241 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10242 // We will be transferring the permission flags, so clear them. 10243 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10244 PackageManager.MASK_PERMISSION_FLAGS, 0); 10245 changedInstallPermission = true; 10246 } 10247 10248 // If the permission is not to be promoted to runtime we ignore it and 10249 // also its other flags as they are not applicable to install permissions. 10250 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10251 for (int userId : currentUserIds) { 10252 if (permissionsState.grantRuntimePermission(bp, userId) != 10253 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10254 // Transfer the permission flags. 10255 permissionsState.updatePermissionFlags(bp, userId, 10256 flags, flags); 10257 // If we granted the permission, we have to write. 10258 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10259 changedRuntimePermissionUserIds, userId); 10260 } 10261 } 10262 } 10263 } break; 10264 10265 default: { 10266 if (packageOfInterest == null 10267 || packageOfInterest.equals(pkg.packageName)) { 10268 Slog.w(TAG, "Not granting permission " + perm 10269 + " to package " + pkg.packageName 10270 + " because it was previously installed without"); 10271 } 10272 } break; 10273 } 10274 } else { 10275 if (permissionsState.revokeInstallPermission(bp) != 10276 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10277 // Also drop the permission flags. 10278 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10279 PackageManager.MASK_PERMISSION_FLAGS, 0); 10280 changedInstallPermission = true; 10281 Slog.i(TAG, "Un-granting permission " + perm 10282 + " from package " + pkg.packageName 10283 + " (protectionLevel=" + bp.protectionLevel 10284 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10285 + ")"); 10286 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10287 // Don't print warning for app op permissions, since it is fine for them 10288 // not to be granted, there is a UI for the user to decide. 10289 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10290 Slog.w(TAG, "Not granting permission " + perm 10291 + " to package " + pkg.packageName 10292 + " (protectionLevel=" + bp.protectionLevel 10293 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10294 + ")"); 10295 } 10296 } 10297 } 10298 } 10299 10300 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10301 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10302 // This is the first that we have heard about this package, so the 10303 // permissions we have now selected are fixed until explicitly 10304 // changed. 10305 ps.installPermissionsFixed = true; 10306 } 10307 10308 // Persist the runtime permissions state for users with changes. If permissions 10309 // were revoked because no app in the shared user declares them we have to 10310 // write synchronously to avoid losing runtime permissions state. 10311 for (int userId : changedRuntimePermissionUserIds) { 10312 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10313 } 10314 10315 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10316 } 10317 10318 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10319 boolean allowed = false; 10320 final int NP = PackageParser.NEW_PERMISSIONS.length; 10321 for (int ip=0; ip<NP; ip++) { 10322 final PackageParser.NewPermissionInfo npi 10323 = PackageParser.NEW_PERMISSIONS[ip]; 10324 if (npi.name.equals(perm) 10325 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10326 allowed = true; 10327 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10328 + pkg.packageName); 10329 break; 10330 } 10331 } 10332 return allowed; 10333 } 10334 10335 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10336 BasePermission bp, PermissionsState origPermissions) { 10337 boolean allowed; 10338 allowed = (compareSignatures( 10339 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10340 == PackageManager.SIGNATURE_MATCH) 10341 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10342 == PackageManager.SIGNATURE_MATCH); 10343 if (!allowed && (bp.protectionLevel 10344 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10345 if (isSystemApp(pkg)) { 10346 // For updated system applications, a system permission 10347 // is granted only if it had been defined by the original application. 10348 if (pkg.isUpdatedSystemApp()) { 10349 final PackageSetting sysPs = mSettings 10350 .getDisabledSystemPkgLPr(pkg.packageName); 10351 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10352 // If the original was granted this permission, we take 10353 // that grant decision as read and propagate it to the 10354 // update. 10355 if (sysPs.isPrivileged()) { 10356 allowed = true; 10357 } 10358 } else { 10359 // The system apk may have been updated with an older 10360 // version of the one on the data partition, but which 10361 // granted a new system permission that it didn't have 10362 // before. In this case we do want to allow the app to 10363 // now get the new permission if the ancestral apk is 10364 // privileged to get it. 10365 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10366 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10367 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10368 allowed = true; 10369 break; 10370 } 10371 } 10372 } 10373 // Also if a privileged parent package on the system image or any of 10374 // its children requested a privileged permission, the updated child 10375 // packages can also get the permission. 10376 if (pkg.parentPackage != null) { 10377 final PackageSetting disabledSysParentPs = mSettings 10378 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10379 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10380 && disabledSysParentPs.isPrivileged()) { 10381 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10382 allowed = true; 10383 } else if (disabledSysParentPs.pkg.childPackages != null) { 10384 final int count = disabledSysParentPs.pkg.childPackages.size(); 10385 for (int i = 0; i < count; i++) { 10386 PackageParser.Package disabledSysChildPkg = 10387 disabledSysParentPs.pkg.childPackages.get(i); 10388 if (isPackageRequestingPermission(disabledSysChildPkg, 10389 perm)) { 10390 allowed = true; 10391 break; 10392 } 10393 } 10394 } 10395 } 10396 } 10397 } 10398 } else { 10399 allowed = isPrivilegedApp(pkg); 10400 } 10401 } 10402 } 10403 if (!allowed) { 10404 if (!allowed && (bp.protectionLevel 10405 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10406 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10407 // If this was a previously normal/dangerous permission that got moved 10408 // to a system permission as part of the runtime permission redesign, then 10409 // we still want to blindly grant it to old apps. 10410 allowed = true; 10411 } 10412 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10413 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10414 // If this permission is to be granted to the system installer and 10415 // this app is an installer, then it gets the permission. 10416 allowed = true; 10417 } 10418 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10419 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10420 // If this permission is to be granted to the system verifier and 10421 // this app is a verifier, then it gets the permission. 10422 allowed = true; 10423 } 10424 if (!allowed && (bp.protectionLevel 10425 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10426 && isSystemApp(pkg)) { 10427 // Any pre-installed system app is allowed to get this permission. 10428 allowed = true; 10429 } 10430 if (!allowed && (bp.protectionLevel 10431 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10432 // For development permissions, a development permission 10433 // is granted only if it was already granted. 10434 allowed = origPermissions.hasInstallPermission(perm); 10435 } 10436 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10437 && pkg.packageName.equals(mSetupWizardPackage)) { 10438 // If this permission is to be granted to the system setup wizard and 10439 // this app is a setup wizard, then it gets the permission. 10440 allowed = true; 10441 } 10442 } 10443 return allowed; 10444 } 10445 10446 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10447 final int permCount = pkg.requestedPermissions.size(); 10448 for (int j = 0; j < permCount; j++) { 10449 String requestedPermission = pkg.requestedPermissions.get(j); 10450 if (permission.equals(requestedPermission)) { 10451 return true; 10452 } 10453 } 10454 return false; 10455 } 10456 10457 final class ActivityIntentResolver 10458 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10459 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10460 boolean defaultOnly, int userId) { 10461 if (!sUserManager.exists(userId)) return null; 10462 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10463 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10464 } 10465 10466 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10467 int userId) { 10468 if (!sUserManager.exists(userId)) return null; 10469 mFlags = flags; 10470 return super.queryIntent(intent, resolvedType, 10471 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10472 } 10473 10474 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10475 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10476 if (!sUserManager.exists(userId)) return null; 10477 if (packageActivities == null) { 10478 return null; 10479 } 10480 mFlags = flags; 10481 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10482 final int N = packageActivities.size(); 10483 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10484 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10485 10486 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10487 for (int i = 0; i < N; ++i) { 10488 intentFilters = packageActivities.get(i).intents; 10489 if (intentFilters != null && intentFilters.size() > 0) { 10490 PackageParser.ActivityIntentInfo[] array = 10491 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10492 intentFilters.toArray(array); 10493 listCut.add(array); 10494 } 10495 } 10496 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10497 } 10498 10499 /** 10500 * Finds a privileged activity that matches the specified activity names. 10501 */ 10502 private PackageParser.Activity findMatchingActivity( 10503 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10504 for (PackageParser.Activity sysActivity : activityList) { 10505 if (sysActivity.info.name.equals(activityInfo.name)) { 10506 return sysActivity; 10507 } 10508 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10509 return sysActivity; 10510 } 10511 if (sysActivity.info.targetActivity != null) { 10512 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10513 return sysActivity; 10514 } 10515 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10516 return sysActivity; 10517 } 10518 } 10519 } 10520 return null; 10521 } 10522 10523 public class IterGenerator<E> { 10524 public Iterator<E> generate(ActivityIntentInfo info) { 10525 return null; 10526 } 10527 } 10528 10529 public class ActionIterGenerator extends IterGenerator<String> { 10530 @Override 10531 public Iterator<String> generate(ActivityIntentInfo info) { 10532 return info.actionsIterator(); 10533 } 10534 } 10535 10536 public class CategoriesIterGenerator extends IterGenerator<String> { 10537 @Override 10538 public Iterator<String> generate(ActivityIntentInfo info) { 10539 return info.categoriesIterator(); 10540 } 10541 } 10542 10543 public class SchemesIterGenerator extends IterGenerator<String> { 10544 @Override 10545 public Iterator<String> generate(ActivityIntentInfo info) { 10546 return info.schemesIterator(); 10547 } 10548 } 10549 10550 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10551 @Override 10552 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10553 return info.authoritiesIterator(); 10554 } 10555 } 10556 10557 /** 10558 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10559 * MODIFIED. Do not pass in a list that should not be changed. 10560 */ 10561 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10562 IterGenerator<T> generator, Iterator<T> searchIterator) { 10563 // loop through the set of actions; every one must be found in the intent filter 10564 while (searchIterator.hasNext()) { 10565 // we must have at least one filter in the list to consider a match 10566 if (intentList.size() == 0) { 10567 break; 10568 } 10569 10570 final T searchAction = searchIterator.next(); 10571 10572 // loop through the set of intent filters 10573 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10574 while (intentIter.hasNext()) { 10575 final ActivityIntentInfo intentInfo = intentIter.next(); 10576 boolean selectionFound = false; 10577 10578 // loop through the intent filter's selection criteria; at least one 10579 // of them must match the searched criteria 10580 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10581 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10582 final T intentSelection = intentSelectionIter.next(); 10583 if (intentSelection != null && intentSelection.equals(searchAction)) { 10584 selectionFound = true; 10585 break; 10586 } 10587 } 10588 10589 // the selection criteria wasn't found in this filter's set; this filter 10590 // is not a potential match 10591 if (!selectionFound) { 10592 intentIter.remove(); 10593 } 10594 } 10595 } 10596 } 10597 10598 private boolean isProtectedAction(ActivityIntentInfo filter) { 10599 final Iterator<String> actionsIter = filter.actionsIterator(); 10600 while (actionsIter != null && actionsIter.hasNext()) { 10601 final String filterAction = actionsIter.next(); 10602 if (PROTECTED_ACTIONS.contains(filterAction)) { 10603 return true; 10604 } 10605 } 10606 return false; 10607 } 10608 10609 /** 10610 * Adjusts the priority of the given intent filter according to policy. 10611 * <p> 10612 * <ul> 10613 * <li>The priority for non privileged applications is capped to '0'</li> 10614 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10615 * <li>The priority for unbundled updates to privileged applications is capped to the 10616 * priority defined on the system partition</li> 10617 * </ul> 10618 * <p> 10619 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10620 * allowed to obtain any priority on any action. 10621 */ 10622 private void adjustPriority( 10623 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10624 // nothing to do; priority is fine as-is 10625 if (intent.getPriority() <= 0) { 10626 return; 10627 } 10628 10629 final ActivityInfo activityInfo = intent.activity.info; 10630 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10631 10632 final boolean privilegedApp = 10633 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10634 if (!privilegedApp) { 10635 // non-privileged applications can never define a priority >0 10636 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10637 + " package: " + applicationInfo.packageName 10638 + " activity: " + intent.activity.className 10639 + " origPrio: " + intent.getPriority()); 10640 intent.setPriority(0); 10641 return; 10642 } 10643 10644 if (systemActivities == null) { 10645 // the system package is not disabled; we're parsing the system partition 10646 if (isProtectedAction(intent)) { 10647 if (mDeferProtectedFilters) { 10648 // We can't deal with these just yet. No component should ever obtain a 10649 // >0 priority for a protected actions, with ONE exception -- the setup 10650 // wizard. The setup wizard, however, cannot be known until we're able to 10651 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10652 // until all intent filters have been processed. Chicken, meet egg. 10653 // Let the filter temporarily have a high priority and rectify the 10654 // priorities after all system packages have been scanned. 10655 mProtectedFilters.add(intent); 10656 if (DEBUG_FILTERS) { 10657 Slog.i(TAG, "Protected action; save for later;" 10658 + " package: " + applicationInfo.packageName 10659 + " activity: " + intent.activity.className 10660 + " origPrio: " + intent.getPriority()); 10661 } 10662 return; 10663 } else { 10664 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10665 Slog.i(TAG, "No setup wizard;" 10666 + " All protected intents capped to priority 0"); 10667 } 10668 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10669 if (DEBUG_FILTERS) { 10670 Slog.i(TAG, "Found setup wizard;" 10671 + " allow priority " + intent.getPriority() + ";" 10672 + " package: " + intent.activity.info.packageName 10673 + " activity: " + intent.activity.className 10674 + " priority: " + intent.getPriority()); 10675 } 10676 // setup wizard gets whatever it wants 10677 return; 10678 } 10679 Slog.w(TAG, "Protected action; cap priority to 0;" 10680 + " package: " + intent.activity.info.packageName 10681 + " activity: " + intent.activity.className 10682 + " origPrio: " + intent.getPriority()); 10683 intent.setPriority(0); 10684 return; 10685 } 10686 } 10687 // privileged apps on the system image get whatever priority they request 10688 return; 10689 } 10690 10691 // privileged app unbundled update ... try to find the same activity 10692 final PackageParser.Activity foundActivity = 10693 findMatchingActivity(systemActivities, activityInfo); 10694 if (foundActivity == null) { 10695 // this is a new activity; it cannot obtain >0 priority 10696 if (DEBUG_FILTERS) { 10697 Slog.i(TAG, "New activity; cap priority to 0;" 10698 + " package: " + applicationInfo.packageName 10699 + " activity: " + intent.activity.className 10700 + " origPrio: " + intent.getPriority()); 10701 } 10702 intent.setPriority(0); 10703 return; 10704 } 10705 10706 // found activity, now check for filter equivalence 10707 10708 // a shallow copy is enough; we modify the list, not its contents 10709 final List<ActivityIntentInfo> intentListCopy = 10710 new ArrayList<>(foundActivity.intents); 10711 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10712 10713 // find matching action subsets 10714 final Iterator<String> actionsIterator = intent.actionsIterator(); 10715 if (actionsIterator != null) { 10716 getIntentListSubset( 10717 intentListCopy, new ActionIterGenerator(), actionsIterator); 10718 if (intentListCopy.size() == 0) { 10719 // no more intents to match; we're not equivalent 10720 if (DEBUG_FILTERS) { 10721 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10722 + " package: " + applicationInfo.packageName 10723 + " activity: " + intent.activity.className 10724 + " origPrio: " + intent.getPriority()); 10725 } 10726 intent.setPriority(0); 10727 return; 10728 } 10729 } 10730 10731 // find matching category subsets 10732 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10733 if (categoriesIterator != null) { 10734 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10735 categoriesIterator); 10736 if (intentListCopy.size() == 0) { 10737 // no more intents to match; we're not equivalent 10738 if (DEBUG_FILTERS) { 10739 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10740 + " package: " + applicationInfo.packageName 10741 + " activity: " + intent.activity.className 10742 + " origPrio: " + intent.getPriority()); 10743 } 10744 intent.setPriority(0); 10745 return; 10746 } 10747 } 10748 10749 // find matching schemes subsets 10750 final Iterator<String> schemesIterator = intent.schemesIterator(); 10751 if (schemesIterator != null) { 10752 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10753 schemesIterator); 10754 if (intentListCopy.size() == 0) { 10755 // no more intents to match; we're not equivalent 10756 if (DEBUG_FILTERS) { 10757 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10758 + " package: " + applicationInfo.packageName 10759 + " activity: " + intent.activity.className 10760 + " origPrio: " + intent.getPriority()); 10761 } 10762 intent.setPriority(0); 10763 return; 10764 } 10765 } 10766 10767 // find matching authorities subsets 10768 final Iterator<IntentFilter.AuthorityEntry> 10769 authoritiesIterator = intent.authoritiesIterator(); 10770 if (authoritiesIterator != null) { 10771 getIntentListSubset(intentListCopy, 10772 new AuthoritiesIterGenerator(), 10773 authoritiesIterator); 10774 if (intentListCopy.size() == 0) { 10775 // no more intents to match; we're not equivalent 10776 if (DEBUG_FILTERS) { 10777 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10778 + " package: " + applicationInfo.packageName 10779 + " activity: " + intent.activity.className 10780 + " origPrio: " + intent.getPriority()); 10781 } 10782 intent.setPriority(0); 10783 return; 10784 } 10785 } 10786 10787 // we found matching filter(s); app gets the max priority of all intents 10788 int cappedPriority = 0; 10789 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10790 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10791 } 10792 if (intent.getPriority() > cappedPriority) { 10793 if (DEBUG_FILTERS) { 10794 Slog.i(TAG, "Found matching filter(s);" 10795 + " cap priority to " + cappedPriority + ";" 10796 + " package: " + applicationInfo.packageName 10797 + " activity: " + intent.activity.className 10798 + " origPrio: " + intent.getPriority()); 10799 } 10800 intent.setPriority(cappedPriority); 10801 return; 10802 } 10803 // all this for nothing; the requested priority was <= what was on the system 10804 } 10805 10806 public final void addActivity(PackageParser.Activity a, String type) { 10807 mActivities.put(a.getComponentName(), a); 10808 if (DEBUG_SHOW_INFO) 10809 Log.v( 10810 TAG, " " + type + " " + 10811 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10812 if (DEBUG_SHOW_INFO) 10813 Log.v(TAG, " Class=" + a.info.name); 10814 final int NI = a.intents.size(); 10815 for (int j=0; j<NI; j++) { 10816 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10817 if ("activity".equals(type)) { 10818 final PackageSetting ps = 10819 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10820 final List<PackageParser.Activity> systemActivities = 10821 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10822 adjustPriority(systemActivities, intent); 10823 } 10824 if (DEBUG_SHOW_INFO) { 10825 Log.v(TAG, " IntentFilter:"); 10826 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10827 } 10828 if (!intent.debugCheck()) { 10829 Log.w(TAG, "==> For Activity " + a.info.name); 10830 } 10831 addFilter(intent); 10832 } 10833 } 10834 10835 public final void removeActivity(PackageParser.Activity a, String type) { 10836 mActivities.remove(a.getComponentName()); 10837 if (DEBUG_SHOW_INFO) { 10838 Log.v(TAG, " " + type + " " 10839 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10840 : a.info.name) + ":"); 10841 Log.v(TAG, " Class=" + a.info.name); 10842 } 10843 final int NI = a.intents.size(); 10844 for (int j=0; j<NI; j++) { 10845 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10846 if (DEBUG_SHOW_INFO) { 10847 Log.v(TAG, " IntentFilter:"); 10848 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10849 } 10850 removeFilter(intent); 10851 } 10852 } 10853 10854 @Override 10855 protected boolean allowFilterResult( 10856 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10857 ActivityInfo filterAi = filter.activity.info; 10858 for (int i=dest.size()-1; i>=0; i--) { 10859 ActivityInfo destAi = dest.get(i).activityInfo; 10860 if (destAi.name == filterAi.name 10861 && destAi.packageName == filterAi.packageName) { 10862 return false; 10863 } 10864 } 10865 return true; 10866 } 10867 10868 @Override 10869 protected ActivityIntentInfo[] newArray(int size) { 10870 return new ActivityIntentInfo[size]; 10871 } 10872 10873 @Override 10874 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10875 if (!sUserManager.exists(userId)) return true; 10876 PackageParser.Package p = filter.activity.owner; 10877 if (p != null) { 10878 PackageSetting ps = (PackageSetting)p.mExtras; 10879 if (ps != null) { 10880 // System apps are never considered stopped for purposes of 10881 // filtering, because there may be no way for the user to 10882 // actually re-launch them. 10883 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10884 && ps.getStopped(userId); 10885 } 10886 } 10887 return false; 10888 } 10889 10890 @Override 10891 protected boolean isPackageForFilter(String packageName, 10892 PackageParser.ActivityIntentInfo info) { 10893 return packageName.equals(info.activity.owner.packageName); 10894 } 10895 10896 @Override 10897 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10898 int match, int userId) { 10899 if (!sUserManager.exists(userId)) return null; 10900 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10901 return null; 10902 } 10903 final PackageParser.Activity activity = info.activity; 10904 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10905 if (ps == null) { 10906 return null; 10907 } 10908 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10909 ps.readUserState(userId), userId); 10910 if (ai == null) { 10911 return null; 10912 } 10913 final ResolveInfo res = new ResolveInfo(); 10914 res.activityInfo = ai; 10915 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10916 res.filter = info; 10917 } 10918 if (info != null) { 10919 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10920 } 10921 res.priority = info.getPriority(); 10922 res.preferredOrder = activity.owner.mPreferredOrder; 10923 //System.out.println("Result: " + res.activityInfo.className + 10924 // " = " + res.priority); 10925 res.match = match; 10926 res.isDefault = info.hasDefault; 10927 res.labelRes = info.labelRes; 10928 res.nonLocalizedLabel = info.nonLocalizedLabel; 10929 if (userNeedsBadging(userId)) { 10930 res.noResourceId = true; 10931 } else { 10932 res.icon = info.icon; 10933 } 10934 res.iconResourceId = info.icon; 10935 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10936 return res; 10937 } 10938 10939 @Override 10940 protected void sortResults(List<ResolveInfo> results) { 10941 Collections.sort(results, mResolvePrioritySorter); 10942 } 10943 10944 @Override 10945 protected void dumpFilter(PrintWriter out, String prefix, 10946 PackageParser.ActivityIntentInfo filter) { 10947 out.print(prefix); out.print( 10948 Integer.toHexString(System.identityHashCode(filter.activity))); 10949 out.print(' '); 10950 filter.activity.printComponentShortName(out); 10951 out.print(" filter "); 10952 out.println(Integer.toHexString(System.identityHashCode(filter))); 10953 } 10954 10955 @Override 10956 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10957 return filter.activity; 10958 } 10959 10960 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10961 PackageParser.Activity activity = (PackageParser.Activity)label; 10962 out.print(prefix); out.print( 10963 Integer.toHexString(System.identityHashCode(activity))); 10964 out.print(' '); 10965 activity.printComponentShortName(out); 10966 if (count > 1) { 10967 out.print(" ("); out.print(count); out.print(" filters)"); 10968 } 10969 out.println(); 10970 } 10971 10972 // Keys are String (activity class name), values are Activity. 10973 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10974 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10975 private int mFlags; 10976 } 10977 10978 private final class ServiceIntentResolver 10979 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10980 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10981 boolean defaultOnly, int userId) { 10982 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10983 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10984 } 10985 10986 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10987 int userId) { 10988 if (!sUserManager.exists(userId)) return null; 10989 mFlags = flags; 10990 return super.queryIntent(intent, resolvedType, 10991 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10992 } 10993 10994 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10995 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10996 if (!sUserManager.exists(userId)) return null; 10997 if (packageServices == null) { 10998 return null; 10999 } 11000 mFlags = flags; 11001 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 11002 final int N = packageServices.size(); 11003 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 11004 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 11005 11006 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 11007 for (int i = 0; i < N; ++i) { 11008 intentFilters = packageServices.get(i).intents; 11009 if (intentFilters != null && intentFilters.size() > 0) { 11010 PackageParser.ServiceIntentInfo[] array = 11011 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 11012 intentFilters.toArray(array); 11013 listCut.add(array); 11014 } 11015 } 11016 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11017 } 11018 11019 public final void addService(PackageParser.Service s) { 11020 mServices.put(s.getComponentName(), s); 11021 if (DEBUG_SHOW_INFO) { 11022 Log.v(TAG, " " 11023 + (s.info.nonLocalizedLabel != null 11024 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11025 Log.v(TAG, " Class=" + s.info.name); 11026 } 11027 final int NI = s.intents.size(); 11028 int j; 11029 for (j=0; j<NI; j++) { 11030 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11031 if (DEBUG_SHOW_INFO) { 11032 Log.v(TAG, " IntentFilter:"); 11033 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11034 } 11035 if (!intent.debugCheck()) { 11036 Log.w(TAG, "==> For Service " + s.info.name); 11037 } 11038 addFilter(intent); 11039 } 11040 } 11041 11042 public final void removeService(PackageParser.Service s) { 11043 mServices.remove(s.getComponentName()); 11044 if (DEBUG_SHOW_INFO) { 11045 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11046 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11047 Log.v(TAG, " Class=" + s.info.name); 11048 } 11049 final int NI = s.intents.size(); 11050 int j; 11051 for (j=0; j<NI; j++) { 11052 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11053 if (DEBUG_SHOW_INFO) { 11054 Log.v(TAG, " IntentFilter:"); 11055 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11056 } 11057 removeFilter(intent); 11058 } 11059 } 11060 11061 @Override 11062 protected boolean allowFilterResult( 11063 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11064 ServiceInfo filterSi = filter.service.info; 11065 for (int i=dest.size()-1; i>=0; i--) { 11066 ServiceInfo destAi = dest.get(i).serviceInfo; 11067 if (destAi.name == filterSi.name 11068 && destAi.packageName == filterSi.packageName) { 11069 return false; 11070 } 11071 } 11072 return true; 11073 } 11074 11075 @Override 11076 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11077 return new PackageParser.ServiceIntentInfo[size]; 11078 } 11079 11080 @Override 11081 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11082 if (!sUserManager.exists(userId)) return true; 11083 PackageParser.Package p = filter.service.owner; 11084 if (p != null) { 11085 PackageSetting ps = (PackageSetting)p.mExtras; 11086 if (ps != null) { 11087 // System apps are never considered stopped for purposes of 11088 // filtering, because there may be no way for the user to 11089 // actually re-launch them. 11090 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11091 && ps.getStopped(userId); 11092 } 11093 } 11094 return false; 11095 } 11096 11097 @Override 11098 protected boolean isPackageForFilter(String packageName, 11099 PackageParser.ServiceIntentInfo info) { 11100 return packageName.equals(info.service.owner.packageName); 11101 } 11102 11103 @Override 11104 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11105 int match, int userId) { 11106 if (!sUserManager.exists(userId)) return null; 11107 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11108 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11109 return null; 11110 } 11111 final PackageParser.Service service = info.service; 11112 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11113 if (ps == null) { 11114 return null; 11115 } 11116 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11117 ps.readUserState(userId), userId); 11118 if (si == null) { 11119 return null; 11120 } 11121 final ResolveInfo res = new ResolveInfo(); 11122 res.serviceInfo = si; 11123 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11124 res.filter = filter; 11125 } 11126 res.priority = info.getPriority(); 11127 res.preferredOrder = service.owner.mPreferredOrder; 11128 res.match = match; 11129 res.isDefault = info.hasDefault; 11130 res.labelRes = info.labelRes; 11131 res.nonLocalizedLabel = info.nonLocalizedLabel; 11132 res.icon = info.icon; 11133 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11134 return res; 11135 } 11136 11137 @Override 11138 protected void sortResults(List<ResolveInfo> results) { 11139 Collections.sort(results, mResolvePrioritySorter); 11140 } 11141 11142 @Override 11143 protected void dumpFilter(PrintWriter out, String prefix, 11144 PackageParser.ServiceIntentInfo filter) { 11145 out.print(prefix); out.print( 11146 Integer.toHexString(System.identityHashCode(filter.service))); 11147 out.print(' '); 11148 filter.service.printComponentShortName(out); 11149 out.print(" filter "); 11150 out.println(Integer.toHexString(System.identityHashCode(filter))); 11151 } 11152 11153 @Override 11154 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11155 return filter.service; 11156 } 11157 11158 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11159 PackageParser.Service service = (PackageParser.Service)label; 11160 out.print(prefix); out.print( 11161 Integer.toHexString(System.identityHashCode(service))); 11162 out.print(' '); 11163 service.printComponentShortName(out); 11164 if (count > 1) { 11165 out.print(" ("); out.print(count); out.print(" filters)"); 11166 } 11167 out.println(); 11168 } 11169 11170// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11171// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11172// final List<ResolveInfo> retList = Lists.newArrayList(); 11173// while (i.hasNext()) { 11174// final ResolveInfo resolveInfo = (ResolveInfo) i; 11175// if (isEnabledLP(resolveInfo.serviceInfo)) { 11176// retList.add(resolveInfo); 11177// } 11178// } 11179// return retList; 11180// } 11181 11182 // Keys are String (activity class name), values are Activity. 11183 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11184 = new ArrayMap<ComponentName, PackageParser.Service>(); 11185 private int mFlags; 11186 }; 11187 11188 private final class ProviderIntentResolver 11189 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11190 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11191 boolean defaultOnly, int userId) { 11192 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11193 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11194 } 11195 11196 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11197 int userId) { 11198 if (!sUserManager.exists(userId)) 11199 return null; 11200 mFlags = flags; 11201 return super.queryIntent(intent, resolvedType, 11202 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11203 } 11204 11205 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11206 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11207 if (!sUserManager.exists(userId)) 11208 return null; 11209 if (packageProviders == null) { 11210 return null; 11211 } 11212 mFlags = flags; 11213 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11214 final int N = packageProviders.size(); 11215 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11216 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11217 11218 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11219 for (int i = 0; i < N; ++i) { 11220 intentFilters = packageProviders.get(i).intents; 11221 if (intentFilters != null && intentFilters.size() > 0) { 11222 PackageParser.ProviderIntentInfo[] array = 11223 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11224 intentFilters.toArray(array); 11225 listCut.add(array); 11226 } 11227 } 11228 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11229 } 11230 11231 public final void addProvider(PackageParser.Provider p) { 11232 if (mProviders.containsKey(p.getComponentName())) { 11233 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11234 return; 11235 } 11236 11237 mProviders.put(p.getComponentName(), p); 11238 if (DEBUG_SHOW_INFO) { 11239 Log.v(TAG, " " 11240 + (p.info.nonLocalizedLabel != null 11241 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11242 Log.v(TAG, " Class=" + p.info.name); 11243 } 11244 final int NI = p.intents.size(); 11245 int j; 11246 for (j = 0; j < NI; j++) { 11247 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11248 if (DEBUG_SHOW_INFO) { 11249 Log.v(TAG, " IntentFilter:"); 11250 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11251 } 11252 if (!intent.debugCheck()) { 11253 Log.w(TAG, "==> For Provider " + p.info.name); 11254 } 11255 addFilter(intent); 11256 } 11257 } 11258 11259 public final void removeProvider(PackageParser.Provider p) { 11260 mProviders.remove(p.getComponentName()); 11261 if (DEBUG_SHOW_INFO) { 11262 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11263 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11264 Log.v(TAG, " Class=" + p.info.name); 11265 } 11266 final int NI = p.intents.size(); 11267 int j; 11268 for (j = 0; j < NI; j++) { 11269 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11270 if (DEBUG_SHOW_INFO) { 11271 Log.v(TAG, " IntentFilter:"); 11272 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11273 } 11274 removeFilter(intent); 11275 } 11276 } 11277 11278 @Override 11279 protected boolean allowFilterResult( 11280 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11281 ProviderInfo filterPi = filter.provider.info; 11282 for (int i = dest.size() - 1; i >= 0; i--) { 11283 ProviderInfo destPi = dest.get(i).providerInfo; 11284 if (destPi.name == filterPi.name 11285 && destPi.packageName == filterPi.packageName) { 11286 return false; 11287 } 11288 } 11289 return true; 11290 } 11291 11292 @Override 11293 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11294 return new PackageParser.ProviderIntentInfo[size]; 11295 } 11296 11297 @Override 11298 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11299 if (!sUserManager.exists(userId)) 11300 return true; 11301 PackageParser.Package p = filter.provider.owner; 11302 if (p != null) { 11303 PackageSetting ps = (PackageSetting) p.mExtras; 11304 if (ps != null) { 11305 // System apps are never considered stopped for purposes of 11306 // filtering, because there may be no way for the user to 11307 // actually re-launch them. 11308 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11309 && ps.getStopped(userId); 11310 } 11311 } 11312 return false; 11313 } 11314 11315 @Override 11316 protected boolean isPackageForFilter(String packageName, 11317 PackageParser.ProviderIntentInfo info) { 11318 return packageName.equals(info.provider.owner.packageName); 11319 } 11320 11321 @Override 11322 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11323 int match, int userId) { 11324 if (!sUserManager.exists(userId)) 11325 return null; 11326 final PackageParser.ProviderIntentInfo info = filter; 11327 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11328 return null; 11329 } 11330 final PackageParser.Provider provider = info.provider; 11331 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11332 if (ps == null) { 11333 return null; 11334 } 11335 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11336 ps.readUserState(userId), userId); 11337 if (pi == null) { 11338 return null; 11339 } 11340 final ResolveInfo res = new ResolveInfo(); 11341 res.providerInfo = pi; 11342 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11343 res.filter = filter; 11344 } 11345 res.priority = info.getPriority(); 11346 res.preferredOrder = provider.owner.mPreferredOrder; 11347 res.match = match; 11348 res.isDefault = info.hasDefault; 11349 res.labelRes = info.labelRes; 11350 res.nonLocalizedLabel = info.nonLocalizedLabel; 11351 res.icon = info.icon; 11352 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11353 return res; 11354 } 11355 11356 @Override 11357 protected void sortResults(List<ResolveInfo> results) { 11358 Collections.sort(results, mResolvePrioritySorter); 11359 } 11360 11361 @Override 11362 protected void dumpFilter(PrintWriter out, String prefix, 11363 PackageParser.ProviderIntentInfo filter) { 11364 out.print(prefix); 11365 out.print( 11366 Integer.toHexString(System.identityHashCode(filter.provider))); 11367 out.print(' '); 11368 filter.provider.printComponentShortName(out); 11369 out.print(" filter "); 11370 out.println(Integer.toHexString(System.identityHashCode(filter))); 11371 } 11372 11373 @Override 11374 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11375 return filter.provider; 11376 } 11377 11378 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11379 PackageParser.Provider provider = (PackageParser.Provider)label; 11380 out.print(prefix); out.print( 11381 Integer.toHexString(System.identityHashCode(provider))); 11382 out.print(' '); 11383 provider.printComponentShortName(out); 11384 if (count > 1) { 11385 out.print(" ("); out.print(count); out.print(" filters)"); 11386 } 11387 out.println(); 11388 } 11389 11390 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11391 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11392 private int mFlags; 11393 } 11394 11395 private static final class EphemeralIntentResolver 11396 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11397 /** 11398 * The result that has the highest defined order. Ordering applies on a 11399 * per-package basis. Mapping is from package name to Pair of order and 11400 * EphemeralResolveInfo. 11401 * <p> 11402 * NOTE: This is implemented as a field variable for convenience and efficiency. 11403 * By having a field variable, we're able to track filter ordering as soon as 11404 * a non-zero order is defined. Otherwise, multiple loops across the result set 11405 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11406 * this needs to be contained entirely within {@link #filterResults()}. 11407 */ 11408 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11409 11410 @Override 11411 protected EphemeralResolveIntentInfo[] newArray(int size) { 11412 return new EphemeralResolveIntentInfo[size]; 11413 } 11414 11415 @Override 11416 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11417 return true; 11418 } 11419 11420 @Override 11421 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11422 int userId) { 11423 if (!sUserManager.exists(userId)) { 11424 return null; 11425 } 11426 final String packageName = info.getEphemeralResolveInfo().getPackageName(); 11427 final Integer order = info.getOrder(); 11428 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11429 mOrderResult.get(packageName); 11430 // ordering is enabled and this item's order isn't high enough 11431 if (lastOrderResult != null && lastOrderResult.first >= order) { 11432 return null; 11433 } 11434 final EphemeralResolveInfo res = info.getEphemeralResolveInfo(); 11435 if (order > 0) { 11436 // non-zero order, enable ordering 11437 mOrderResult.put(packageName, new Pair<>(order, res)); 11438 } 11439 return res; 11440 } 11441 11442 @Override 11443 protected void filterResults(List<EphemeralResolveInfo> results) { 11444 // only do work if ordering is enabled [most of the time it won't be] 11445 if (mOrderResult.size() == 0) { 11446 return; 11447 } 11448 int resultSize = results.size(); 11449 for (int i = 0; i < resultSize; i++) { 11450 final EphemeralResolveInfo info = results.get(i); 11451 final String packageName = info.getPackageName(); 11452 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11453 if (savedInfo == null) { 11454 // package doesn't having ordering 11455 continue; 11456 } 11457 if (savedInfo.second == info) { 11458 // circled back to the highest ordered item; remove from order list 11459 mOrderResult.remove(savedInfo); 11460 if (mOrderResult.size() == 0) { 11461 // no more ordered items 11462 break; 11463 } 11464 continue; 11465 } 11466 // item has a worse order, remove it from the result list 11467 results.remove(i); 11468 resultSize--; 11469 i--; 11470 } 11471 } 11472 } 11473 11474 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11475 new Comparator<ResolveInfo>() { 11476 public int compare(ResolveInfo r1, ResolveInfo r2) { 11477 int v1 = r1.priority; 11478 int v2 = r2.priority; 11479 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11480 if (v1 != v2) { 11481 return (v1 > v2) ? -1 : 1; 11482 } 11483 v1 = r1.preferredOrder; 11484 v2 = r2.preferredOrder; 11485 if (v1 != v2) { 11486 return (v1 > v2) ? -1 : 1; 11487 } 11488 if (r1.isDefault != r2.isDefault) { 11489 return r1.isDefault ? -1 : 1; 11490 } 11491 v1 = r1.match; 11492 v2 = r2.match; 11493 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11494 if (v1 != v2) { 11495 return (v1 > v2) ? -1 : 1; 11496 } 11497 if (r1.system != r2.system) { 11498 return r1.system ? -1 : 1; 11499 } 11500 if (r1.activityInfo != null) { 11501 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11502 } 11503 if (r1.serviceInfo != null) { 11504 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11505 } 11506 if (r1.providerInfo != null) { 11507 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11508 } 11509 return 0; 11510 } 11511 }; 11512 11513 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11514 new Comparator<ProviderInfo>() { 11515 public int compare(ProviderInfo p1, ProviderInfo p2) { 11516 final int v1 = p1.initOrder; 11517 final int v2 = p2.initOrder; 11518 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11519 } 11520 }; 11521 11522 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11523 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11524 final int[] userIds) { 11525 mHandler.post(new Runnable() { 11526 @Override 11527 public void run() { 11528 try { 11529 final IActivityManager am = ActivityManagerNative.getDefault(); 11530 if (am == null) return; 11531 final int[] resolvedUserIds; 11532 if (userIds == null) { 11533 resolvedUserIds = am.getRunningUserIds(); 11534 } else { 11535 resolvedUserIds = userIds; 11536 } 11537 for (int id : resolvedUserIds) { 11538 final Intent intent = new Intent(action, 11539 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11540 if (extras != null) { 11541 intent.putExtras(extras); 11542 } 11543 if (targetPkg != null) { 11544 intent.setPackage(targetPkg); 11545 } 11546 // Modify the UID when posting to other users 11547 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11548 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11549 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11550 intent.putExtra(Intent.EXTRA_UID, uid); 11551 } 11552 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11553 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11554 if (DEBUG_BROADCASTS) { 11555 RuntimeException here = new RuntimeException("here"); 11556 here.fillInStackTrace(); 11557 Slog.d(TAG, "Sending to user " + id + ": " 11558 + intent.toShortString(false, true, false, false) 11559 + " " + intent.getExtras(), here); 11560 } 11561 am.broadcastIntent(null, intent, null, finishedReceiver, 11562 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11563 null, finishedReceiver != null, false, id); 11564 } 11565 } catch (RemoteException ex) { 11566 } 11567 } 11568 }); 11569 } 11570 11571 /** 11572 * Check if the external storage media is available. This is true if there 11573 * is a mounted external storage medium or if the external storage is 11574 * emulated. 11575 */ 11576 private boolean isExternalMediaAvailable() { 11577 return mMediaMounted || Environment.isExternalStorageEmulated(); 11578 } 11579 11580 @Override 11581 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11582 // writer 11583 synchronized (mPackages) { 11584 if (!isExternalMediaAvailable()) { 11585 // If the external storage is no longer mounted at this point, 11586 // the caller may not have been able to delete all of this 11587 // packages files and can not delete any more. Bail. 11588 return null; 11589 } 11590 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11591 if (lastPackage != null) { 11592 pkgs.remove(lastPackage); 11593 } 11594 if (pkgs.size() > 0) { 11595 return pkgs.get(0); 11596 } 11597 } 11598 return null; 11599 } 11600 11601 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11602 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11603 userId, andCode ? 1 : 0, packageName); 11604 if (mSystemReady) { 11605 msg.sendToTarget(); 11606 } else { 11607 if (mPostSystemReadyMessages == null) { 11608 mPostSystemReadyMessages = new ArrayList<>(); 11609 } 11610 mPostSystemReadyMessages.add(msg); 11611 } 11612 } 11613 11614 void startCleaningPackages() { 11615 // reader 11616 if (!isExternalMediaAvailable()) { 11617 return; 11618 } 11619 synchronized (mPackages) { 11620 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11621 return; 11622 } 11623 } 11624 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11625 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11626 IActivityManager am = ActivityManagerNative.getDefault(); 11627 if (am != null) { 11628 try { 11629 am.startService(null, intent, null, mContext.getOpPackageName(), 11630 UserHandle.USER_SYSTEM); 11631 } catch (RemoteException e) { 11632 } 11633 } 11634 } 11635 11636 @Override 11637 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11638 int installFlags, String installerPackageName, int userId) { 11639 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11640 11641 final int callingUid = Binder.getCallingUid(); 11642 enforceCrossUserPermission(callingUid, userId, 11643 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11644 11645 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11646 try { 11647 if (observer != null) { 11648 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11649 } 11650 } catch (RemoteException re) { 11651 } 11652 return; 11653 } 11654 11655 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11656 installFlags |= PackageManager.INSTALL_FROM_ADB; 11657 11658 } else { 11659 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11660 // about installerPackageName. 11661 11662 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11663 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11664 } 11665 11666 UserHandle user; 11667 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11668 user = UserHandle.ALL; 11669 } else { 11670 user = new UserHandle(userId); 11671 } 11672 11673 // Only system components can circumvent runtime permissions when installing. 11674 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11675 && mContext.checkCallingOrSelfPermission(Manifest.permission 11676 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11677 throw new SecurityException("You need the " 11678 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11679 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11680 } 11681 11682 final File originFile = new File(originPath); 11683 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11684 11685 final Message msg = mHandler.obtainMessage(INIT_COPY); 11686 final VerificationInfo verificationInfo = new VerificationInfo( 11687 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11688 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11689 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11690 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11691 null /*certificates*/); 11692 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11693 msg.obj = params; 11694 11695 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11696 System.identityHashCode(msg.obj)); 11697 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11698 System.identityHashCode(msg.obj)); 11699 11700 mHandler.sendMessage(msg); 11701 } 11702 11703 void installStage(String packageName, File stagedDir, String stagedCid, 11704 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11705 String installerPackageName, int installerUid, UserHandle user, 11706 Certificate[][] certificates) { 11707 if (DEBUG_EPHEMERAL) { 11708 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11709 Slog.d(TAG, "Ephemeral install of " + packageName); 11710 } 11711 } 11712 final VerificationInfo verificationInfo = new VerificationInfo( 11713 sessionParams.originatingUri, sessionParams.referrerUri, 11714 sessionParams.originatingUid, installerUid); 11715 11716 final OriginInfo origin; 11717 if (stagedDir != null) { 11718 origin = OriginInfo.fromStagedFile(stagedDir); 11719 } else { 11720 origin = OriginInfo.fromStagedContainer(stagedCid); 11721 } 11722 11723 final Message msg = mHandler.obtainMessage(INIT_COPY); 11724 final InstallParams params = new InstallParams(origin, null, observer, 11725 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11726 verificationInfo, user, sessionParams.abiOverride, 11727 sessionParams.grantedRuntimePermissions, certificates); 11728 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11729 msg.obj = params; 11730 11731 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11732 System.identityHashCode(msg.obj)); 11733 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11734 System.identityHashCode(msg.obj)); 11735 11736 mHandler.sendMessage(msg); 11737 } 11738 11739 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11740 int userId) { 11741 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11742 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11743 } 11744 11745 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11746 int appId, int userId) { 11747 Bundle extras = new Bundle(1); 11748 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11749 11750 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11751 packageName, extras, 0, null, null, new int[] {userId}); 11752 try { 11753 IActivityManager am = ActivityManagerNative.getDefault(); 11754 if (isSystem && am.isUserRunning(userId, 0)) { 11755 // The just-installed/enabled app is bundled on the system, so presumed 11756 // to be able to run automatically without needing an explicit launch. 11757 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11758 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11759 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11760 .setPackage(packageName); 11761 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11762 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11763 } 11764 } catch (RemoteException e) { 11765 // shouldn't happen 11766 Slog.w(TAG, "Unable to bootstrap installed package", e); 11767 } 11768 } 11769 11770 @Override 11771 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11772 int userId) { 11773 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11774 PackageSetting pkgSetting; 11775 final int uid = Binder.getCallingUid(); 11776 enforceCrossUserPermission(uid, userId, 11777 true /* requireFullPermission */, true /* checkShell */, 11778 "setApplicationHiddenSetting for user " + userId); 11779 11780 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11781 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11782 return false; 11783 } 11784 11785 long callingId = Binder.clearCallingIdentity(); 11786 try { 11787 boolean sendAdded = false; 11788 boolean sendRemoved = false; 11789 // writer 11790 synchronized (mPackages) { 11791 pkgSetting = mSettings.mPackages.get(packageName); 11792 if (pkgSetting == null) { 11793 return false; 11794 } 11795 // Do not allow "android" is being disabled 11796 if ("android".equals(packageName)) { 11797 Slog.w(TAG, "Cannot hide package: android"); 11798 return false; 11799 } 11800 // Only allow protected packages to hide themselves. 11801 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11802 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11803 Slog.w(TAG, "Not hiding protected package: " + packageName); 11804 return false; 11805 } 11806 11807 if (pkgSetting.getHidden(userId) != hidden) { 11808 pkgSetting.setHidden(hidden, userId); 11809 mSettings.writePackageRestrictionsLPr(userId); 11810 if (hidden) { 11811 sendRemoved = true; 11812 } else { 11813 sendAdded = true; 11814 } 11815 } 11816 } 11817 if (sendAdded) { 11818 sendPackageAddedForUser(packageName, pkgSetting, userId); 11819 return true; 11820 } 11821 if (sendRemoved) { 11822 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11823 "hiding pkg"); 11824 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11825 return true; 11826 } 11827 } finally { 11828 Binder.restoreCallingIdentity(callingId); 11829 } 11830 return false; 11831 } 11832 11833 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11834 int userId) { 11835 final PackageRemovedInfo info = new PackageRemovedInfo(); 11836 info.removedPackage = packageName; 11837 info.removedUsers = new int[] {userId}; 11838 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11839 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11840 } 11841 11842 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11843 if (pkgList.length > 0) { 11844 Bundle extras = new Bundle(1); 11845 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11846 11847 sendPackageBroadcast( 11848 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11849 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11850 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11851 new int[] {userId}); 11852 } 11853 } 11854 11855 /** 11856 * Returns true if application is not found or there was an error. Otherwise it returns 11857 * the hidden state of the package for the given user. 11858 */ 11859 @Override 11860 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11861 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11862 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11863 true /* requireFullPermission */, false /* checkShell */, 11864 "getApplicationHidden for user " + userId); 11865 PackageSetting pkgSetting; 11866 long callingId = Binder.clearCallingIdentity(); 11867 try { 11868 // writer 11869 synchronized (mPackages) { 11870 pkgSetting = mSettings.mPackages.get(packageName); 11871 if (pkgSetting == null) { 11872 return true; 11873 } 11874 return pkgSetting.getHidden(userId); 11875 } 11876 } finally { 11877 Binder.restoreCallingIdentity(callingId); 11878 } 11879 } 11880 11881 /** 11882 * @hide 11883 */ 11884 @Override 11885 public int installExistingPackageAsUser(String packageName, int userId) { 11886 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11887 null); 11888 PackageSetting pkgSetting; 11889 final int uid = Binder.getCallingUid(); 11890 enforceCrossUserPermission(uid, userId, 11891 true /* requireFullPermission */, true /* checkShell */, 11892 "installExistingPackage for user " + userId); 11893 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11894 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11895 } 11896 11897 long callingId = Binder.clearCallingIdentity(); 11898 try { 11899 boolean installed = false; 11900 11901 // writer 11902 synchronized (mPackages) { 11903 pkgSetting = mSettings.mPackages.get(packageName); 11904 if (pkgSetting == null) { 11905 return PackageManager.INSTALL_FAILED_INVALID_URI; 11906 } 11907 if (!pkgSetting.getInstalled(userId)) { 11908 pkgSetting.setInstalled(true, userId); 11909 pkgSetting.setHidden(false, userId); 11910 mSettings.writePackageRestrictionsLPr(userId); 11911 installed = true; 11912 } 11913 } 11914 11915 if (installed) { 11916 if (pkgSetting.pkg != null) { 11917 synchronized (mInstallLock) { 11918 // We don't need to freeze for a brand new install 11919 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11920 } 11921 } 11922 sendPackageAddedForUser(packageName, pkgSetting, userId); 11923 } 11924 } finally { 11925 Binder.restoreCallingIdentity(callingId); 11926 } 11927 11928 return PackageManager.INSTALL_SUCCEEDED; 11929 } 11930 11931 boolean isUserRestricted(int userId, String restrictionKey) { 11932 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11933 if (restrictions.getBoolean(restrictionKey, false)) { 11934 Log.w(TAG, "User is restricted: " + restrictionKey); 11935 return true; 11936 } 11937 return false; 11938 } 11939 11940 @Override 11941 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11942 int userId) { 11943 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11944 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11945 true /* requireFullPermission */, true /* checkShell */, 11946 "setPackagesSuspended for user " + userId); 11947 11948 if (ArrayUtils.isEmpty(packageNames)) { 11949 return packageNames; 11950 } 11951 11952 // List of package names for whom the suspended state has changed. 11953 List<String> changedPackages = new ArrayList<>(packageNames.length); 11954 // List of package names for whom the suspended state is not set as requested in this 11955 // method. 11956 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11957 long callingId = Binder.clearCallingIdentity(); 11958 try { 11959 for (int i = 0; i < packageNames.length; i++) { 11960 String packageName = packageNames[i]; 11961 boolean changed = false; 11962 final int appId; 11963 synchronized (mPackages) { 11964 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11965 if (pkgSetting == null) { 11966 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11967 + "\". Skipping suspending/un-suspending."); 11968 unactionedPackages.add(packageName); 11969 continue; 11970 } 11971 appId = pkgSetting.appId; 11972 if (pkgSetting.getSuspended(userId) != suspended) { 11973 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11974 unactionedPackages.add(packageName); 11975 continue; 11976 } 11977 pkgSetting.setSuspended(suspended, userId); 11978 mSettings.writePackageRestrictionsLPr(userId); 11979 changed = true; 11980 changedPackages.add(packageName); 11981 } 11982 } 11983 11984 if (changed && suspended) { 11985 killApplication(packageName, UserHandle.getUid(userId, appId), 11986 "suspending package"); 11987 } 11988 } 11989 } finally { 11990 Binder.restoreCallingIdentity(callingId); 11991 } 11992 11993 if (!changedPackages.isEmpty()) { 11994 sendPackagesSuspendedForUser(changedPackages.toArray( 11995 new String[changedPackages.size()]), userId, suspended); 11996 } 11997 11998 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11999 } 12000 12001 @Override 12002 public boolean isPackageSuspendedForUser(String packageName, int userId) { 12003 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12004 true /* requireFullPermission */, false /* checkShell */, 12005 "isPackageSuspendedForUser for user " + userId); 12006 synchronized (mPackages) { 12007 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12008 if (pkgSetting == null) { 12009 throw new IllegalArgumentException("Unknown target package: " + packageName); 12010 } 12011 return pkgSetting.getSuspended(userId); 12012 } 12013 } 12014 12015 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 12016 if (isPackageDeviceAdmin(packageName, userId)) { 12017 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12018 + "\": has an active device admin"); 12019 return false; 12020 } 12021 12022 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 12023 if (packageName.equals(activeLauncherPackageName)) { 12024 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12025 + "\": contains the active launcher"); 12026 return false; 12027 } 12028 12029 if (packageName.equals(mRequiredInstallerPackage)) { 12030 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12031 + "\": required for package installation"); 12032 return false; 12033 } 12034 12035 if (packageName.equals(mRequiredUninstallerPackage)) { 12036 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12037 + "\": required for package uninstallation"); 12038 return false; 12039 } 12040 12041 if (packageName.equals(mRequiredVerifierPackage)) { 12042 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12043 + "\": required for package verification"); 12044 return false; 12045 } 12046 12047 if (packageName.equals(getDefaultDialerPackageName(userId))) { 12048 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12049 + "\": is the default dialer"); 12050 return false; 12051 } 12052 12053 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12054 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12055 + "\": protected package"); 12056 return false; 12057 } 12058 12059 return true; 12060 } 12061 12062 private String getActiveLauncherPackageName(int userId) { 12063 Intent intent = new Intent(Intent.ACTION_MAIN); 12064 intent.addCategory(Intent.CATEGORY_HOME); 12065 ResolveInfo resolveInfo = resolveIntent( 12066 intent, 12067 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 12068 PackageManager.MATCH_DEFAULT_ONLY, 12069 userId); 12070 12071 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 12072 } 12073 12074 private String getDefaultDialerPackageName(int userId) { 12075 synchronized (mPackages) { 12076 return mSettings.getDefaultDialerPackageNameLPw(userId); 12077 } 12078 } 12079 12080 @Override 12081 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 12082 mContext.enforceCallingOrSelfPermission( 12083 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12084 "Only package verification agents can verify applications"); 12085 12086 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12087 final PackageVerificationResponse response = new PackageVerificationResponse( 12088 verificationCode, Binder.getCallingUid()); 12089 msg.arg1 = id; 12090 msg.obj = response; 12091 mHandler.sendMessage(msg); 12092 } 12093 12094 @Override 12095 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12096 long millisecondsToDelay) { 12097 mContext.enforceCallingOrSelfPermission( 12098 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12099 "Only package verification agents can extend verification timeouts"); 12100 12101 final PackageVerificationState state = mPendingVerification.get(id); 12102 final PackageVerificationResponse response = new PackageVerificationResponse( 12103 verificationCodeAtTimeout, Binder.getCallingUid()); 12104 12105 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12106 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12107 } 12108 if (millisecondsToDelay < 0) { 12109 millisecondsToDelay = 0; 12110 } 12111 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12112 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12113 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12114 } 12115 12116 if ((state != null) && !state.timeoutExtended()) { 12117 state.extendTimeout(); 12118 12119 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12120 msg.arg1 = id; 12121 msg.obj = response; 12122 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12123 } 12124 } 12125 12126 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12127 int verificationCode, UserHandle user) { 12128 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12129 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12130 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12131 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12132 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12133 12134 mContext.sendBroadcastAsUser(intent, user, 12135 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12136 } 12137 12138 private ComponentName matchComponentForVerifier(String packageName, 12139 List<ResolveInfo> receivers) { 12140 ActivityInfo targetReceiver = null; 12141 12142 final int NR = receivers.size(); 12143 for (int i = 0; i < NR; i++) { 12144 final ResolveInfo info = receivers.get(i); 12145 if (info.activityInfo == null) { 12146 continue; 12147 } 12148 12149 if (packageName.equals(info.activityInfo.packageName)) { 12150 targetReceiver = info.activityInfo; 12151 break; 12152 } 12153 } 12154 12155 if (targetReceiver == null) { 12156 return null; 12157 } 12158 12159 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12160 } 12161 12162 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12163 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12164 if (pkgInfo.verifiers.length == 0) { 12165 return null; 12166 } 12167 12168 final int N = pkgInfo.verifiers.length; 12169 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12170 for (int i = 0; i < N; i++) { 12171 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12172 12173 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12174 receivers); 12175 if (comp == null) { 12176 continue; 12177 } 12178 12179 final int verifierUid = getUidForVerifier(verifierInfo); 12180 if (verifierUid == -1) { 12181 continue; 12182 } 12183 12184 if (DEBUG_VERIFY) { 12185 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12186 + " with the correct signature"); 12187 } 12188 sufficientVerifiers.add(comp); 12189 verificationState.addSufficientVerifier(verifierUid); 12190 } 12191 12192 return sufficientVerifiers; 12193 } 12194 12195 private int getUidForVerifier(VerifierInfo verifierInfo) { 12196 synchronized (mPackages) { 12197 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12198 if (pkg == null) { 12199 return -1; 12200 } else if (pkg.mSignatures.length != 1) { 12201 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12202 + " has more than one signature; ignoring"); 12203 return -1; 12204 } 12205 12206 /* 12207 * If the public key of the package's signature does not match 12208 * our expected public key, then this is a different package and 12209 * we should skip. 12210 */ 12211 12212 final byte[] expectedPublicKey; 12213 try { 12214 final Signature verifierSig = pkg.mSignatures[0]; 12215 final PublicKey publicKey = verifierSig.getPublicKey(); 12216 expectedPublicKey = publicKey.getEncoded(); 12217 } catch (CertificateException e) { 12218 return -1; 12219 } 12220 12221 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12222 12223 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12224 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12225 + " does not have the expected public key; ignoring"); 12226 return -1; 12227 } 12228 12229 return pkg.applicationInfo.uid; 12230 } 12231 } 12232 12233 @Override 12234 public void finishPackageInstall(int token, boolean didLaunch) { 12235 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12236 12237 if (DEBUG_INSTALL) { 12238 Slog.v(TAG, "BM finishing package install for " + token); 12239 } 12240 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12241 12242 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12243 mHandler.sendMessage(msg); 12244 } 12245 12246 /** 12247 * Get the verification agent timeout. 12248 * 12249 * @return verification timeout in milliseconds 12250 */ 12251 private long getVerificationTimeout() { 12252 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12253 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12254 DEFAULT_VERIFICATION_TIMEOUT); 12255 } 12256 12257 /** 12258 * Get the default verification agent response code. 12259 * 12260 * @return default verification response code 12261 */ 12262 private int getDefaultVerificationResponse() { 12263 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12264 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12265 DEFAULT_VERIFICATION_RESPONSE); 12266 } 12267 12268 /** 12269 * Check whether or not package verification has been enabled. 12270 * 12271 * @return true if verification should be performed 12272 */ 12273 private boolean isVerificationEnabled(int userId, int installFlags) { 12274 if (!DEFAULT_VERIFY_ENABLE) { 12275 return false; 12276 } 12277 // Ephemeral apps don't get the full verification treatment 12278 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12279 if (DEBUG_EPHEMERAL) { 12280 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12281 } 12282 return false; 12283 } 12284 12285 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12286 12287 // Check if installing from ADB 12288 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12289 // Do not run verification in a test harness environment 12290 if (ActivityManager.isRunningInTestHarness()) { 12291 return false; 12292 } 12293 if (ensureVerifyAppsEnabled) { 12294 return true; 12295 } 12296 // Check if the developer does not want package verification for ADB installs 12297 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12298 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12299 return false; 12300 } 12301 } 12302 12303 if (ensureVerifyAppsEnabled) { 12304 return true; 12305 } 12306 12307 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12308 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12309 } 12310 12311 @Override 12312 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12313 throws RemoteException { 12314 mContext.enforceCallingOrSelfPermission( 12315 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12316 "Only intentfilter verification agents can verify applications"); 12317 12318 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12319 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12320 Binder.getCallingUid(), verificationCode, failedDomains); 12321 msg.arg1 = id; 12322 msg.obj = response; 12323 mHandler.sendMessage(msg); 12324 } 12325 12326 @Override 12327 public int getIntentVerificationStatus(String packageName, int userId) { 12328 synchronized (mPackages) { 12329 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12330 } 12331 } 12332 12333 @Override 12334 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12335 mContext.enforceCallingOrSelfPermission( 12336 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12337 12338 boolean result = false; 12339 synchronized (mPackages) { 12340 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12341 } 12342 if (result) { 12343 scheduleWritePackageRestrictionsLocked(userId); 12344 } 12345 return result; 12346 } 12347 12348 @Override 12349 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12350 String packageName) { 12351 synchronized (mPackages) { 12352 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12353 } 12354 } 12355 12356 @Override 12357 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12358 if (TextUtils.isEmpty(packageName)) { 12359 return ParceledListSlice.emptyList(); 12360 } 12361 synchronized (mPackages) { 12362 PackageParser.Package pkg = mPackages.get(packageName); 12363 if (pkg == null || pkg.activities == null) { 12364 return ParceledListSlice.emptyList(); 12365 } 12366 final int count = pkg.activities.size(); 12367 ArrayList<IntentFilter> result = new ArrayList<>(); 12368 for (int n=0; n<count; n++) { 12369 PackageParser.Activity activity = pkg.activities.get(n); 12370 if (activity.intents != null && activity.intents.size() > 0) { 12371 result.addAll(activity.intents); 12372 } 12373 } 12374 return new ParceledListSlice<>(result); 12375 } 12376 } 12377 12378 @Override 12379 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12380 mContext.enforceCallingOrSelfPermission( 12381 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12382 12383 synchronized (mPackages) { 12384 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12385 if (packageName != null) { 12386 result |= updateIntentVerificationStatus(packageName, 12387 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12388 userId); 12389 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12390 packageName, userId); 12391 } 12392 return result; 12393 } 12394 } 12395 12396 @Override 12397 public String getDefaultBrowserPackageName(int userId) { 12398 synchronized (mPackages) { 12399 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12400 } 12401 } 12402 12403 /** 12404 * Get the "allow unknown sources" setting. 12405 * 12406 * @return the current "allow unknown sources" setting 12407 */ 12408 private int getUnknownSourcesSettings() { 12409 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12410 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12411 -1); 12412 } 12413 12414 @Override 12415 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12416 final int uid = Binder.getCallingUid(); 12417 // writer 12418 synchronized (mPackages) { 12419 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12420 if (targetPackageSetting == null) { 12421 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12422 } 12423 12424 PackageSetting installerPackageSetting; 12425 if (installerPackageName != null) { 12426 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12427 if (installerPackageSetting == null) { 12428 throw new IllegalArgumentException("Unknown installer package: " 12429 + installerPackageName); 12430 } 12431 } else { 12432 installerPackageSetting = null; 12433 } 12434 12435 Signature[] callerSignature; 12436 Object obj = mSettings.getUserIdLPr(uid); 12437 if (obj != null) { 12438 if (obj instanceof SharedUserSetting) { 12439 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12440 } else if (obj instanceof PackageSetting) { 12441 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12442 } else { 12443 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12444 } 12445 } else { 12446 throw new SecurityException("Unknown calling UID: " + uid); 12447 } 12448 12449 // Verify: can't set installerPackageName to a package that is 12450 // not signed with the same cert as the caller. 12451 if (installerPackageSetting != null) { 12452 if (compareSignatures(callerSignature, 12453 installerPackageSetting.signatures.mSignatures) 12454 != PackageManager.SIGNATURE_MATCH) { 12455 throw new SecurityException( 12456 "Caller does not have same cert as new installer package " 12457 + installerPackageName); 12458 } 12459 } 12460 12461 // Verify: if target already has an installer package, it must 12462 // be signed with the same cert as the caller. 12463 if (targetPackageSetting.installerPackageName != null) { 12464 PackageSetting setting = mSettings.mPackages.get( 12465 targetPackageSetting.installerPackageName); 12466 // If the currently set package isn't valid, then it's always 12467 // okay to change it. 12468 if (setting != null) { 12469 if (compareSignatures(callerSignature, 12470 setting.signatures.mSignatures) 12471 != PackageManager.SIGNATURE_MATCH) { 12472 throw new SecurityException( 12473 "Caller does not have same cert as old installer package " 12474 + targetPackageSetting.installerPackageName); 12475 } 12476 } 12477 } 12478 12479 // Okay! 12480 targetPackageSetting.installerPackageName = installerPackageName; 12481 if (installerPackageName != null) { 12482 mSettings.mInstallerPackages.add(installerPackageName); 12483 } 12484 scheduleWriteSettingsLocked(); 12485 } 12486 } 12487 12488 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12489 // Queue up an async operation since the package installation may take a little while. 12490 mHandler.post(new Runnable() { 12491 public void run() { 12492 mHandler.removeCallbacks(this); 12493 // Result object to be returned 12494 PackageInstalledInfo res = new PackageInstalledInfo(); 12495 res.setReturnCode(currentStatus); 12496 res.uid = -1; 12497 res.pkg = null; 12498 res.removedInfo = null; 12499 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12500 args.doPreInstall(res.returnCode); 12501 synchronized (mInstallLock) { 12502 installPackageTracedLI(args, res); 12503 } 12504 args.doPostInstall(res.returnCode, res.uid); 12505 } 12506 12507 // A restore should be performed at this point if (a) the install 12508 // succeeded, (b) the operation is not an update, and (c) the new 12509 // package has not opted out of backup participation. 12510 final boolean update = res.removedInfo != null 12511 && res.removedInfo.removedPackage != null; 12512 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12513 boolean doRestore = !update 12514 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12515 12516 // Set up the post-install work request bookkeeping. This will be used 12517 // and cleaned up by the post-install event handling regardless of whether 12518 // there's a restore pass performed. Token values are >= 1. 12519 int token; 12520 if (mNextInstallToken < 0) mNextInstallToken = 1; 12521 token = mNextInstallToken++; 12522 12523 PostInstallData data = new PostInstallData(args, res); 12524 mRunningInstalls.put(token, data); 12525 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12526 12527 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12528 // Pass responsibility to the Backup Manager. It will perform a 12529 // restore if appropriate, then pass responsibility back to the 12530 // Package Manager to run the post-install observer callbacks 12531 // and broadcasts. 12532 IBackupManager bm = IBackupManager.Stub.asInterface( 12533 ServiceManager.getService(Context.BACKUP_SERVICE)); 12534 if (bm != null) { 12535 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12536 + " to BM for possible restore"); 12537 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12538 try { 12539 // TODO: http://b/22388012 12540 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12541 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12542 } else { 12543 doRestore = false; 12544 } 12545 } catch (RemoteException e) { 12546 // can't happen; the backup manager is local 12547 } catch (Exception e) { 12548 Slog.e(TAG, "Exception trying to enqueue restore", e); 12549 doRestore = false; 12550 } 12551 } else { 12552 Slog.e(TAG, "Backup Manager not found!"); 12553 doRestore = false; 12554 } 12555 } 12556 12557 if (!doRestore) { 12558 // No restore possible, or the Backup Manager was mysteriously not 12559 // available -- just fire the post-install work request directly. 12560 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12561 12562 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12563 12564 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12565 mHandler.sendMessage(msg); 12566 } 12567 } 12568 }); 12569 } 12570 12571 /** 12572 * Callback from PackageSettings whenever an app is first transitioned out of the 12573 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12574 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12575 * here whether the app is the target of an ongoing install, and only send the 12576 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12577 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12578 * handling. 12579 */ 12580 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12581 // Serialize this with the rest of the install-process message chain. In the 12582 // restore-at-install case, this Runnable will necessarily run before the 12583 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12584 // are coherent. In the non-restore case, the app has already completed install 12585 // and been launched through some other means, so it is not in a problematic 12586 // state for observers to see the FIRST_LAUNCH signal. 12587 mHandler.post(new Runnable() { 12588 @Override 12589 public void run() { 12590 for (int i = 0; i < mRunningInstalls.size(); i++) { 12591 final PostInstallData data = mRunningInstalls.valueAt(i); 12592 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12593 continue; 12594 } 12595 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12596 // right package; but is it for the right user? 12597 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12598 if (userId == data.res.newUsers[uIndex]) { 12599 if (DEBUG_BACKUP) { 12600 Slog.i(TAG, "Package " + pkgName 12601 + " being restored so deferring FIRST_LAUNCH"); 12602 } 12603 return; 12604 } 12605 } 12606 } 12607 } 12608 // didn't find it, so not being restored 12609 if (DEBUG_BACKUP) { 12610 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12611 } 12612 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12613 } 12614 }); 12615 } 12616 12617 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12618 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12619 installerPkg, null, userIds); 12620 } 12621 12622 private abstract class HandlerParams { 12623 private static final int MAX_RETRIES = 4; 12624 12625 /** 12626 * Number of times startCopy() has been attempted and had a non-fatal 12627 * error. 12628 */ 12629 private int mRetries = 0; 12630 12631 /** User handle for the user requesting the information or installation. */ 12632 private final UserHandle mUser; 12633 String traceMethod; 12634 int traceCookie; 12635 12636 HandlerParams(UserHandle user) { 12637 mUser = user; 12638 } 12639 12640 UserHandle getUser() { 12641 return mUser; 12642 } 12643 12644 HandlerParams setTraceMethod(String traceMethod) { 12645 this.traceMethod = traceMethod; 12646 return this; 12647 } 12648 12649 HandlerParams setTraceCookie(int traceCookie) { 12650 this.traceCookie = traceCookie; 12651 return this; 12652 } 12653 12654 final boolean startCopy() { 12655 boolean res; 12656 try { 12657 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12658 12659 if (++mRetries > MAX_RETRIES) { 12660 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12661 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12662 handleServiceError(); 12663 return false; 12664 } else { 12665 handleStartCopy(); 12666 res = true; 12667 } 12668 } catch (RemoteException e) { 12669 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12670 mHandler.sendEmptyMessage(MCS_RECONNECT); 12671 res = false; 12672 } 12673 handleReturnCode(); 12674 return res; 12675 } 12676 12677 final void serviceError() { 12678 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12679 handleServiceError(); 12680 handleReturnCode(); 12681 } 12682 12683 abstract void handleStartCopy() throws RemoteException; 12684 abstract void handleServiceError(); 12685 abstract void handleReturnCode(); 12686 } 12687 12688 class MeasureParams extends HandlerParams { 12689 private final PackageStats mStats; 12690 private boolean mSuccess; 12691 12692 private final IPackageStatsObserver mObserver; 12693 12694 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12695 super(new UserHandle(stats.userHandle)); 12696 mObserver = observer; 12697 mStats = stats; 12698 } 12699 12700 @Override 12701 public String toString() { 12702 return "MeasureParams{" 12703 + Integer.toHexString(System.identityHashCode(this)) 12704 + " " + mStats.packageName + "}"; 12705 } 12706 12707 @Override 12708 void handleStartCopy() throws RemoteException { 12709 synchronized (mInstallLock) { 12710 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12711 } 12712 12713 if (mSuccess) { 12714 boolean mounted = false; 12715 try { 12716 final String status = Environment.getExternalStorageState(); 12717 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12718 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12719 } catch (Exception e) { 12720 } 12721 12722 if (mounted) { 12723 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12724 12725 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12726 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12727 12728 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12729 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12730 12731 // Always subtract cache size, since it's a subdirectory 12732 mStats.externalDataSize -= mStats.externalCacheSize; 12733 12734 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12735 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12736 12737 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12738 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12739 } 12740 } 12741 } 12742 12743 @Override 12744 void handleReturnCode() { 12745 if (mObserver != null) { 12746 try { 12747 mObserver.onGetStatsCompleted(mStats, mSuccess); 12748 } catch (RemoteException e) { 12749 Slog.i(TAG, "Observer no longer exists."); 12750 } 12751 } 12752 } 12753 12754 @Override 12755 void handleServiceError() { 12756 Slog.e(TAG, "Could not measure application " + mStats.packageName 12757 + " external storage"); 12758 } 12759 } 12760 12761 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12762 throws RemoteException { 12763 long result = 0; 12764 for (File path : paths) { 12765 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12766 } 12767 return result; 12768 } 12769 12770 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12771 for (File path : paths) { 12772 try { 12773 mcs.clearDirectory(path.getAbsolutePath()); 12774 } catch (RemoteException e) { 12775 } 12776 } 12777 } 12778 12779 static class OriginInfo { 12780 /** 12781 * Location where install is coming from, before it has been 12782 * copied/renamed into place. This could be a single monolithic APK 12783 * file, or a cluster directory. This location may be untrusted. 12784 */ 12785 final File file; 12786 final String cid; 12787 12788 /** 12789 * Flag indicating that {@link #file} or {@link #cid} has already been 12790 * staged, meaning downstream users don't need to defensively copy the 12791 * contents. 12792 */ 12793 final boolean staged; 12794 12795 /** 12796 * Flag indicating that {@link #file} or {@link #cid} is an already 12797 * installed app that is being moved. 12798 */ 12799 final boolean existing; 12800 12801 final String resolvedPath; 12802 final File resolvedFile; 12803 12804 static OriginInfo fromNothing() { 12805 return new OriginInfo(null, null, false, false); 12806 } 12807 12808 static OriginInfo fromUntrustedFile(File file) { 12809 return new OriginInfo(file, null, false, false); 12810 } 12811 12812 static OriginInfo fromExistingFile(File file) { 12813 return new OriginInfo(file, null, false, true); 12814 } 12815 12816 static OriginInfo fromStagedFile(File file) { 12817 return new OriginInfo(file, null, true, false); 12818 } 12819 12820 static OriginInfo fromStagedContainer(String cid) { 12821 return new OriginInfo(null, cid, true, false); 12822 } 12823 12824 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12825 this.file = file; 12826 this.cid = cid; 12827 this.staged = staged; 12828 this.existing = existing; 12829 12830 if (cid != null) { 12831 resolvedPath = PackageHelper.getSdDir(cid); 12832 resolvedFile = new File(resolvedPath); 12833 } else if (file != null) { 12834 resolvedPath = file.getAbsolutePath(); 12835 resolvedFile = file; 12836 } else { 12837 resolvedPath = null; 12838 resolvedFile = null; 12839 } 12840 } 12841 } 12842 12843 static class MoveInfo { 12844 final int moveId; 12845 final String fromUuid; 12846 final String toUuid; 12847 final String packageName; 12848 final String dataAppName; 12849 final int appId; 12850 final String seinfo; 12851 final int targetSdkVersion; 12852 12853 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12854 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12855 this.moveId = moveId; 12856 this.fromUuid = fromUuid; 12857 this.toUuid = toUuid; 12858 this.packageName = packageName; 12859 this.dataAppName = dataAppName; 12860 this.appId = appId; 12861 this.seinfo = seinfo; 12862 this.targetSdkVersion = targetSdkVersion; 12863 } 12864 } 12865 12866 static class VerificationInfo { 12867 /** A constant used to indicate that a uid value is not present. */ 12868 public static final int NO_UID = -1; 12869 12870 /** URI referencing where the package was downloaded from. */ 12871 final Uri originatingUri; 12872 12873 /** HTTP referrer URI associated with the originatingURI. */ 12874 final Uri referrer; 12875 12876 /** UID of the application that the install request originated from. */ 12877 final int originatingUid; 12878 12879 /** UID of application requesting the install */ 12880 final int installerUid; 12881 12882 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12883 this.originatingUri = originatingUri; 12884 this.referrer = referrer; 12885 this.originatingUid = originatingUid; 12886 this.installerUid = installerUid; 12887 } 12888 } 12889 12890 class InstallParams extends HandlerParams { 12891 final OriginInfo origin; 12892 final MoveInfo move; 12893 final IPackageInstallObserver2 observer; 12894 int installFlags; 12895 final String installerPackageName; 12896 final String volumeUuid; 12897 private InstallArgs mArgs; 12898 private int mRet; 12899 final String packageAbiOverride; 12900 final String[] grantedRuntimePermissions; 12901 final VerificationInfo verificationInfo; 12902 final Certificate[][] certificates; 12903 12904 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12905 int installFlags, String installerPackageName, String volumeUuid, 12906 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12907 String[] grantedPermissions, Certificate[][] certificates) { 12908 super(user); 12909 this.origin = origin; 12910 this.move = move; 12911 this.observer = observer; 12912 this.installFlags = installFlags; 12913 this.installerPackageName = installerPackageName; 12914 this.volumeUuid = volumeUuid; 12915 this.verificationInfo = verificationInfo; 12916 this.packageAbiOverride = packageAbiOverride; 12917 this.grantedRuntimePermissions = grantedPermissions; 12918 this.certificates = certificates; 12919 } 12920 12921 @Override 12922 public String toString() { 12923 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12924 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12925 } 12926 12927 private int installLocationPolicy(PackageInfoLite pkgLite) { 12928 String packageName = pkgLite.packageName; 12929 int installLocation = pkgLite.installLocation; 12930 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12931 // reader 12932 synchronized (mPackages) { 12933 // Currently installed package which the new package is attempting to replace or 12934 // null if no such package is installed. 12935 PackageParser.Package installedPkg = mPackages.get(packageName); 12936 // Package which currently owns the data which the new package will own if installed. 12937 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12938 // will be null whereas dataOwnerPkg will contain information about the package 12939 // which was uninstalled while keeping its data. 12940 PackageParser.Package dataOwnerPkg = installedPkg; 12941 if (dataOwnerPkg == null) { 12942 PackageSetting ps = mSettings.mPackages.get(packageName); 12943 if (ps != null) { 12944 dataOwnerPkg = ps.pkg; 12945 } 12946 } 12947 12948 if (dataOwnerPkg != null) { 12949 // If installed, the package will get access to data left on the device by its 12950 // predecessor. As a security measure, this is permited only if this is not a 12951 // version downgrade or if the predecessor package is marked as debuggable and 12952 // a downgrade is explicitly requested. 12953 // 12954 // On debuggable platform builds, downgrades are permitted even for 12955 // non-debuggable packages to make testing easier. Debuggable platform builds do 12956 // not offer security guarantees and thus it's OK to disable some security 12957 // mechanisms to make debugging/testing easier on those builds. However, even on 12958 // debuggable builds downgrades of packages are permitted only if requested via 12959 // installFlags. This is because we aim to keep the behavior of debuggable 12960 // platform builds as close as possible to the behavior of non-debuggable 12961 // platform builds. 12962 final boolean downgradeRequested = 12963 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12964 final boolean packageDebuggable = 12965 (dataOwnerPkg.applicationInfo.flags 12966 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12967 final boolean downgradePermitted = 12968 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12969 if (!downgradePermitted) { 12970 try { 12971 checkDowngrade(dataOwnerPkg, pkgLite); 12972 } catch (PackageManagerException e) { 12973 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12974 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12975 } 12976 } 12977 } 12978 12979 if (installedPkg != null) { 12980 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12981 // Check for updated system application. 12982 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12983 if (onSd) { 12984 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12985 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12986 } 12987 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12988 } else { 12989 if (onSd) { 12990 // Install flag overrides everything. 12991 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12992 } 12993 // If current upgrade specifies particular preference 12994 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12995 // Application explicitly specified internal. 12996 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12997 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12998 // App explictly prefers external. Let policy decide 12999 } else { 13000 // Prefer previous location 13001 if (isExternal(installedPkg)) { 13002 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13003 } 13004 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13005 } 13006 } 13007 } else { 13008 // Invalid install. Return error code 13009 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 13010 } 13011 } 13012 } 13013 // All the special cases have been taken care of. 13014 // Return result based on recommended install location. 13015 if (onSd) { 13016 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13017 } 13018 return pkgLite.recommendedInstallLocation; 13019 } 13020 13021 /* 13022 * Invoke remote method to get package information and install 13023 * location values. Override install location based on default 13024 * policy if needed and then create install arguments based 13025 * on the install location. 13026 */ 13027 public void handleStartCopy() throws RemoteException { 13028 int ret = PackageManager.INSTALL_SUCCEEDED; 13029 13030 // If we're already staged, we've firmly committed to an install location 13031 if (origin.staged) { 13032 if (origin.file != null) { 13033 installFlags |= PackageManager.INSTALL_INTERNAL; 13034 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13035 } else if (origin.cid != null) { 13036 installFlags |= PackageManager.INSTALL_EXTERNAL; 13037 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13038 } else { 13039 throw new IllegalStateException("Invalid stage location"); 13040 } 13041 } 13042 13043 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13044 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 13045 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13046 PackageInfoLite pkgLite = null; 13047 13048 if (onInt && onSd) { 13049 // Check if both bits are set. 13050 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 13051 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13052 } else if (onSd && ephemeral) { 13053 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 13054 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13055 } else { 13056 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 13057 packageAbiOverride); 13058 13059 if (DEBUG_EPHEMERAL && ephemeral) { 13060 Slog.v(TAG, "pkgLite for install: " + pkgLite); 13061 } 13062 13063 /* 13064 * If we have too little free space, try to free cache 13065 * before giving up. 13066 */ 13067 if (!origin.staged && pkgLite.recommendedInstallLocation 13068 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13069 // TODO: focus freeing disk space on the target device 13070 final StorageManager storage = StorageManager.from(mContext); 13071 final long lowThreshold = storage.getStorageLowBytes( 13072 Environment.getDataDirectory()); 13073 13074 final long sizeBytes = mContainerService.calculateInstalledSize( 13075 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 13076 13077 try { 13078 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 13079 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 13080 installFlags, packageAbiOverride); 13081 } catch (InstallerException e) { 13082 Slog.w(TAG, "Failed to free cache", e); 13083 } 13084 13085 /* 13086 * The cache free must have deleted the file we 13087 * downloaded to install. 13088 * 13089 * TODO: fix the "freeCache" call to not delete 13090 * the file we care about. 13091 */ 13092 if (pkgLite.recommendedInstallLocation 13093 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13094 pkgLite.recommendedInstallLocation 13095 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 13096 } 13097 } 13098 } 13099 13100 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13101 int loc = pkgLite.recommendedInstallLocation; 13102 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13103 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13104 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13105 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13106 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13107 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13108 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13109 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13110 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13111 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13112 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13113 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13114 } else { 13115 // Override with defaults if needed. 13116 loc = installLocationPolicy(pkgLite); 13117 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13118 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13119 } else if (!onSd && !onInt) { 13120 // Override install location with flags 13121 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13122 // Set the flag to install on external media. 13123 installFlags |= PackageManager.INSTALL_EXTERNAL; 13124 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13125 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13126 if (DEBUG_EPHEMERAL) { 13127 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13128 } 13129 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13130 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13131 |PackageManager.INSTALL_INTERNAL); 13132 } else { 13133 // Make sure the flag for installing on external 13134 // media is unset 13135 installFlags |= PackageManager.INSTALL_INTERNAL; 13136 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13137 } 13138 } 13139 } 13140 } 13141 13142 final InstallArgs args = createInstallArgs(this); 13143 mArgs = args; 13144 13145 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13146 // TODO: http://b/22976637 13147 // Apps installed for "all" users use the device owner to verify the app 13148 UserHandle verifierUser = getUser(); 13149 if (verifierUser == UserHandle.ALL) { 13150 verifierUser = UserHandle.SYSTEM; 13151 } 13152 13153 /* 13154 * Determine if we have any installed package verifiers. If we 13155 * do, then we'll defer to them to verify the packages. 13156 */ 13157 final int requiredUid = mRequiredVerifierPackage == null ? -1 13158 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13159 verifierUser.getIdentifier()); 13160 if (!origin.existing && requiredUid != -1 13161 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13162 final Intent verification = new Intent( 13163 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13164 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13165 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13166 PACKAGE_MIME_TYPE); 13167 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13168 13169 // Query all live verifiers based on current user state 13170 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13171 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13172 13173 if (DEBUG_VERIFY) { 13174 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13175 + verification.toString() + " with " + pkgLite.verifiers.length 13176 + " optional verifiers"); 13177 } 13178 13179 final int verificationId = mPendingVerificationToken++; 13180 13181 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13182 13183 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13184 installerPackageName); 13185 13186 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13187 installFlags); 13188 13189 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13190 pkgLite.packageName); 13191 13192 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13193 pkgLite.versionCode); 13194 13195 if (verificationInfo != null) { 13196 if (verificationInfo.originatingUri != null) { 13197 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13198 verificationInfo.originatingUri); 13199 } 13200 if (verificationInfo.referrer != null) { 13201 verification.putExtra(Intent.EXTRA_REFERRER, 13202 verificationInfo.referrer); 13203 } 13204 if (verificationInfo.originatingUid >= 0) { 13205 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13206 verificationInfo.originatingUid); 13207 } 13208 if (verificationInfo.installerUid >= 0) { 13209 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13210 verificationInfo.installerUid); 13211 } 13212 } 13213 13214 final PackageVerificationState verificationState = new PackageVerificationState( 13215 requiredUid, args); 13216 13217 mPendingVerification.append(verificationId, verificationState); 13218 13219 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13220 receivers, verificationState); 13221 13222 /* 13223 * If any sufficient verifiers were listed in the package 13224 * manifest, attempt to ask them. 13225 */ 13226 if (sufficientVerifiers != null) { 13227 final int N = sufficientVerifiers.size(); 13228 if (N == 0) { 13229 Slog.i(TAG, "Additional verifiers required, but none installed."); 13230 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13231 } else { 13232 for (int i = 0; i < N; i++) { 13233 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13234 13235 final Intent sufficientIntent = new Intent(verification); 13236 sufficientIntent.setComponent(verifierComponent); 13237 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13238 } 13239 } 13240 } 13241 13242 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13243 mRequiredVerifierPackage, receivers); 13244 if (ret == PackageManager.INSTALL_SUCCEEDED 13245 && mRequiredVerifierPackage != null) { 13246 Trace.asyncTraceBegin( 13247 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13248 /* 13249 * Send the intent to the required verification agent, 13250 * but only start the verification timeout after the 13251 * target BroadcastReceivers have run. 13252 */ 13253 verification.setComponent(requiredVerifierComponent); 13254 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13255 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13256 new BroadcastReceiver() { 13257 @Override 13258 public void onReceive(Context context, Intent intent) { 13259 final Message msg = mHandler 13260 .obtainMessage(CHECK_PENDING_VERIFICATION); 13261 msg.arg1 = verificationId; 13262 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13263 } 13264 }, null, 0, null, null); 13265 13266 /* 13267 * We don't want the copy to proceed until verification 13268 * succeeds, so null out this field. 13269 */ 13270 mArgs = null; 13271 } 13272 } else { 13273 /* 13274 * No package verification is enabled, so immediately start 13275 * the remote call to initiate copy using temporary file. 13276 */ 13277 ret = args.copyApk(mContainerService, true); 13278 } 13279 } 13280 13281 mRet = ret; 13282 } 13283 13284 @Override 13285 void handleReturnCode() { 13286 // If mArgs is null, then MCS couldn't be reached. When it 13287 // reconnects, it will try again to install. At that point, this 13288 // will succeed. 13289 if (mArgs != null) { 13290 processPendingInstall(mArgs, mRet); 13291 } 13292 } 13293 13294 @Override 13295 void handleServiceError() { 13296 mArgs = createInstallArgs(this); 13297 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13298 } 13299 13300 public boolean isForwardLocked() { 13301 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13302 } 13303 } 13304 13305 /** 13306 * Used during creation of InstallArgs 13307 * 13308 * @param installFlags package installation flags 13309 * @return true if should be installed on external storage 13310 */ 13311 private static boolean installOnExternalAsec(int installFlags) { 13312 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13313 return false; 13314 } 13315 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13316 return true; 13317 } 13318 return false; 13319 } 13320 13321 /** 13322 * Used during creation of InstallArgs 13323 * 13324 * @param installFlags package installation flags 13325 * @return true if should be installed as forward locked 13326 */ 13327 private static boolean installForwardLocked(int installFlags) { 13328 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13329 } 13330 13331 private InstallArgs createInstallArgs(InstallParams params) { 13332 if (params.move != null) { 13333 return new MoveInstallArgs(params); 13334 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13335 return new AsecInstallArgs(params); 13336 } else { 13337 return new FileInstallArgs(params); 13338 } 13339 } 13340 13341 /** 13342 * Create args that describe an existing installed package. Typically used 13343 * when cleaning up old installs, or used as a move source. 13344 */ 13345 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13346 String resourcePath, String[] instructionSets) { 13347 final boolean isInAsec; 13348 if (installOnExternalAsec(installFlags)) { 13349 /* Apps on SD card are always in ASEC containers. */ 13350 isInAsec = true; 13351 } else if (installForwardLocked(installFlags) 13352 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13353 /* 13354 * Forward-locked apps are only in ASEC containers if they're the 13355 * new style 13356 */ 13357 isInAsec = true; 13358 } else { 13359 isInAsec = false; 13360 } 13361 13362 if (isInAsec) { 13363 return new AsecInstallArgs(codePath, instructionSets, 13364 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13365 } else { 13366 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13367 } 13368 } 13369 13370 static abstract class InstallArgs { 13371 /** @see InstallParams#origin */ 13372 final OriginInfo origin; 13373 /** @see InstallParams#move */ 13374 final MoveInfo move; 13375 13376 final IPackageInstallObserver2 observer; 13377 // Always refers to PackageManager flags only 13378 final int installFlags; 13379 final String installerPackageName; 13380 final String volumeUuid; 13381 final UserHandle user; 13382 final String abiOverride; 13383 final String[] installGrantPermissions; 13384 /** If non-null, drop an async trace when the install completes */ 13385 final String traceMethod; 13386 final int traceCookie; 13387 final Certificate[][] certificates; 13388 13389 // The list of instruction sets supported by this app. This is currently 13390 // only used during the rmdex() phase to clean up resources. We can get rid of this 13391 // if we move dex files under the common app path. 13392 /* nullable */ String[] instructionSets; 13393 13394 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13395 int installFlags, String installerPackageName, String volumeUuid, 13396 UserHandle user, String[] instructionSets, 13397 String abiOverride, String[] installGrantPermissions, 13398 String traceMethod, int traceCookie, Certificate[][] certificates) { 13399 this.origin = origin; 13400 this.move = move; 13401 this.installFlags = installFlags; 13402 this.observer = observer; 13403 this.installerPackageName = installerPackageName; 13404 this.volumeUuid = volumeUuid; 13405 this.user = user; 13406 this.instructionSets = instructionSets; 13407 this.abiOverride = abiOverride; 13408 this.installGrantPermissions = installGrantPermissions; 13409 this.traceMethod = traceMethod; 13410 this.traceCookie = traceCookie; 13411 this.certificates = certificates; 13412 } 13413 13414 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13415 abstract int doPreInstall(int status); 13416 13417 /** 13418 * Rename package into final resting place. All paths on the given 13419 * scanned package should be updated to reflect the rename. 13420 */ 13421 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13422 abstract int doPostInstall(int status, int uid); 13423 13424 /** @see PackageSettingBase#codePathString */ 13425 abstract String getCodePath(); 13426 /** @see PackageSettingBase#resourcePathString */ 13427 abstract String getResourcePath(); 13428 13429 // Need installer lock especially for dex file removal. 13430 abstract void cleanUpResourcesLI(); 13431 abstract boolean doPostDeleteLI(boolean delete); 13432 13433 /** 13434 * Called before the source arguments are copied. This is used mostly 13435 * for MoveParams when it needs to read the source file to put it in the 13436 * destination. 13437 */ 13438 int doPreCopy() { 13439 return PackageManager.INSTALL_SUCCEEDED; 13440 } 13441 13442 /** 13443 * Called after the source arguments are copied. This is used mostly for 13444 * MoveParams when it needs to read the source file to put it in the 13445 * destination. 13446 */ 13447 int doPostCopy(int uid) { 13448 return PackageManager.INSTALL_SUCCEEDED; 13449 } 13450 13451 protected boolean isFwdLocked() { 13452 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13453 } 13454 13455 protected boolean isExternalAsec() { 13456 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13457 } 13458 13459 protected boolean isEphemeral() { 13460 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13461 } 13462 13463 UserHandle getUser() { 13464 return user; 13465 } 13466 } 13467 13468 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13469 if (!allCodePaths.isEmpty()) { 13470 if (instructionSets == null) { 13471 throw new IllegalStateException("instructionSet == null"); 13472 } 13473 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13474 for (String codePath : allCodePaths) { 13475 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13476 try { 13477 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13478 } catch (InstallerException ignored) { 13479 } 13480 } 13481 } 13482 } 13483 } 13484 13485 /** 13486 * Logic to handle installation of non-ASEC applications, including copying 13487 * and renaming logic. 13488 */ 13489 class FileInstallArgs extends InstallArgs { 13490 private File codeFile; 13491 private File resourceFile; 13492 13493 // Example topology: 13494 // /data/app/com.example/base.apk 13495 // /data/app/com.example/split_foo.apk 13496 // /data/app/com.example/lib/arm/libfoo.so 13497 // /data/app/com.example/lib/arm64/libfoo.so 13498 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13499 13500 /** New install */ 13501 FileInstallArgs(InstallParams params) { 13502 super(params.origin, params.move, params.observer, params.installFlags, 13503 params.installerPackageName, params.volumeUuid, 13504 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13505 params.grantedRuntimePermissions, 13506 params.traceMethod, params.traceCookie, params.certificates); 13507 if (isFwdLocked()) { 13508 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13509 } 13510 } 13511 13512 /** Existing install */ 13513 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13514 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13515 null, null, null, 0, null /*certificates*/); 13516 this.codeFile = (codePath != null) ? new File(codePath) : null; 13517 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13518 } 13519 13520 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13521 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13522 try { 13523 return doCopyApk(imcs, temp); 13524 } finally { 13525 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13526 } 13527 } 13528 13529 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13530 if (origin.staged) { 13531 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13532 codeFile = origin.file; 13533 resourceFile = origin.file; 13534 return PackageManager.INSTALL_SUCCEEDED; 13535 } 13536 13537 try { 13538 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13539 final File tempDir = 13540 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13541 codeFile = tempDir; 13542 resourceFile = tempDir; 13543 } catch (IOException e) { 13544 Slog.w(TAG, "Failed to create copy file: " + e); 13545 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13546 } 13547 13548 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13549 @Override 13550 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13551 if (!FileUtils.isValidExtFilename(name)) { 13552 throw new IllegalArgumentException("Invalid filename: " + name); 13553 } 13554 try { 13555 final File file = new File(codeFile, name); 13556 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13557 O_RDWR | O_CREAT, 0644); 13558 Os.chmod(file.getAbsolutePath(), 0644); 13559 return new ParcelFileDescriptor(fd); 13560 } catch (ErrnoException e) { 13561 throw new RemoteException("Failed to open: " + e.getMessage()); 13562 } 13563 } 13564 }; 13565 13566 int ret = PackageManager.INSTALL_SUCCEEDED; 13567 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13568 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13569 Slog.e(TAG, "Failed to copy package"); 13570 return ret; 13571 } 13572 13573 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13574 NativeLibraryHelper.Handle handle = null; 13575 try { 13576 handle = NativeLibraryHelper.Handle.create(codeFile); 13577 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13578 abiOverride); 13579 } catch (IOException e) { 13580 Slog.e(TAG, "Copying native libraries failed", e); 13581 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13582 } finally { 13583 IoUtils.closeQuietly(handle); 13584 } 13585 13586 return ret; 13587 } 13588 13589 int doPreInstall(int status) { 13590 if (status != PackageManager.INSTALL_SUCCEEDED) { 13591 cleanUp(); 13592 } 13593 return status; 13594 } 13595 13596 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13597 if (status != PackageManager.INSTALL_SUCCEEDED) { 13598 cleanUp(); 13599 return false; 13600 } 13601 13602 final File targetDir = codeFile.getParentFile(); 13603 final File beforeCodeFile = codeFile; 13604 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13605 13606 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13607 try { 13608 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13609 } catch (ErrnoException e) { 13610 Slog.w(TAG, "Failed to rename", e); 13611 return false; 13612 } 13613 13614 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13615 Slog.w(TAG, "Failed to restorecon"); 13616 return false; 13617 } 13618 13619 // Reflect the rename internally 13620 codeFile = afterCodeFile; 13621 resourceFile = afterCodeFile; 13622 13623 // Reflect the rename in scanned details 13624 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13625 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13626 afterCodeFile, pkg.baseCodePath)); 13627 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13628 afterCodeFile, pkg.splitCodePaths)); 13629 13630 // Reflect the rename in app info 13631 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13632 pkg.setApplicationInfoCodePath(pkg.codePath); 13633 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13634 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13635 pkg.setApplicationInfoResourcePath(pkg.codePath); 13636 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13637 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13638 13639 return true; 13640 } 13641 13642 int doPostInstall(int status, int uid) { 13643 if (status != PackageManager.INSTALL_SUCCEEDED) { 13644 cleanUp(); 13645 } 13646 return status; 13647 } 13648 13649 @Override 13650 String getCodePath() { 13651 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13652 } 13653 13654 @Override 13655 String getResourcePath() { 13656 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13657 } 13658 13659 private boolean cleanUp() { 13660 if (codeFile == null || !codeFile.exists()) { 13661 return false; 13662 } 13663 13664 removeCodePathLI(codeFile); 13665 13666 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13667 resourceFile.delete(); 13668 } 13669 13670 return true; 13671 } 13672 13673 void cleanUpResourcesLI() { 13674 // Try enumerating all code paths before deleting 13675 List<String> allCodePaths = Collections.EMPTY_LIST; 13676 if (codeFile != null && codeFile.exists()) { 13677 try { 13678 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13679 allCodePaths = pkg.getAllCodePaths(); 13680 } catch (PackageParserException e) { 13681 // Ignored; we tried our best 13682 } 13683 } 13684 13685 cleanUp(); 13686 removeDexFiles(allCodePaths, instructionSets); 13687 } 13688 13689 boolean doPostDeleteLI(boolean delete) { 13690 // XXX err, shouldn't we respect the delete flag? 13691 cleanUpResourcesLI(); 13692 return true; 13693 } 13694 } 13695 13696 private boolean isAsecExternal(String cid) { 13697 final String asecPath = PackageHelper.getSdFilesystem(cid); 13698 return !asecPath.startsWith(mAsecInternalPath); 13699 } 13700 13701 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13702 PackageManagerException { 13703 if (copyRet < 0) { 13704 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13705 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13706 throw new PackageManagerException(copyRet, message); 13707 } 13708 } 13709 } 13710 13711 /** 13712 * Extract the MountService "container ID" from the full code path of an 13713 * .apk. 13714 */ 13715 static String cidFromCodePath(String fullCodePath) { 13716 int eidx = fullCodePath.lastIndexOf("/"); 13717 String subStr1 = fullCodePath.substring(0, eidx); 13718 int sidx = subStr1.lastIndexOf("/"); 13719 return subStr1.substring(sidx+1, eidx); 13720 } 13721 13722 /** 13723 * Logic to handle installation of ASEC applications, including copying and 13724 * renaming logic. 13725 */ 13726 class AsecInstallArgs extends InstallArgs { 13727 static final String RES_FILE_NAME = "pkg.apk"; 13728 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13729 13730 String cid; 13731 String packagePath; 13732 String resourcePath; 13733 13734 /** New install */ 13735 AsecInstallArgs(InstallParams params) { 13736 super(params.origin, params.move, params.observer, params.installFlags, 13737 params.installerPackageName, params.volumeUuid, 13738 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13739 params.grantedRuntimePermissions, 13740 params.traceMethod, params.traceCookie, params.certificates); 13741 } 13742 13743 /** Existing install */ 13744 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13745 boolean isExternal, boolean isForwardLocked) { 13746 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13747 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13748 instructionSets, null, null, null, 0, null /*certificates*/); 13749 // Hackily pretend we're still looking at a full code path 13750 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13751 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13752 } 13753 13754 // Extract cid from fullCodePath 13755 int eidx = fullCodePath.lastIndexOf("/"); 13756 String subStr1 = fullCodePath.substring(0, eidx); 13757 int sidx = subStr1.lastIndexOf("/"); 13758 cid = subStr1.substring(sidx+1, eidx); 13759 setMountPath(subStr1); 13760 } 13761 13762 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13763 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13764 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13765 instructionSets, null, null, null, 0, null /*certificates*/); 13766 this.cid = cid; 13767 setMountPath(PackageHelper.getSdDir(cid)); 13768 } 13769 13770 void createCopyFile() { 13771 cid = mInstallerService.allocateExternalStageCidLegacy(); 13772 } 13773 13774 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13775 if (origin.staged && origin.cid != null) { 13776 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13777 cid = origin.cid; 13778 setMountPath(PackageHelper.getSdDir(cid)); 13779 return PackageManager.INSTALL_SUCCEEDED; 13780 } 13781 13782 if (temp) { 13783 createCopyFile(); 13784 } else { 13785 /* 13786 * Pre-emptively destroy the container since it's destroyed if 13787 * copying fails due to it existing anyway. 13788 */ 13789 PackageHelper.destroySdDir(cid); 13790 } 13791 13792 final String newMountPath = imcs.copyPackageToContainer( 13793 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13794 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13795 13796 if (newMountPath != null) { 13797 setMountPath(newMountPath); 13798 return PackageManager.INSTALL_SUCCEEDED; 13799 } else { 13800 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13801 } 13802 } 13803 13804 @Override 13805 String getCodePath() { 13806 return packagePath; 13807 } 13808 13809 @Override 13810 String getResourcePath() { 13811 return resourcePath; 13812 } 13813 13814 int doPreInstall(int status) { 13815 if (status != PackageManager.INSTALL_SUCCEEDED) { 13816 // Destroy container 13817 PackageHelper.destroySdDir(cid); 13818 } else { 13819 boolean mounted = PackageHelper.isContainerMounted(cid); 13820 if (!mounted) { 13821 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13822 Process.SYSTEM_UID); 13823 if (newMountPath != null) { 13824 setMountPath(newMountPath); 13825 } else { 13826 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13827 } 13828 } 13829 } 13830 return status; 13831 } 13832 13833 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13834 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13835 String newMountPath = null; 13836 if (PackageHelper.isContainerMounted(cid)) { 13837 // Unmount the container 13838 if (!PackageHelper.unMountSdDir(cid)) { 13839 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13840 return false; 13841 } 13842 } 13843 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13844 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13845 " which might be stale. Will try to clean up."); 13846 // Clean up the stale container and proceed to recreate. 13847 if (!PackageHelper.destroySdDir(newCacheId)) { 13848 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13849 return false; 13850 } 13851 // Successfully cleaned up stale container. Try to rename again. 13852 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13853 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13854 + " inspite of cleaning it up."); 13855 return false; 13856 } 13857 } 13858 if (!PackageHelper.isContainerMounted(newCacheId)) { 13859 Slog.w(TAG, "Mounting container " + newCacheId); 13860 newMountPath = PackageHelper.mountSdDir(newCacheId, 13861 getEncryptKey(), Process.SYSTEM_UID); 13862 } else { 13863 newMountPath = PackageHelper.getSdDir(newCacheId); 13864 } 13865 if (newMountPath == null) { 13866 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13867 return false; 13868 } 13869 Log.i(TAG, "Succesfully renamed " + cid + 13870 " to " + newCacheId + 13871 " at new path: " + newMountPath); 13872 cid = newCacheId; 13873 13874 final File beforeCodeFile = new File(packagePath); 13875 setMountPath(newMountPath); 13876 final File afterCodeFile = new File(packagePath); 13877 13878 // Reflect the rename in scanned details 13879 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13880 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13881 afterCodeFile, pkg.baseCodePath)); 13882 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13883 afterCodeFile, pkg.splitCodePaths)); 13884 13885 // Reflect the rename in app info 13886 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13887 pkg.setApplicationInfoCodePath(pkg.codePath); 13888 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13889 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13890 pkg.setApplicationInfoResourcePath(pkg.codePath); 13891 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13892 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13893 13894 return true; 13895 } 13896 13897 private void setMountPath(String mountPath) { 13898 final File mountFile = new File(mountPath); 13899 13900 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13901 if (monolithicFile.exists()) { 13902 packagePath = monolithicFile.getAbsolutePath(); 13903 if (isFwdLocked()) { 13904 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13905 } else { 13906 resourcePath = packagePath; 13907 } 13908 } else { 13909 packagePath = mountFile.getAbsolutePath(); 13910 resourcePath = packagePath; 13911 } 13912 } 13913 13914 int doPostInstall(int status, int uid) { 13915 if (status != PackageManager.INSTALL_SUCCEEDED) { 13916 cleanUp(); 13917 } else { 13918 final int groupOwner; 13919 final String protectedFile; 13920 if (isFwdLocked()) { 13921 groupOwner = UserHandle.getSharedAppGid(uid); 13922 protectedFile = RES_FILE_NAME; 13923 } else { 13924 groupOwner = -1; 13925 protectedFile = null; 13926 } 13927 13928 if (uid < Process.FIRST_APPLICATION_UID 13929 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13930 Slog.e(TAG, "Failed to finalize " + cid); 13931 PackageHelper.destroySdDir(cid); 13932 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13933 } 13934 13935 boolean mounted = PackageHelper.isContainerMounted(cid); 13936 if (!mounted) { 13937 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13938 } 13939 } 13940 return status; 13941 } 13942 13943 private void cleanUp() { 13944 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13945 13946 // Destroy secure container 13947 PackageHelper.destroySdDir(cid); 13948 } 13949 13950 private List<String> getAllCodePaths() { 13951 final File codeFile = new File(getCodePath()); 13952 if (codeFile != null && codeFile.exists()) { 13953 try { 13954 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13955 return pkg.getAllCodePaths(); 13956 } catch (PackageParserException e) { 13957 // Ignored; we tried our best 13958 } 13959 } 13960 return Collections.EMPTY_LIST; 13961 } 13962 13963 void cleanUpResourcesLI() { 13964 // Enumerate all code paths before deleting 13965 cleanUpResourcesLI(getAllCodePaths()); 13966 } 13967 13968 private void cleanUpResourcesLI(List<String> allCodePaths) { 13969 cleanUp(); 13970 removeDexFiles(allCodePaths, instructionSets); 13971 } 13972 13973 String getPackageName() { 13974 return getAsecPackageName(cid); 13975 } 13976 13977 boolean doPostDeleteLI(boolean delete) { 13978 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13979 final List<String> allCodePaths = getAllCodePaths(); 13980 boolean mounted = PackageHelper.isContainerMounted(cid); 13981 if (mounted) { 13982 // Unmount first 13983 if (PackageHelper.unMountSdDir(cid)) { 13984 mounted = false; 13985 } 13986 } 13987 if (!mounted && delete) { 13988 cleanUpResourcesLI(allCodePaths); 13989 } 13990 return !mounted; 13991 } 13992 13993 @Override 13994 int doPreCopy() { 13995 if (isFwdLocked()) { 13996 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13997 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13998 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13999 } 14000 } 14001 14002 return PackageManager.INSTALL_SUCCEEDED; 14003 } 14004 14005 @Override 14006 int doPostCopy(int uid) { 14007 if (isFwdLocked()) { 14008 if (uid < Process.FIRST_APPLICATION_UID 14009 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 14010 RES_FILE_NAME)) { 14011 Slog.e(TAG, "Failed to finalize " + cid); 14012 PackageHelper.destroySdDir(cid); 14013 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14014 } 14015 } 14016 14017 return PackageManager.INSTALL_SUCCEEDED; 14018 } 14019 } 14020 14021 /** 14022 * Logic to handle movement of existing installed applications. 14023 */ 14024 class MoveInstallArgs extends InstallArgs { 14025 private File codeFile; 14026 private File resourceFile; 14027 14028 /** New install */ 14029 MoveInstallArgs(InstallParams params) { 14030 super(params.origin, params.move, params.observer, params.installFlags, 14031 params.installerPackageName, params.volumeUuid, 14032 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14033 params.grantedRuntimePermissions, 14034 params.traceMethod, params.traceCookie, params.certificates); 14035 } 14036 14037 int copyApk(IMediaContainerService imcs, boolean temp) { 14038 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 14039 + move.fromUuid + " to " + move.toUuid); 14040 synchronized (mInstaller) { 14041 try { 14042 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 14043 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 14044 } catch (InstallerException e) { 14045 Slog.w(TAG, "Failed to move app", e); 14046 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14047 } 14048 } 14049 14050 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 14051 resourceFile = codeFile; 14052 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 14053 14054 return PackageManager.INSTALL_SUCCEEDED; 14055 } 14056 14057 int doPreInstall(int status) { 14058 if (status != PackageManager.INSTALL_SUCCEEDED) { 14059 cleanUp(move.toUuid); 14060 } 14061 return status; 14062 } 14063 14064 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14065 if (status != PackageManager.INSTALL_SUCCEEDED) { 14066 cleanUp(move.toUuid); 14067 return false; 14068 } 14069 14070 // Reflect the move in app info 14071 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14072 pkg.setApplicationInfoCodePath(pkg.codePath); 14073 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14074 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14075 pkg.setApplicationInfoResourcePath(pkg.codePath); 14076 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14077 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14078 14079 return true; 14080 } 14081 14082 int doPostInstall(int status, int uid) { 14083 if (status == PackageManager.INSTALL_SUCCEEDED) { 14084 cleanUp(move.fromUuid); 14085 } else { 14086 cleanUp(move.toUuid); 14087 } 14088 return status; 14089 } 14090 14091 @Override 14092 String getCodePath() { 14093 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14094 } 14095 14096 @Override 14097 String getResourcePath() { 14098 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14099 } 14100 14101 private boolean cleanUp(String volumeUuid) { 14102 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14103 move.dataAppName); 14104 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14105 final int[] userIds = sUserManager.getUserIds(); 14106 synchronized (mInstallLock) { 14107 // Clean up both app data and code 14108 // All package moves are frozen until finished 14109 for (int userId : userIds) { 14110 try { 14111 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14112 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14113 } catch (InstallerException e) { 14114 Slog.w(TAG, String.valueOf(e)); 14115 } 14116 } 14117 removeCodePathLI(codeFile); 14118 } 14119 return true; 14120 } 14121 14122 void cleanUpResourcesLI() { 14123 throw new UnsupportedOperationException(); 14124 } 14125 14126 boolean doPostDeleteLI(boolean delete) { 14127 throw new UnsupportedOperationException(); 14128 } 14129 } 14130 14131 static String getAsecPackageName(String packageCid) { 14132 int idx = packageCid.lastIndexOf("-"); 14133 if (idx == -1) { 14134 return packageCid; 14135 } 14136 return packageCid.substring(0, idx); 14137 } 14138 14139 // Utility method used to create code paths based on package name and available index. 14140 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14141 String idxStr = ""; 14142 int idx = 1; 14143 // Fall back to default value of idx=1 if prefix is not 14144 // part of oldCodePath 14145 if (oldCodePath != null) { 14146 String subStr = oldCodePath; 14147 // Drop the suffix right away 14148 if (suffix != null && subStr.endsWith(suffix)) { 14149 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14150 } 14151 // If oldCodePath already contains prefix find out the 14152 // ending index to either increment or decrement. 14153 int sidx = subStr.lastIndexOf(prefix); 14154 if (sidx != -1) { 14155 subStr = subStr.substring(sidx + prefix.length()); 14156 if (subStr != null) { 14157 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14158 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14159 } 14160 try { 14161 idx = Integer.parseInt(subStr); 14162 if (idx <= 1) { 14163 idx++; 14164 } else { 14165 idx--; 14166 } 14167 } catch(NumberFormatException e) { 14168 } 14169 } 14170 } 14171 } 14172 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14173 return prefix + idxStr; 14174 } 14175 14176 private File getNextCodePath(File targetDir, String packageName) { 14177 int suffix = 1; 14178 File result; 14179 do { 14180 result = new File(targetDir, packageName + "-" + suffix); 14181 suffix++; 14182 } while (result.exists()); 14183 return result; 14184 } 14185 14186 // Utility method that returns the relative package path with respect 14187 // to the installation directory. Like say for /data/data/com.test-1.apk 14188 // string com.test-1 is returned. 14189 static String deriveCodePathName(String codePath) { 14190 if (codePath == null) { 14191 return null; 14192 } 14193 final File codeFile = new File(codePath); 14194 final String name = codeFile.getName(); 14195 if (codeFile.isDirectory()) { 14196 return name; 14197 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14198 final int lastDot = name.lastIndexOf('.'); 14199 return name.substring(0, lastDot); 14200 } else { 14201 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14202 return null; 14203 } 14204 } 14205 14206 static class PackageInstalledInfo { 14207 String name; 14208 int uid; 14209 // The set of users that originally had this package installed. 14210 int[] origUsers; 14211 // The set of users that now have this package installed. 14212 int[] newUsers; 14213 PackageParser.Package pkg; 14214 int returnCode; 14215 String returnMsg; 14216 PackageRemovedInfo removedInfo; 14217 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14218 14219 public void setError(int code, String msg) { 14220 setReturnCode(code); 14221 setReturnMessage(msg); 14222 Slog.w(TAG, msg); 14223 } 14224 14225 public void setError(String msg, PackageParserException e) { 14226 setReturnCode(e.error); 14227 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14228 Slog.w(TAG, msg, e); 14229 } 14230 14231 public void setError(String msg, PackageManagerException e) { 14232 returnCode = e.error; 14233 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14234 Slog.w(TAG, msg, e); 14235 } 14236 14237 public void setReturnCode(int returnCode) { 14238 this.returnCode = returnCode; 14239 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14240 for (int i = 0; i < childCount; i++) { 14241 addedChildPackages.valueAt(i).returnCode = returnCode; 14242 } 14243 } 14244 14245 private void setReturnMessage(String returnMsg) { 14246 this.returnMsg = returnMsg; 14247 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14248 for (int i = 0; i < childCount; i++) { 14249 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14250 } 14251 } 14252 14253 // In some error cases we want to convey more info back to the observer 14254 String origPackage; 14255 String origPermission; 14256 } 14257 14258 /* 14259 * Install a non-existing package. 14260 */ 14261 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14262 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14263 PackageInstalledInfo res) { 14264 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14265 14266 // Remember this for later, in case we need to rollback this install 14267 String pkgName = pkg.packageName; 14268 14269 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14270 14271 synchronized(mPackages) { 14272 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14273 // A package with the same name is already installed, though 14274 // it has been renamed to an older name. The package we 14275 // are trying to install should be installed as an update to 14276 // the existing one, but that has not been requested, so bail. 14277 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14278 + " without first uninstalling package running as " 14279 + mSettings.mRenamedPackages.get(pkgName)); 14280 return; 14281 } 14282 if (mPackages.containsKey(pkgName)) { 14283 // Don't allow installation over an existing package with the same name. 14284 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14285 + " without first uninstalling."); 14286 return; 14287 } 14288 } 14289 14290 try { 14291 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14292 System.currentTimeMillis(), user); 14293 14294 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14295 14296 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14297 prepareAppDataAfterInstallLIF(newPackage); 14298 14299 } else { 14300 // Remove package from internal structures, but keep around any 14301 // data that might have already existed 14302 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14303 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14304 } 14305 } catch (PackageManagerException e) { 14306 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14307 } 14308 14309 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14310 } 14311 14312 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14313 // Can't rotate keys during boot or if sharedUser. 14314 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14315 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14316 return false; 14317 } 14318 // app is using upgradeKeySets; make sure all are valid 14319 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14320 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14321 for (int i = 0; i < upgradeKeySets.length; i++) { 14322 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14323 Slog.wtf(TAG, "Package " 14324 + (oldPs.name != null ? oldPs.name : "<null>") 14325 + " contains upgrade-key-set reference to unknown key-set: " 14326 + upgradeKeySets[i] 14327 + " reverting to signatures check."); 14328 return false; 14329 } 14330 } 14331 return true; 14332 } 14333 14334 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14335 // Upgrade keysets are being used. Determine if new package has a superset of the 14336 // required keys. 14337 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14338 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14339 for (int i = 0; i < upgradeKeySets.length; i++) { 14340 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14341 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14342 return true; 14343 } 14344 } 14345 return false; 14346 } 14347 14348 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14349 try (DigestInputStream digestStream = 14350 new DigestInputStream(new FileInputStream(file), digest)) { 14351 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14352 } 14353 } 14354 14355 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14356 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14357 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14358 14359 final PackageParser.Package oldPackage; 14360 final String pkgName = pkg.packageName; 14361 final int[] allUsers; 14362 final int[] installedUsers; 14363 14364 synchronized(mPackages) { 14365 oldPackage = mPackages.get(pkgName); 14366 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14367 14368 // don't allow upgrade to target a release SDK from a pre-release SDK 14369 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14370 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14371 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14372 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14373 if (oldTargetsPreRelease 14374 && !newTargetsPreRelease 14375 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14376 Slog.w(TAG, "Can't install package targeting released sdk"); 14377 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14378 return; 14379 } 14380 14381 // don't allow an upgrade from full to ephemeral 14382 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14383 if (isEphemeral && !oldIsEphemeral) { 14384 // can't downgrade from full to ephemeral 14385 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14386 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14387 return; 14388 } 14389 14390 // verify signatures are valid 14391 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14392 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14393 if (!checkUpgradeKeySetLP(ps, pkg)) { 14394 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14395 "New package not signed by keys specified by upgrade-keysets: " 14396 + pkgName); 14397 return; 14398 } 14399 } else { 14400 // default to original signature matching 14401 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14402 != PackageManager.SIGNATURE_MATCH) { 14403 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14404 "New package has a different signature: " + pkgName); 14405 return; 14406 } 14407 } 14408 14409 // don't allow a system upgrade unless the upgrade hash matches 14410 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14411 byte[] digestBytes = null; 14412 try { 14413 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14414 updateDigest(digest, new File(pkg.baseCodePath)); 14415 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14416 for (String path : pkg.splitCodePaths) { 14417 updateDigest(digest, new File(path)); 14418 } 14419 } 14420 digestBytes = digest.digest(); 14421 } catch (NoSuchAlgorithmException | IOException e) { 14422 res.setError(INSTALL_FAILED_INVALID_APK, 14423 "Could not compute hash: " + pkgName); 14424 return; 14425 } 14426 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14427 res.setError(INSTALL_FAILED_INVALID_APK, 14428 "New package fails restrict-update check: " + pkgName); 14429 return; 14430 } 14431 // retain upgrade restriction 14432 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14433 } 14434 14435 // Check for shared user id changes 14436 String invalidPackageName = 14437 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14438 if (invalidPackageName != null) { 14439 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14440 "Package " + invalidPackageName + " tried to change user " 14441 + oldPackage.mSharedUserId); 14442 return; 14443 } 14444 14445 // In case of rollback, remember per-user/profile install state 14446 allUsers = sUserManager.getUserIds(); 14447 installedUsers = ps.queryInstalledUsers(allUsers, true); 14448 } 14449 14450 // Update what is removed 14451 res.removedInfo = new PackageRemovedInfo(); 14452 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14453 res.removedInfo.removedPackage = oldPackage.packageName; 14454 res.removedInfo.isUpdate = true; 14455 res.removedInfo.origUsers = installedUsers; 14456 final int childCount = (oldPackage.childPackages != null) 14457 ? oldPackage.childPackages.size() : 0; 14458 for (int i = 0; i < childCount; i++) { 14459 boolean childPackageUpdated = false; 14460 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14461 if (res.addedChildPackages != null) { 14462 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14463 if (childRes != null) { 14464 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14465 childRes.removedInfo.removedPackage = childPkg.packageName; 14466 childRes.removedInfo.isUpdate = true; 14467 childPackageUpdated = true; 14468 } 14469 } 14470 if (!childPackageUpdated) { 14471 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14472 childRemovedRes.removedPackage = childPkg.packageName; 14473 childRemovedRes.isUpdate = false; 14474 childRemovedRes.dataRemoved = true; 14475 synchronized (mPackages) { 14476 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14477 if (childPs != null) { 14478 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14479 } 14480 } 14481 if (res.removedInfo.removedChildPackages == null) { 14482 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14483 } 14484 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14485 } 14486 } 14487 14488 boolean sysPkg = (isSystemApp(oldPackage)); 14489 if (sysPkg) { 14490 // Set the system/privileged flags as needed 14491 final boolean privileged = 14492 (oldPackage.applicationInfo.privateFlags 14493 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14494 final int systemPolicyFlags = policyFlags 14495 | PackageParser.PARSE_IS_SYSTEM 14496 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14497 14498 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14499 user, allUsers, installerPackageName, res); 14500 } else { 14501 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14502 user, allUsers, installerPackageName, res); 14503 } 14504 } 14505 14506 public List<String> getPreviousCodePaths(String packageName) { 14507 final PackageSetting ps = mSettings.mPackages.get(packageName); 14508 final List<String> result = new ArrayList<String>(); 14509 if (ps != null && ps.oldCodePaths != null) { 14510 result.addAll(ps.oldCodePaths); 14511 } 14512 return result; 14513 } 14514 14515 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14516 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14517 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14518 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14519 + deletedPackage); 14520 14521 String pkgName = deletedPackage.packageName; 14522 boolean deletedPkg = true; 14523 boolean addedPkg = false; 14524 boolean updatedSettings = false; 14525 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14526 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14527 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14528 14529 final long origUpdateTime = (pkg.mExtras != null) 14530 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14531 14532 // First delete the existing package while retaining the data directory 14533 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14534 res.removedInfo, true, pkg)) { 14535 // If the existing package wasn't successfully deleted 14536 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14537 deletedPkg = false; 14538 } else { 14539 // Successfully deleted the old package; proceed with replace. 14540 14541 // If deleted package lived in a container, give users a chance to 14542 // relinquish resources before killing. 14543 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14544 if (DEBUG_INSTALL) { 14545 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14546 } 14547 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14548 final ArrayList<String> pkgList = new ArrayList<String>(1); 14549 pkgList.add(deletedPackage.applicationInfo.packageName); 14550 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14551 } 14552 14553 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14554 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14555 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14556 14557 try { 14558 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14559 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14560 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14561 14562 // Update the in-memory copy of the previous code paths. 14563 PackageSetting ps = mSettings.mPackages.get(pkgName); 14564 if (!killApp) { 14565 if (ps.oldCodePaths == null) { 14566 ps.oldCodePaths = new ArraySet<>(); 14567 } 14568 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14569 if (deletedPackage.splitCodePaths != null) { 14570 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14571 } 14572 } else { 14573 ps.oldCodePaths = null; 14574 } 14575 if (ps.childPackageNames != null) { 14576 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14577 final String childPkgName = ps.childPackageNames.get(i); 14578 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14579 childPs.oldCodePaths = ps.oldCodePaths; 14580 } 14581 } 14582 prepareAppDataAfterInstallLIF(newPackage); 14583 addedPkg = true; 14584 } catch (PackageManagerException e) { 14585 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14586 } 14587 } 14588 14589 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14590 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14591 14592 // Revert all internal state mutations and added folders for the failed install 14593 if (addedPkg) { 14594 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14595 res.removedInfo, true, null); 14596 } 14597 14598 // Restore the old package 14599 if (deletedPkg) { 14600 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14601 File restoreFile = new File(deletedPackage.codePath); 14602 // Parse old package 14603 boolean oldExternal = isExternal(deletedPackage); 14604 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14605 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14606 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14607 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14608 try { 14609 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14610 null); 14611 } catch (PackageManagerException e) { 14612 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14613 + e.getMessage()); 14614 return; 14615 } 14616 14617 synchronized (mPackages) { 14618 // Ensure the installer package name up to date 14619 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14620 14621 // Update permissions for restored package 14622 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14623 14624 mSettings.writeLPr(); 14625 } 14626 14627 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14628 } 14629 } else { 14630 synchronized (mPackages) { 14631 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14632 if (ps != null) { 14633 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14634 if (res.removedInfo.removedChildPackages != null) { 14635 final int childCount = res.removedInfo.removedChildPackages.size(); 14636 // Iterate in reverse as we may modify the collection 14637 for (int i = childCount - 1; i >= 0; i--) { 14638 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14639 if (res.addedChildPackages.containsKey(childPackageName)) { 14640 res.removedInfo.removedChildPackages.removeAt(i); 14641 } else { 14642 PackageRemovedInfo childInfo = res.removedInfo 14643 .removedChildPackages.valueAt(i); 14644 childInfo.removedForAllUsers = mPackages.get( 14645 childInfo.removedPackage) == null; 14646 } 14647 } 14648 } 14649 } 14650 } 14651 } 14652 } 14653 14654 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14655 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14656 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14657 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14658 + ", old=" + deletedPackage); 14659 14660 final boolean disabledSystem; 14661 14662 // Remove existing system package 14663 removePackageLI(deletedPackage, true); 14664 14665 synchronized (mPackages) { 14666 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14667 } 14668 if (!disabledSystem) { 14669 // We didn't need to disable the .apk as a current system package, 14670 // which means we are replacing another update that is already 14671 // installed. We need to make sure to delete the older one's .apk. 14672 res.removedInfo.args = createInstallArgsForExisting(0, 14673 deletedPackage.applicationInfo.getCodePath(), 14674 deletedPackage.applicationInfo.getResourcePath(), 14675 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14676 } else { 14677 res.removedInfo.args = null; 14678 } 14679 14680 // Successfully disabled the old package. Now proceed with re-installation 14681 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14682 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14683 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14684 14685 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14686 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14687 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14688 14689 PackageParser.Package newPackage = null; 14690 try { 14691 // Add the package to the internal data structures 14692 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14693 14694 // Set the update and install times 14695 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14696 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14697 System.currentTimeMillis()); 14698 14699 // Update the package dynamic state if succeeded 14700 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14701 // Now that the install succeeded make sure we remove data 14702 // directories for any child package the update removed. 14703 final int deletedChildCount = (deletedPackage.childPackages != null) 14704 ? deletedPackage.childPackages.size() : 0; 14705 final int newChildCount = (newPackage.childPackages != null) 14706 ? newPackage.childPackages.size() : 0; 14707 for (int i = 0; i < deletedChildCount; i++) { 14708 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14709 boolean childPackageDeleted = true; 14710 for (int j = 0; j < newChildCount; j++) { 14711 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14712 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14713 childPackageDeleted = false; 14714 break; 14715 } 14716 } 14717 if (childPackageDeleted) { 14718 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14719 deletedChildPkg.packageName); 14720 if (ps != null && res.removedInfo.removedChildPackages != null) { 14721 PackageRemovedInfo removedChildRes = res.removedInfo 14722 .removedChildPackages.get(deletedChildPkg.packageName); 14723 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14724 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14725 } 14726 } 14727 } 14728 14729 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14730 prepareAppDataAfterInstallLIF(newPackage); 14731 } 14732 } catch (PackageManagerException e) { 14733 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14734 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14735 } 14736 14737 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14738 // Re installation failed. Restore old information 14739 // Remove new pkg information 14740 if (newPackage != null) { 14741 removeInstalledPackageLI(newPackage, true); 14742 } 14743 // Add back the old system package 14744 try { 14745 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14746 } catch (PackageManagerException e) { 14747 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14748 } 14749 14750 synchronized (mPackages) { 14751 if (disabledSystem) { 14752 enableSystemPackageLPw(deletedPackage); 14753 } 14754 14755 // Ensure the installer package name up to date 14756 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14757 14758 // Update permissions for restored package 14759 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14760 14761 mSettings.writeLPr(); 14762 } 14763 14764 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14765 + " after failed upgrade"); 14766 } 14767 } 14768 14769 /** 14770 * Checks whether the parent or any of the child packages have a change shared 14771 * user. For a package to be a valid update the shred users of the parent and 14772 * the children should match. We may later support changing child shared users. 14773 * @param oldPkg The updated package. 14774 * @param newPkg The update package. 14775 * @return The shared user that change between the versions. 14776 */ 14777 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14778 PackageParser.Package newPkg) { 14779 // Check parent shared user 14780 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14781 return newPkg.packageName; 14782 } 14783 // Check child shared users 14784 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14785 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14786 for (int i = 0; i < newChildCount; i++) { 14787 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14788 // If this child was present, did it have the same shared user? 14789 for (int j = 0; j < oldChildCount; j++) { 14790 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14791 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14792 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14793 return newChildPkg.packageName; 14794 } 14795 } 14796 } 14797 return null; 14798 } 14799 14800 private void removeNativeBinariesLI(PackageSetting ps) { 14801 // Remove the lib path for the parent package 14802 if (ps != null) { 14803 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14804 // Remove the lib path for the child packages 14805 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14806 for (int i = 0; i < childCount; i++) { 14807 PackageSetting childPs = null; 14808 synchronized (mPackages) { 14809 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14810 } 14811 if (childPs != null) { 14812 NativeLibraryHelper.removeNativeBinariesLI(childPs 14813 .legacyNativeLibraryPathString); 14814 } 14815 } 14816 } 14817 } 14818 14819 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14820 // Enable the parent package 14821 mSettings.enableSystemPackageLPw(pkg.packageName); 14822 // Enable the child packages 14823 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14824 for (int i = 0; i < childCount; i++) { 14825 PackageParser.Package childPkg = pkg.childPackages.get(i); 14826 mSettings.enableSystemPackageLPw(childPkg.packageName); 14827 } 14828 } 14829 14830 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14831 PackageParser.Package newPkg) { 14832 // Disable the parent package (parent always replaced) 14833 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14834 // Disable the child packages 14835 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14836 for (int i = 0; i < childCount; i++) { 14837 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14838 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14839 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14840 } 14841 return disabled; 14842 } 14843 14844 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14845 String installerPackageName) { 14846 // Enable the parent package 14847 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14848 // Enable the child packages 14849 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14850 for (int i = 0; i < childCount; i++) { 14851 PackageParser.Package childPkg = pkg.childPackages.get(i); 14852 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14853 } 14854 } 14855 14856 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14857 // Collect all used permissions in the UID 14858 ArraySet<String> usedPermissions = new ArraySet<>(); 14859 final int packageCount = su.packages.size(); 14860 for (int i = 0; i < packageCount; i++) { 14861 PackageSetting ps = su.packages.valueAt(i); 14862 if (ps.pkg == null) { 14863 continue; 14864 } 14865 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14866 for (int j = 0; j < requestedPermCount; j++) { 14867 String permission = ps.pkg.requestedPermissions.get(j); 14868 BasePermission bp = mSettings.mPermissions.get(permission); 14869 if (bp != null) { 14870 usedPermissions.add(permission); 14871 } 14872 } 14873 } 14874 14875 PermissionsState permissionsState = su.getPermissionsState(); 14876 // Prune install permissions 14877 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14878 final int installPermCount = installPermStates.size(); 14879 for (int i = installPermCount - 1; i >= 0; i--) { 14880 PermissionState permissionState = installPermStates.get(i); 14881 if (!usedPermissions.contains(permissionState.getName())) { 14882 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14883 if (bp != null) { 14884 permissionsState.revokeInstallPermission(bp); 14885 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14886 PackageManager.MASK_PERMISSION_FLAGS, 0); 14887 } 14888 } 14889 } 14890 14891 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14892 14893 // Prune runtime permissions 14894 for (int userId : allUserIds) { 14895 List<PermissionState> runtimePermStates = permissionsState 14896 .getRuntimePermissionStates(userId); 14897 final int runtimePermCount = runtimePermStates.size(); 14898 for (int i = runtimePermCount - 1; i >= 0; i--) { 14899 PermissionState permissionState = runtimePermStates.get(i); 14900 if (!usedPermissions.contains(permissionState.getName())) { 14901 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14902 if (bp != null) { 14903 permissionsState.revokeRuntimePermission(bp, userId); 14904 permissionsState.updatePermissionFlags(bp, userId, 14905 PackageManager.MASK_PERMISSION_FLAGS, 0); 14906 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14907 runtimePermissionChangedUserIds, userId); 14908 } 14909 } 14910 } 14911 } 14912 14913 return runtimePermissionChangedUserIds; 14914 } 14915 14916 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14917 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14918 // Update the parent package setting 14919 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14920 res, user); 14921 // Update the child packages setting 14922 final int childCount = (newPackage.childPackages != null) 14923 ? newPackage.childPackages.size() : 0; 14924 for (int i = 0; i < childCount; i++) { 14925 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14926 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14927 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14928 childRes.origUsers, childRes, user); 14929 } 14930 } 14931 14932 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14933 String installerPackageName, int[] allUsers, int[] installedForUsers, 14934 PackageInstalledInfo res, UserHandle user) { 14935 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14936 14937 String pkgName = newPackage.packageName; 14938 synchronized (mPackages) { 14939 //write settings. the installStatus will be incomplete at this stage. 14940 //note that the new package setting would have already been 14941 //added to mPackages. It hasn't been persisted yet. 14942 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14943 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14944 mSettings.writeLPr(); 14945 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14946 } 14947 14948 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14949 synchronized (mPackages) { 14950 updatePermissionsLPw(newPackage.packageName, newPackage, 14951 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14952 ? UPDATE_PERMISSIONS_ALL : 0)); 14953 // For system-bundled packages, we assume that installing an upgraded version 14954 // of the package implies that the user actually wants to run that new code, 14955 // so we enable the package. 14956 PackageSetting ps = mSettings.mPackages.get(pkgName); 14957 final int userId = user.getIdentifier(); 14958 if (ps != null) { 14959 if (isSystemApp(newPackage)) { 14960 if (DEBUG_INSTALL) { 14961 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14962 } 14963 // Enable system package for requested users 14964 if (res.origUsers != null) { 14965 for (int origUserId : res.origUsers) { 14966 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14967 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14968 origUserId, installerPackageName); 14969 } 14970 } 14971 } 14972 // Also convey the prior install/uninstall state 14973 if (allUsers != null && installedForUsers != null) { 14974 for (int currentUserId : allUsers) { 14975 final boolean installed = ArrayUtils.contains( 14976 installedForUsers, currentUserId); 14977 if (DEBUG_INSTALL) { 14978 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14979 } 14980 ps.setInstalled(installed, currentUserId); 14981 } 14982 // these install state changes will be persisted in the 14983 // upcoming call to mSettings.writeLPr(). 14984 } 14985 } 14986 // It's implied that when a user requests installation, they want the app to be 14987 // installed and enabled. 14988 if (userId != UserHandle.USER_ALL) { 14989 ps.setInstalled(true, userId); 14990 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14991 } 14992 } 14993 res.name = pkgName; 14994 res.uid = newPackage.applicationInfo.uid; 14995 res.pkg = newPackage; 14996 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14997 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14998 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14999 //to update install status 15000 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15001 mSettings.writeLPr(); 15002 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15003 } 15004 15005 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15006 } 15007 15008 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 15009 try { 15010 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 15011 installPackageLI(args, res); 15012 } finally { 15013 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15014 } 15015 } 15016 15017 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 15018 final int installFlags = args.installFlags; 15019 final String installerPackageName = args.installerPackageName; 15020 final String volumeUuid = args.volumeUuid; 15021 final File tmpPackageFile = new File(args.getCodePath()); 15022 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 15023 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 15024 || (args.volumeUuid != null)); 15025 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 15026 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 15027 boolean replace = false; 15028 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 15029 if (args.move != null) { 15030 // moving a complete application; perform an initial scan on the new install location 15031 scanFlags |= SCAN_INITIAL; 15032 } 15033 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 15034 scanFlags |= SCAN_DONT_KILL_APP; 15035 } 15036 15037 // Result object to be returned 15038 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15039 15040 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 15041 15042 // Sanity check 15043 if (ephemeral && (forwardLocked || onExternal)) { 15044 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 15045 + " external=" + onExternal); 15046 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15047 return; 15048 } 15049 15050 // Retrieve PackageSettings and parse package 15051 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 15052 | PackageParser.PARSE_ENFORCE_CODE 15053 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 15054 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 15055 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 15056 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 15057 PackageParser pp = new PackageParser(); 15058 pp.setSeparateProcesses(mSeparateProcesses); 15059 pp.setDisplayMetrics(mMetrics); 15060 15061 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 15062 final PackageParser.Package pkg; 15063 try { 15064 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 15065 } catch (PackageParserException e) { 15066 res.setError("Failed parse during installPackageLI", e); 15067 return; 15068 } finally { 15069 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15070 } 15071 15072 // If we are installing a clustered package add results for the children 15073 if (pkg.childPackages != null) { 15074 synchronized (mPackages) { 15075 final int childCount = pkg.childPackages.size(); 15076 for (int i = 0; i < childCount; i++) { 15077 PackageParser.Package childPkg = pkg.childPackages.get(i); 15078 PackageInstalledInfo childRes = new PackageInstalledInfo(); 15079 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15080 childRes.pkg = childPkg; 15081 childRes.name = childPkg.packageName; 15082 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15083 if (childPs != null) { 15084 childRes.origUsers = childPs.queryInstalledUsers( 15085 sUserManager.getUserIds(), true); 15086 } 15087 if ((mPackages.containsKey(childPkg.packageName))) { 15088 childRes.removedInfo = new PackageRemovedInfo(); 15089 childRes.removedInfo.removedPackage = childPkg.packageName; 15090 } 15091 if (res.addedChildPackages == null) { 15092 res.addedChildPackages = new ArrayMap<>(); 15093 } 15094 res.addedChildPackages.put(childPkg.packageName, childRes); 15095 } 15096 } 15097 } 15098 15099 // If package doesn't declare API override, mark that we have an install 15100 // time CPU ABI override. 15101 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15102 pkg.cpuAbiOverride = args.abiOverride; 15103 } 15104 15105 String pkgName = res.name = pkg.packageName; 15106 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15107 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15108 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15109 return; 15110 } 15111 } 15112 15113 try { 15114 // either use what we've been given or parse directly from the APK 15115 if (args.certificates != null) { 15116 try { 15117 PackageParser.populateCertificates(pkg, args.certificates); 15118 } catch (PackageParserException e) { 15119 // there was something wrong with the certificates we were given; 15120 // try to pull them from the APK 15121 PackageParser.collectCertificates(pkg, parseFlags); 15122 } 15123 } else { 15124 PackageParser.collectCertificates(pkg, parseFlags); 15125 } 15126 } catch (PackageParserException e) { 15127 res.setError("Failed collect during installPackageLI", e); 15128 return; 15129 } 15130 15131 // Get rid of all references to package scan path via parser. 15132 pp = null; 15133 String oldCodePath = null; 15134 boolean systemApp = false; 15135 synchronized (mPackages) { 15136 // Check if installing already existing package 15137 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15138 String oldName = mSettings.mRenamedPackages.get(pkgName); 15139 if (pkg.mOriginalPackages != null 15140 && pkg.mOriginalPackages.contains(oldName) 15141 && mPackages.containsKey(oldName)) { 15142 // This package is derived from an original package, 15143 // and this device has been updating from that original 15144 // name. We must continue using the original name, so 15145 // rename the new package here. 15146 pkg.setPackageName(oldName); 15147 pkgName = pkg.packageName; 15148 replace = true; 15149 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15150 + oldName + " pkgName=" + pkgName); 15151 } else if (mPackages.containsKey(pkgName)) { 15152 // This package, under its official name, already exists 15153 // on the device; we should replace it. 15154 replace = true; 15155 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15156 } 15157 15158 // Child packages are installed through the parent package 15159 if (pkg.parentPackage != null) { 15160 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15161 "Package " + pkg.packageName + " is child of package " 15162 + pkg.parentPackage.parentPackage + ". Child packages " 15163 + "can be updated only through the parent package."); 15164 return; 15165 } 15166 15167 if (replace) { 15168 // Prevent apps opting out from runtime permissions 15169 PackageParser.Package oldPackage = mPackages.get(pkgName); 15170 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15171 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15172 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15173 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15174 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15175 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15176 + " doesn't support runtime permissions but the old" 15177 + " target SDK " + oldTargetSdk + " does."); 15178 return; 15179 } 15180 15181 // Prevent installing of child packages 15182 if (oldPackage.parentPackage != null) { 15183 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15184 "Package " + pkg.packageName + " is child of package " 15185 + oldPackage.parentPackage + ". Child packages " 15186 + "can be updated only through the parent package."); 15187 return; 15188 } 15189 } 15190 } 15191 15192 PackageSetting ps = mSettings.mPackages.get(pkgName); 15193 if (ps != null) { 15194 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15195 15196 // Quick sanity check that we're signed correctly if updating; 15197 // we'll check this again later when scanning, but we want to 15198 // bail early here before tripping over redefined permissions. 15199 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15200 if (!checkUpgradeKeySetLP(ps, pkg)) { 15201 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15202 + pkg.packageName + " upgrade keys do not match the " 15203 + "previously installed version"); 15204 return; 15205 } 15206 } else { 15207 try { 15208 verifySignaturesLP(ps, pkg); 15209 } catch (PackageManagerException e) { 15210 res.setError(e.error, e.getMessage()); 15211 return; 15212 } 15213 } 15214 15215 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15216 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15217 systemApp = (ps.pkg.applicationInfo.flags & 15218 ApplicationInfo.FLAG_SYSTEM) != 0; 15219 } 15220 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15221 } 15222 15223 // Check whether the newly-scanned package wants to define an already-defined perm 15224 int N = pkg.permissions.size(); 15225 for (int i = N-1; i >= 0; i--) { 15226 PackageParser.Permission perm = pkg.permissions.get(i); 15227 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15228 if (bp != null) { 15229 // If the defining package is signed with our cert, it's okay. This 15230 // also includes the "updating the same package" case, of course. 15231 // "updating same package" could also involve key-rotation. 15232 final boolean sigsOk; 15233 if (bp.sourcePackage.equals(pkg.packageName) 15234 && (bp.packageSetting instanceof PackageSetting) 15235 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15236 scanFlags))) { 15237 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15238 } else { 15239 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15240 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15241 } 15242 if (!sigsOk) { 15243 // If the owning package is the system itself, we log but allow 15244 // install to proceed; we fail the install on all other permission 15245 // redefinitions. 15246 if (!bp.sourcePackage.equals("android")) { 15247 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15248 + pkg.packageName + " attempting to redeclare permission " 15249 + perm.info.name + " already owned by " + bp.sourcePackage); 15250 res.origPermission = perm.info.name; 15251 res.origPackage = bp.sourcePackage; 15252 return; 15253 } else { 15254 Slog.w(TAG, "Package " + pkg.packageName 15255 + " attempting to redeclare system permission " 15256 + perm.info.name + "; ignoring new declaration"); 15257 pkg.permissions.remove(i); 15258 } 15259 } 15260 } 15261 } 15262 } 15263 15264 if (systemApp) { 15265 if (onExternal) { 15266 // Abort update; system app can't be replaced with app on sdcard 15267 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15268 "Cannot install updates to system apps on sdcard"); 15269 return; 15270 } else if (ephemeral) { 15271 // Abort update; system app can't be replaced with an ephemeral app 15272 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15273 "Cannot update a system app with an ephemeral app"); 15274 return; 15275 } 15276 } 15277 15278 if (args.move != null) { 15279 // We did an in-place move, so dex is ready to roll 15280 scanFlags |= SCAN_NO_DEX; 15281 scanFlags |= SCAN_MOVE; 15282 15283 synchronized (mPackages) { 15284 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15285 if (ps == null) { 15286 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15287 "Missing settings for moved package " + pkgName); 15288 } 15289 15290 // We moved the entire application as-is, so bring over the 15291 // previously derived ABI information. 15292 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15293 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15294 } 15295 15296 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15297 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15298 scanFlags |= SCAN_NO_DEX; 15299 15300 try { 15301 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15302 args.abiOverride : pkg.cpuAbiOverride); 15303 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15304 true /* extract libs */); 15305 } catch (PackageManagerException pme) { 15306 Slog.e(TAG, "Error deriving application ABI", pme); 15307 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15308 return; 15309 } 15310 15311 // Shared libraries for the package need to be updated. 15312 synchronized (mPackages) { 15313 try { 15314 updateSharedLibrariesLPw(pkg, null); 15315 } catch (PackageManagerException e) { 15316 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15317 } 15318 } 15319 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15320 // Do not run PackageDexOptimizer through the local performDexOpt 15321 // method because `pkg` may not be in `mPackages` yet. 15322 // 15323 // Also, don't fail application installs if the dexopt step fails. 15324 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15325 null /* instructionSets */, false /* checkProfiles */, 15326 getCompilerFilterForReason(REASON_INSTALL), 15327 getOrCreateCompilerPackageStats(pkg)); 15328 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15329 15330 // Notify BackgroundDexOptService that the package has been changed. 15331 // If this is an update of a package which used to fail to compile, 15332 // BDOS will remove it from its blacklist. 15333 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15334 } 15335 15336 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15337 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15338 return; 15339 } 15340 15341 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15342 15343 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15344 "installPackageLI")) { 15345 if (replace) { 15346 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15347 installerPackageName, res); 15348 } else { 15349 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15350 args.user, installerPackageName, volumeUuid, res); 15351 } 15352 } 15353 synchronized (mPackages) { 15354 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15355 if (ps != null) { 15356 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15357 } 15358 15359 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15360 for (int i = 0; i < childCount; i++) { 15361 PackageParser.Package childPkg = pkg.childPackages.get(i); 15362 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15363 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15364 if (childPs != null) { 15365 childRes.newUsers = childPs.queryInstalledUsers( 15366 sUserManager.getUserIds(), true); 15367 } 15368 } 15369 } 15370 } 15371 15372 private void startIntentFilterVerifications(int userId, boolean replacing, 15373 PackageParser.Package pkg) { 15374 if (mIntentFilterVerifierComponent == null) { 15375 Slog.w(TAG, "No IntentFilter verification will not be done as " 15376 + "there is no IntentFilterVerifier available!"); 15377 return; 15378 } 15379 15380 final int verifierUid = getPackageUid( 15381 mIntentFilterVerifierComponent.getPackageName(), 15382 MATCH_DEBUG_TRIAGED_MISSING, 15383 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15384 15385 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15386 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15387 mHandler.sendMessage(msg); 15388 15389 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15390 for (int i = 0; i < childCount; i++) { 15391 PackageParser.Package childPkg = pkg.childPackages.get(i); 15392 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15393 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15394 mHandler.sendMessage(msg); 15395 } 15396 } 15397 15398 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15399 PackageParser.Package pkg) { 15400 int size = pkg.activities.size(); 15401 if (size == 0) { 15402 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15403 "No activity, so no need to verify any IntentFilter!"); 15404 return; 15405 } 15406 15407 final boolean hasDomainURLs = hasDomainURLs(pkg); 15408 if (!hasDomainURLs) { 15409 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15410 "No domain URLs, so no need to verify any IntentFilter!"); 15411 return; 15412 } 15413 15414 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15415 + " if any IntentFilter from the " + size 15416 + " Activities needs verification ..."); 15417 15418 int count = 0; 15419 final String packageName = pkg.packageName; 15420 15421 synchronized (mPackages) { 15422 // If this is a new install and we see that we've already run verification for this 15423 // package, we have nothing to do: it means the state was restored from backup. 15424 if (!replacing) { 15425 IntentFilterVerificationInfo ivi = 15426 mSettings.getIntentFilterVerificationLPr(packageName); 15427 if (ivi != null) { 15428 if (DEBUG_DOMAIN_VERIFICATION) { 15429 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15430 + ivi.getStatusString()); 15431 } 15432 return; 15433 } 15434 } 15435 15436 // If any filters need to be verified, then all need to be. 15437 boolean needToVerify = false; 15438 for (PackageParser.Activity a : pkg.activities) { 15439 for (ActivityIntentInfo filter : a.intents) { 15440 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15441 if (DEBUG_DOMAIN_VERIFICATION) { 15442 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15443 } 15444 needToVerify = true; 15445 break; 15446 } 15447 } 15448 } 15449 15450 if (needToVerify) { 15451 final int verificationId = mIntentFilterVerificationToken++; 15452 for (PackageParser.Activity a : pkg.activities) { 15453 for (ActivityIntentInfo filter : a.intents) { 15454 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15455 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15456 "Verification needed for IntentFilter:" + filter.toString()); 15457 mIntentFilterVerifier.addOneIntentFilterVerification( 15458 verifierUid, userId, verificationId, filter, packageName); 15459 count++; 15460 } 15461 } 15462 } 15463 } 15464 } 15465 15466 if (count > 0) { 15467 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15468 + " IntentFilter verification" + (count > 1 ? "s" : "") 15469 + " for userId:" + userId); 15470 mIntentFilterVerifier.startVerifications(userId); 15471 } else { 15472 if (DEBUG_DOMAIN_VERIFICATION) { 15473 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15474 } 15475 } 15476 } 15477 15478 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15479 final ComponentName cn = filter.activity.getComponentName(); 15480 final String packageName = cn.getPackageName(); 15481 15482 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15483 packageName); 15484 if (ivi == null) { 15485 return true; 15486 } 15487 int status = ivi.getStatus(); 15488 switch (status) { 15489 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15490 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15491 return true; 15492 15493 default: 15494 // Nothing to do 15495 return false; 15496 } 15497 } 15498 15499 private static boolean isMultiArch(ApplicationInfo info) { 15500 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15501 } 15502 15503 private static boolean isExternal(PackageParser.Package pkg) { 15504 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15505 } 15506 15507 private static boolean isExternal(PackageSetting ps) { 15508 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15509 } 15510 15511 private static boolean isEphemeral(PackageParser.Package pkg) { 15512 return pkg.applicationInfo.isEphemeralApp(); 15513 } 15514 15515 private static boolean isEphemeral(PackageSetting ps) { 15516 return ps.pkg != null && isEphemeral(ps.pkg); 15517 } 15518 15519 private static boolean isSystemApp(PackageParser.Package pkg) { 15520 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15521 } 15522 15523 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15524 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15525 } 15526 15527 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15528 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15529 } 15530 15531 private static boolean isSystemApp(PackageSetting ps) { 15532 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15533 } 15534 15535 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15536 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15537 } 15538 15539 private int packageFlagsToInstallFlags(PackageSetting ps) { 15540 int installFlags = 0; 15541 if (isEphemeral(ps)) { 15542 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15543 } 15544 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15545 // This existing package was an external ASEC install when we have 15546 // the external flag without a UUID 15547 installFlags |= PackageManager.INSTALL_EXTERNAL; 15548 } 15549 if (ps.isForwardLocked()) { 15550 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15551 } 15552 return installFlags; 15553 } 15554 15555 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15556 if (isExternal(pkg)) { 15557 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15558 return StorageManager.UUID_PRIMARY_PHYSICAL; 15559 } else { 15560 return pkg.volumeUuid; 15561 } 15562 } else { 15563 return StorageManager.UUID_PRIVATE_INTERNAL; 15564 } 15565 } 15566 15567 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15568 if (isExternal(pkg)) { 15569 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15570 return mSettings.getExternalVersion(); 15571 } else { 15572 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15573 } 15574 } else { 15575 return mSettings.getInternalVersion(); 15576 } 15577 } 15578 15579 private void deleteTempPackageFiles() { 15580 final FilenameFilter filter = new FilenameFilter() { 15581 public boolean accept(File dir, String name) { 15582 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15583 } 15584 }; 15585 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15586 file.delete(); 15587 } 15588 } 15589 15590 @Override 15591 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15592 int flags) { 15593 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15594 flags); 15595 } 15596 15597 @Override 15598 public void deletePackage(final String packageName, 15599 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15600 mContext.enforceCallingOrSelfPermission( 15601 android.Manifest.permission.DELETE_PACKAGES, null); 15602 Preconditions.checkNotNull(packageName); 15603 Preconditions.checkNotNull(observer); 15604 final int uid = Binder.getCallingUid(); 15605 if (!isOrphaned(packageName) 15606 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 15607 try { 15608 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 15609 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 15610 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 15611 observer.onUserActionRequired(intent); 15612 } catch (RemoteException re) { 15613 } 15614 return; 15615 } 15616 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15617 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15618 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15619 mContext.enforceCallingOrSelfPermission( 15620 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15621 "deletePackage for user " + userId); 15622 } 15623 15624 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15625 try { 15626 observer.onPackageDeleted(packageName, 15627 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15628 } catch (RemoteException re) { 15629 } 15630 return; 15631 } 15632 15633 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15634 try { 15635 observer.onPackageDeleted(packageName, 15636 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15637 } catch (RemoteException re) { 15638 } 15639 return; 15640 } 15641 15642 if (DEBUG_REMOVE) { 15643 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15644 + " deleteAllUsers: " + deleteAllUsers ); 15645 } 15646 // Queue up an async operation since the package deletion may take a little while. 15647 mHandler.post(new Runnable() { 15648 public void run() { 15649 mHandler.removeCallbacks(this); 15650 int returnCode; 15651 if (!deleteAllUsers) { 15652 returnCode = deletePackageX(packageName, userId, deleteFlags); 15653 } else { 15654 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15655 // If nobody is blocking uninstall, proceed with delete for all users 15656 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15657 returnCode = deletePackageX(packageName, userId, deleteFlags); 15658 } else { 15659 // Otherwise uninstall individually for users with blockUninstalls=false 15660 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15661 for (int userId : users) { 15662 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15663 returnCode = deletePackageX(packageName, userId, userFlags); 15664 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15665 Slog.w(TAG, "Package delete failed for user " + userId 15666 + ", returnCode " + returnCode); 15667 } 15668 } 15669 } 15670 // The app has only been marked uninstalled for certain users. 15671 // We still need to report that delete was blocked 15672 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15673 } 15674 } 15675 try { 15676 observer.onPackageDeleted(packageName, returnCode, null); 15677 } catch (RemoteException e) { 15678 Log.i(TAG, "Observer no longer exists."); 15679 } //end catch 15680 } //end run 15681 }); 15682 } 15683 15684 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 15685 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 15686 || callingUid == Process.SYSTEM_UID) { 15687 return true; 15688 } 15689 final int callingUserId = UserHandle.getUserId(callingUid); 15690 // If the caller installed the pkgName, then allow it to silently uninstall. 15691 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 15692 return true; 15693 } 15694 15695 // Allow package verifier to silently uninstall. 15696 if (mRequiredVerifierPackage != null && 15697 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 15698 return true; 15699 } 15700 15701 // Allow package uninstaller to silently uninstall. 15702 if (mRequiredUninstallerPackage != null && 15703 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 15704 return true; 15705 } 15706 15707 // Allow storage manager to silently uninstall. 15708 if (mStorageManagerPackage != null && 15709 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 15710 return true; 15711 } 15712 return false; 15713 } 15714 15715 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15716 int[] result = EMPTY_INT_ARRAY; 15717 for (int userId : userIds) { 15718 if (getBlockUninstallForUser(packageName, userId)) { 15719 result = ArrayUtils.appendInt(result, userId); 15720 } 15721 } 15722 return result; 15723 } 15724 15725 @Override 15726 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15727 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15728 } 15729 15730 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15731 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15732 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15733 try { 15734 if (dpm != null) { 15735 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15736 /* callingUserOnly =*/ false); 15737 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15738 : deviceOwnerComponentName.getPackageName(); 15739 // Does the package contains the device owner? 15740 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15741 // this check is probably not needed, since DO should be registered as a device 15742 // admin on some user too. (Original bug for this: b/17657954) 15743 if (packageName.equals(deviceOwnerPackageName)) { 15744 return true; 15745 } 15746 // Does it contain a device admin for any user? 15747 int[] users; 15748 if (userId == UserHandle.USER_ALL) { 15749 users = sUserManager.getUserIds(); 15750 } else { 15751 users = new int[]{userId}; 15752 } 15753 for (int i = 0; i < users.length; ++i) { 15754 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15755 return true; 15756 } 15757 } 15758 } 15759 } catch (RemoteException e) { 15760 } 15761 return false; 15762 } 15763 15764 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15765 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15766 } 15767 15768 /** 15769 * This method is an internal method that could be get invoked either 15770 * to delete an installed package or to clean up a failed installation. 15771 * After deleting an installed package, a broadcast is sent to notify any 15772 * listeners that the package has been removed. For cleaning up a failed 15773 * installation, the broadcast is not necessary since the package's 15774 * installation wouldn't have sent the initial broadcast either 15775 * The key steps in deleting a package are 15776 * deleting the package information in internal structures like mPackages, 15777 * deleting the packages base directories through installd 15778 * updating mSettings to reflect current status 15779 * persisting settings for later use 15780 * sending a broadcast if necessary 15781 */ 15782 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15783 final PackageRemovedInfo info = new PackageRemovedInfo(); 15784 final boolean res; 15785 15786 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15787 ? UserHandle.USER_ALL : userId; 15788 15789 if (isPackageDeviceAdmin(packageName, removeUser)) { 15790 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15791 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15792 } 15793 15794 PackageSetting uninstalledPs = null; 15795 15796 // for the uninstall-updates case and restricted profiles, remember the per- 15797 // user handle installed state 15798 int[] allUsers; 15799 synchronized (mPackages) { 15800 uninstalledPs = mSettings.mPackages.get(packageName); 15801 if (uninstalledPs == null) { 15802 Slog.w(TAG, "Not removing non-existent package " + packageName); 15803 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15804 } 15805 allUsers = sUserManager.getUserIds(); 15806 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15807 } 15808 15809 final int freezeUser; 15810 if (isUpdatedSystemApp(uninstalledPs) 15811 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15812 // We're downgrading a system app, which will apply to all users, so 15813 // freeze them all during the downgrade 15814 freezeUser = UserHandle.USER_ALL; 15815 } else { 15816 freezeUser = removeUser; 15817 } 15818 15819 synchronized (mInstallLock) { 15820 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15821 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15822 deleteFlags, "deletePackageX")) { 15823 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15824 deleteFlags | REMOVE_CHATTY, info, true, null); 15825 } 15826 synchronized (mPackages) { 15827 if (res) { 15828 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15829 } 15830 } 15831 } 15832 15833 if (res) { 15834 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15835 info.sendPackageRemovedBroadcasts(killApp); 15836 info.sendSystemPackageUpdatedBroadcasts(); 15837 info.sendSystemPackageAppearedBroadcasts(); 15838 } 15839 // Force a gc here. 15840 Runtime.getRuntime().gc(); 15841 // Delete the resources here after sending the broadcast to let 15842 // other processes clean up before deleting resources. 15843 if (info.args != null) { 15844 synchronized (mInstallLock) { 15845 info.args.doPostDeleteLI(true); 15846 } 15847 } 15848 15849 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15850 } 15851 15852 class PackageRemovedInfo { 15853 String removedPackage; 15854 int uid = -1; 15855 int removedAppId = -1; 15856 int[] origUsers; 15857 int[] removedUsers = null; 15858 boolean isRemovedPackageSystemUpdate = false; 15859 boolean isUpdate; 15860 boolean dataRemoved; 15861 boolean removedForAllUsers; 15862 // Clean up resources deleted packages. 15863 InstallArgs args = null; 15864 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15865 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15866 15867 void sendPackageRemovedBroadcasts(boolean killApp) { 15868 sendPackageRemovedBroadcastInternal(killApp); 15869 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15870 for (int i = 0; i < childCount; i++) { 15871 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15872 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15873 } 15874 } 15875 15876 void sendSystemPackageUpdatedBroadcasts() { 15877 if (isRemovedPackageSystemUpdate) { 15878 sendSystemPackageUpdatedBroadcastsInternal(); 15879 final int childCount = (removedChildPackages != null) 15880 ? removedChildPackages.size() : 0; 15881 for (int i = 0; i < childCount; i++) { 15882 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15883 if (childInfo.isRemovedPackageSystemUpdate) { 15884 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15885 } 15886 } 15887 } 15888 } 15889 15890 void sendSystemPackageAppearedBroadcasts() { 15891 final int packageCount = (appearedChildPackages != null) 15892 ? appearedChildPackages.size() : 0; 15893 for (int i = 0; i < packageCount; i++) { 15894 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15895 for (int userId : installedInfo.newUsers) { 15896 sendPackageAddedForUser(installedInfo.name, true, 15897 UserHandle.getAppId(installedInfo.uid), userId); 15898 } 15899 } 15900 } 15901 15902 private void sendSystemPackageUpdatedBroadcastsInternal() { 15903 Bundle extras = new Bundle(2); 15904 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15905 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15906 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15907 extras, 0, null, null, null); 15908 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15909 extras, 0, null, null, null); 15910 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15911 null, 0, removedPackage, null, null); 15912 } 15913 15914 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15915 Bundle extras = new Bundle(2); 15916 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15917 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15918 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15919 if (isUpdate || isRemovedPackageSystemUpdate) { 15920 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15921 } 15922 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15923 if (removedPackage != null) { 15924 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15925 extras, 0, null, null, removedUsers); 15926 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15927 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15928 removedPackage, extras, 0, null, null, removedUsers); 15929 } 15930 } 15931 if (removedAppId >= 0) { 15932 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15933 removedUsers); 15934 } 15935 } 15936 } 15937 15938 /* 15939 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15940 * flag is not set, the data directory is removed as well. 15941 * make sure this flag is set for partially installed apps. If not its meaningless to 15942 * delete a partially installed application. 15943 */ 15944 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15945 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15946 String packageName = ps.name; 15947 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15948 // Retrieve object to delete permissions for shared user later on 15949 final PackageParser.Package deletedPkg; 15950 final PackageSetting deletedPs; 15951 // reader 15952 synchronized (mPackages) { 15953 deletedPkg = mPackages.get(packageName); 15954 deletedPs = mSettings.mPackages.get(packageName); 15955 if (outInfo != null) { 15956 outInfo.removedPackage = packageName; 15957 outInfo.removedUsers = deletedPs != null 15958 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15959 : null; 15960 } 15961 } 15962 15963 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15964 15965 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15966 final PackageParser.Package resolvedPkg; 15967 if (deletedPkg != null) { 15968 resolvedPkg = deletedPkg; 15969 } else { 15970 // We don't have a parsed package when it lives on an ejected 15971 // adopted storage device, so fake something together 15972 resolvedPkg = new PackageParser.Package(ps.name); 15973 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15974 } 15975 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15976 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15977 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15978 if (outInfo != null) { 15979 outInfo.dataRemoved = true; 15980 } 15981 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15982 } 15983 15984 // writer 15985 synchronized (mPackages) { 15986 if (deletedPs != null) { 15987 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15988 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15989 clearDefaultBrowserIfNeeded(packageName); 15990 if (outInfo != null) { 15991 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15992 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15993 } 15994 updatePermissionsLPw(deletedPs.name, null, 0); 15995 if (deletedPs.sharedUser != null) { 15996 // Remove permissions associated with package. Since runtime 15997 // permissions are per user we have to kill the removed package 15998 // or packages running under the shared user of the removed 15999 // package if revoking the permissions requested only by the removed 16000 // package is successful and this causes a change in gids. 16001 for (int userId : UserManagerService.getInstance().getUserIds()) { 16002 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 16003 userId); 16004 if (userIdToKill == UserHandle.USER_ALL 16005 || userIdToKill >= UserHandle.USER_SYSTEM) { 16006 // If gids changed for this user, kill all affected packages. 16007 mHandler.post(new Runnable() { 16008 @Override 16009 public void run() { 16010 // This has to happen with no lock held. 16011 killApplication(deletedPs.name, deletedPs.appId, 16012 KILL_APP_REASON_GIDS_CHANGED); 16013 } 16014 }); 16015 break; 16016 } 16017 } 16018 } 16019 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 16020 } 16021 // make sure to preserve per-user disabled state if this removal was just 16022 // a downgrade of a system app to the factory package 16023 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 16024 if (DEBUG_REMOVE) { 16025 Slog.d(TAG, "Propagating install state across downgrade"); 16026 } 16027 for (int userId : allUserHandles) { 16028 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16029 if (DEBUG_REMOVE) { 16030 Slog.d(TAG, " user " + userId + " => " + installed); 16031 } 16032 ps.setInstalled(installed, userId); 16033 } 16034 } 16035 } 16036 // can downgrade to reader 16037 if (writeSettings) { 16038 // Save settings now 16039 mSettings.writeLPr(); 16040 } 16041 } 16042 if (outInfo != null) { 16043 // A user ID was deleted here. Go through all users and remove it 16044 // from KeyStore. 16045 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 16046 } 16047 } 16048 16049 static boolean locationIsPrivileged(File path) { 16050 try { 16051 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 16052 .getCanonicalPath(); 16053 return path.getCanonicalPath().startsWith(privilegedAppDir); 16054 } catch (IOException e) { 16055 Slog.e(TAG, "Unable to access code path " + path); 16056 } 16057 return false; 16058 } 16059 16060 /* 16061 * Tries to delete system package. 16062 */ 16063 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 16064 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 16065 boolean writeSettings) { 16066 if (deletedPs.parentPackageName != null) { 16067 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 16068 return false; 16069 } 16070 16071 final boolean applyUserRestrictions 16072 = (allUserHandles != null) && (outInfo.origUsers != null); 16073 final PackageSetting disabledPs; 16074 // Confirm if the system package has been updated 16075 // An updated system app can be deleted. This will also have to restore 16076 // the system pkg from system partition 16077 // reader 16078 synchronized (mPackages) { 16079 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 16080 } 16081 16082 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 16083 + " disabledPs=" + disabledPs); 16084 16085 if (disabledPs == null) { 16086 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 16087 return false; 16088 } else if (DEBUG_REMOVE) { 16089 Slog.d(TAG, "Deleting system pkg from data partition"); 16090 } 16091 16092 if (DEBUG_REMOVE) { 16093 if (applyUserRestrictions) { 16094 Slog.d(TAG, "Remembering install states:"); 16095 for (int userId : allUserHandles) { 16096 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 16097 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 16098 } 16099 } 16100 } 16101 16102 // Delete the updated package 16103 outInfo.isRemovedPackageSystemUpdate = true; 16104 if (outInfo.removedChildPackages != null) { 16105 final int childCount = (deletedPs.childPackageNames != null) 16106 ? deletedPs.childPackageNames.size() : 0; 16107 for (int i = 0; i < childCount; i++) { 16108 String childPackageName = deletedPs.childPackageNames.get(i); 16109 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16110 .contains(childPackageName)) { 16111 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16112 childPackageName); 16113 if (childInfo != null) { 16114 childInfo.isRemovedPackageSystemUpdate = true; 16115 } 16116 } 16117 } 16118 } 16119 16120 if (disabledPs.versionCode < deletedPs.versionCode) { 16121 // Delete data for downgrades 16122 flags &= ~PackageManager.DELETE_KEEP_DATA; 16123 } else { 16124 // Preserve data by setting flag 16125 flags |= PackageManager.DELETE_KEEP_DATA; 16126 } 16127 16128 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16129 outInfo, writeSettings, disabledPs.pkg); 16130 if (!ret) { 16131 return false; 16132 } 16133 16134 // writer 16135 synchronized (mPackages) { 16136 // Reinstate the old system package 16137 enableSystemPackageLPw(disabledPs.pkg); 16138 // Remove any native libraries from the upgraded package. 16139 removeNativeBinariesLI(deletedPs); 16140 } 16141 16142 // Install the system package 16143 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16144 int parseFlags = mDefParseFlags 16145 | PackageParser.PARSE_MUST_BE_APK 16146 | PackageParser.PARSE_IS_SYSTEM 16147 | PackageParser.PARSE_IS_SYSTEM_DIR; 16148 if (locationIsPrivileged(disabledPs.codePath)) { 16149 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16150 } 16151 16152 final PackageParser.Package newPkg; 16153 try { 16154 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 16155 } catch (PackageManagerException e) { 16156 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16157 + e.getMessage()); 16158 return false; 16159 } 16160 try { 16161 // update shared libraries for the newly re-installed system package 16162 updateSharedLibrariesLPw(newPkg, null); 16163 } catch (PackageManagerException e) { 16164 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16165 } 16166 16167 prepareAppDataAfterInstallLIF(newPkg); 16168 16169 // writer 16170 synchronized (mPackages) { 16171 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16172 16173 // Propagate the permissions state as we do not want to drop on the floor 16174 // runtime permissions. The update permissions method below will take 16175 // care of removing obsolete permissions and grant install permissions. 16176 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16177 updatePermissionsLPw(newPkg.packageName, newPkg, 16178 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16179 16180 if (applyUserRestrictions) { 16181 if (DEBUG_REMOVE) { 16182 Slog.d(TAG, "Propagating install state across reinstall"); 16183 } 16184 for (int userId : allUserHandles) { 16185 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16186 if (DEBUG_REMOVE) { 16187 Slog.d(TAG, " user " + userId + " => " + installed); 16188 } 16189 ps.setInstalled(installed, userId); 16190 16191 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16192 } 16193 // Regardless of writeSettings we need to ensure that this restriction 16194 // state propagation is persisted 16195 mSettings.writeAllUsersPackageRestrictionsLPr(); 16196 } 16197 // can downgrade to reader here 16198 if (writeSettings) { 16199 mSettings.writeLPr(); 16200 } 16201 } 16202 return true; 16203 } 16204 16205 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16206 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16207 PackageRemovedInfo outInfo, boolean writeSettings, 16208 PackageParser.Package replacingPackage) { 16209 synchronized (mPackages) { 16210 if (outInfo != null) { 16211 outInfo.uid = ps.appId; 16212 } 16213 16214 if (outInfo != null && outInfo.removedChildPackages != null) { 16215 final int childCount = (ps.childPackageNames != null) 16216 ? ps.childPackageNames.size() : 0; 16217 for (int i = 0; i < childCount; i++) { 16218 String childPackageName = ps.childPackageNames.get(i); 16219 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16220 if (childPs == null) { 16221 return false; 16222 } 16223 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16224 childPackageName); 16225 if (childInfo != null) { 16226 childInfo.uid = childPs.appId; 16227 } 16228 } 16229 } 16230 } 16231 16232 // Delete package data from internal structures and also remove data if flag is set 16233 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16234 16235 // Delete the child packages data 16236 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16237 for (int i = 0; i < childCount; i++) { 16238 PackageSetting childPs; 16239 synchronized (mPackages) { 16240 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16241 } 16242 if (childPs != null) { 16243 PackageRemovedInfo childOutInfo = (outInfo != null 16244 && outInfo.removedChildPackages != null) 16245 ? outInfo.removedChildPackages.get(childPs.name) : null; 16246 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16247 && (replacingPackage != null 16248 && !replacingPackage.hasChildPackage(childPs.name)) 16249 ? flags & ~DELETE_KEEP_DATA : flags; 16250 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16251 deleteFlags, writeSettings); 16252 } 16253 } 16254 16255 // Delete application code and resources only for parent packages 16256 if (ps.parentPackageName == null) { 16257 if (deleteCodeAndResources && (outInfo != null)) { 16258 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16259 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16260 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16261 } 16262 } 16263 16264 return true; 16265 } 16266 16267 @Override 16268 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16269 int userId) { 16270 mContext.enforceCallingOrSelfPermission( 16271 android.Manifest.permission.DELETE_PACKAGES, null); 16272 synchronized (mPackages) { 16273 PackageSetting ps = mSettings.mPackages.get(packageName); 16274 if (ps == null) { 16275 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16276 return false; 16277 } 16278 if (!ps.getInstalled(userId)) { 16279 // Can't block uninstall for an app that is not installed or enabled. 16280 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16281 return false; 16282 } 16283 ps.setBlockUninstall(blockUninstall, userId); 16284 mSettings.writePackageRestrictionsLPr(userId); 16285 } 16286 return true; 16287 } 16288 16289 @Override 16290 public boolean getBlockUninstallForUser(String packageName, int userId) { 16291 synchronized (mPackages) { 16292 PackageSetting ps = mSettings.mPackages.get(packageName); 16293 if (ps == null) { 16294 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16295 return false; 16296 } 16297 return ps.getBlockUninstall(userId); 16298 } 16299 } 16300 16301 @Override 16302 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16303 int callingUid = Binder.getCallingUid(); 16304 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16305 throw new SecurityException( 16306 "setRequiredForSystemUser can only be run by the system or root"); 16307 } 16308 synchronized (mPackages) { 16309 PackageSetting ps = mSettings.mPackages.get(packageName); 16310 if (ps == null) { 16311 Log.w(TAG, "Package doesn't exist: " + packageName); 16312 return false; 16313 } 16314 if (systemUserApp) { 16315 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16316 } else { 16317 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16318 } 16319 mSettings.writeLPr(); 16320 } 16321 return true; 16322 } 16323 16324 /* 16325 * This method handles package deletion in general 16326 */ 16327 private boolean deletePackageLIF(String packageName, UserHandle user, 16328 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16329 PackageRemovedInfo outInfo, boolean writeSettings, 16330 PackageParser.Package replacingPackage) { 16331 if (packageName == null) { 16332 Slog.w(TAG, "Attempt to delete null packageName."); 16333 return false; 16334 } 16335 16336 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16337 16338 PackageSetting ps; 16339 16340 synchronized (mPackages) { 16341 ps = mSettings.mPackages.get(packageName); 16342 if (ps == null) { 16343 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16344 return false; 16345 } 16346 16347 if (ps.parentPackageName != null && (!isSystemApp(ps) 16348 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16349 if (DEBUG_REMOVE) { 16350 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16351 + ((user == null) ? UserHandle.USER_ALL : user)); 16352 } 16353 final int removedUserId = (user != null) ? user.getIdentifier() 16354 : UserHandle.USER_ALL; 16355 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16356 return false; 16357 } 16358 markPackageUninstalledForUserLPw(ps, user); 16359 scheduleWritePackageRestrictionsLocked(user); 16360 return true; 16361 } 16362 } 16363 16364 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16365 && user.getIdentifier() != UserHandle.USER_ALL)) { 16366 // The caller is asking that the package only be deleted for a single 16367 // user. To do this, we just mark its uninstalled state and delete 16368 // its data. If this is a system app, we only allow this to happen if 16369 // they have set the special DELETE_SYSTEM_APP which requests different 16370 // semantics than normal for uninstalling system apps. 16371 markPackageUninstalledForUserLPw(ps, user); 16372 16373 if (!isSystemApp(ps)) { 16374 // Do not uninstall the APK if an app should be cached 16375 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16376 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16377 // Other user still have this package installed, so all 16378 // we need to do is clear this user's data and save that 16379 // it is uninstalled. 16380 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16381 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16382 return false; 16383 } 16384 scheduleWritePackageRestrictionsLocked(user); 16385 return true; 16386 } else { 16387 // We need to set it back to 'installed' so the uninstall 16388 // broadcasts will be sent correctly. 16389 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16390 ps.setInstalled(true, user.getIdentifier()); 16391 } 16392 } else { 16393 // This is a system app, so we assume that the 16394 // other users still have this package installed, so all 16395 // we need to do is clear this user's data and save that 16396 // it is uninstalled. 16397 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16398 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16399 return false; 16400 } 16401 scheduleWritePackageRestrictionsLocked(user); 16402 return true; 16403 } 16404 } 16405 16406 // If we are deleting a composite package for all users, keep track 16407 // of result for each child. 16408 if (ps.childPackageNames != null && outInfo != null) { 16409 synchronized (mPackages) { 16410 final int childCount = ps.childPackageNames.size(); 16411 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16412 for (int i = 0; i < childCount; i++) { 16413 String childPackageName = ps.childPackageNames.get(i); 16414 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16415 childInfo.removedPackage = childPackageName; 16416 outInfo.removedChildPackages.put(childPackageName, childInfo); 16417 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16418 if (childPs != null) { 16419 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16420 } 16421 } 16422 } 16423 } 16424 16425 boolean ret = false; 16426 if (isSystemApp(ps)) { 16427 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16428 // When an updated system application is deleted we delete the existing resources 16429 // as well and fall back to existing code in system partition 16430 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16431 } else { 16432 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16433 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16434 outInfo, writeSettings, replacingPackage); 16435 } 16436 16437 // Take a note whether we deleted the package for all users 16438 if (outInfo != null) { 16439 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16440 if (outInfo.removedChildPackages != null) { 16441 synchronized (mPackages) { 16442 final int childCount = outInfo.removedChildPackages.size(); 16443 for (int i = 0; i < childCount; i++) { 16444 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16445 if (childInfo != null) { 16446 childInfo.removedForAllUsers = mPackages.get( 16447 childInfo.removedPackage) == null; 16448 } 16449 } 16450 } 16451 } 16452 // If we uninstalled an update to a system app there may be some 16453 // child packages that appeared as they are declared in the system 16454 // app but were not declared in the update. 16455 if (isSystemApp(ps)) { 16456 synchronized (mPackages) { 16457 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16458 final int childCount = (updatedPs.childPackageNames != null) 16459 ? updatedPs.childPackageNames.size() : 0; 16460 for (int i = 0; i < childCount; i++) { 16461 String childPackageName = updatedPs.childPackageNames.get(i); 16462 if (outInfo.removedChildPackages == null 16463 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16464 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16465 if (childPs == null) { 16466 continue; 16467 } 16468 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16469 installRes.name = childPackageName; 16470 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16471 installRes.pkg = mPackages.get(childPackageName); 16472 installRes.uid = childPs.pkg.applicationInfo.uid; 16473 if (outInfo.appearedChildPackages == null) { 16474 outInfo.appearedChildPackages = new ArrayMap<>(); 16475 } 16476 outInfo.appearedChildPackages.put(childPackageName, installRes); 16477 } 16478 } 16479 } 16480 } 16481 } 16482 16483 return ret; 16484 } 16485 16486 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16487 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16488 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16489 for (int nextUserId : userIds) { 16490 if (DEBUG_REMOVE) { 16491 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16492 } 16493 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16494 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16495 false /*hidden*/, false /*suspended*/, null, null, null, 16496 false /*blockUninstall*/, 16497 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16498 } 16499 } 16500 16501 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16502 PackageRemovedInfo outInfo) { 16503 final PackageParser.Package pkg; 16504 synchronized (mPackages) { 16505 pkg = mPackages.get(ps.name); 16506 } 16507 16508 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16509 : new int[] {userId}; 16510 for (int nextUserId : userIds) { 16511 if (DEBUG_REMOVE) { 16512 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16513 + nextUserId); 16514 } 16515 16516 destroyAppDataLIF(pkg, userId, 16517 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16518 destroyAppProfilesLIF(pkg, userId); 16519 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16520 schedulePackageCleaning(ps.name, nextUserId, false); 16521 synchronized (mPackages) { 16522 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16523 scheduleWritePackageRestrictionsLocked(nextUserId); 16524 } 16525 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16526 } 16527 } 16528 16529 if (outInfo != null) { 16530 outInfo.removedPackage = ps.name; 16531 outInfo.removedAppId = ps.appId; 16532 outInfo.removedUsers = userIds; 16533 } 16534 16535 return true; 16536 } 16537 16538 private final class ClearStorageConnection implements ServiceConnection { 16539 IMediaContainerService mContainerService; 16540 16541 @Override 16542 public void onServiceConnected(ComponentName name, IBinder service) { 16543 synchronized (this) { 16544 mContainerService = IMediaContainerService.Stub.asInterface(service); 16545 notifyAll(); 16546 } 16547 } 16548 16549 @Override 16550 public void onServiceDisconnected(ComponentName name) { 16551 } 16552 } 16553 16554 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16555 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16556 16557 final boolean mounted; 16558 if (Environment.isExternalStorageEmulated()) { 16559 mounted = true; 16560 } else { 16561 final String status = Environment.getExternalStorageState(); 16562 16563 mounted = status.equals(Environment.MEDIA_MOUNTED) 16564 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16565 } 16566 16567 if (!mounted) { 16568 return; 16569 } 16570 16571 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16572 int[] users; 16573 if (userId == UserHandle.USER_ALL) { 16574 users = sUserManager.getUserIds(); 16575 } else { 16576 users = new int[] { userId }; 16577 } 16578 final ClearStorageConnection conn = new ClearStorageConnection(); 16579 if (mContext.bindServiceAsUser( 16580 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16581 try { 16582 for (int curUser : users) { 16583 long timeout = SystemClock.uptimeMillis() + 5000; 16584 synchronized (conn) { 16585 long now; 16586 while (conn.mContainerService == null && 16587 (now = SystemClock.uptimeMillis()) < timeout) { 16588 try { 16589 conn.wait(timeout - now); 16590 } catch (InterruptedException e) { 16591 } 16592 } 16593 } 16594 if (conn.mContainerService == null) { 16595 return; 16596 } 16597 16598 final UserEnvironment userEnv = new UserEnvironment(curUser); 16599 clearDirectory(conn.mContainerService, 16600 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16601 if (allData) { 16602 clearDirectory(conn.mContainerService, 16603 userEnv.buildExternalStorageAppDataDirs(packageName)); 16604 clearDirectory(conn.mContainerService, 16605 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16606 } 16607 } 16608 } finally { 16609 mContext.unbindService(conn); 16610 } 16611 } 16612 } 16613 16614 @Override 16615 public void clearApplicationProfileData(String packageName) { 16616 enforceSystemOrRoot("Only the system can clear all profile data"); 16617 16618 final PackageParser.Package pkg; 16619 synchronized (mPackages) { 16620 pkg = mPackages.get(packageName); 16621 } 16622 16623 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16624 synchronized (mInstallLock) { 16625 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16626 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16627 true /* removeBaseMarker */); 16628 } 16629 } 16630 } 16631 16632 @Override 16633 public void clearApplicationUserData(final String packageName, 16634 final IPackageDataObserver observer, final int userId) { 16635 mContext.enforceCallingOrSelfPermission( 16636 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16637 16638 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16639 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16640 16641 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16642 throw new SecurityException("Cannot clear data for a protected package: " 16643 + packageName); 16644 } 16645 // Queue up an async operation since the package deletion may take a little while. 16646 mHandler.post(new Runnable() { 16647 public void run() { 16648 mHandler.removeCallbacks(this); 16649 final boolean succeeded; 16650 try (PackageFreezer freezer = freezePackage(packageName, 16651 "clearApplicationUserData")) { 16652 synchronized (mInstallLock) { 16653 succeeded = clearApplicationUserDataLIF(packageName, userId); 16654 } 16655 clearExternalStorageDataSync(packageName, userId, true); 16656 } 16657 if (succeeded) { 16658 // invoke DeviceStorageMonitor's update method to clear any notifications 16659 DeviceStorageMonitorInternal dsm = LocalServices 16660 .getService(DeviceStorageMonitorInternal.class); 16661 if (dsm != null) { 16662 dsm.checkMemory(); 16663 } 16664 } 16665 if(observer != null) { 16666 try { 16667 observer.onRemoveCompleted(packageName, succeeded); 16668 } catch (RemoteException e) { 16669 Log.i(TAG, "Observer no longer exists."); 16670 } 16671 } //end if observer 16672 } //end run 16673 }); 16674 } 16675 16676 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16677 if (packageName == null) { 16678 Slog.w(TAG, "Attempt to delete null packageName."); 16679 return false; 16680 } 16681 16682 // Try finding details about the requested package 16683 PackageParser.Package pkg; 16684 synchronized (mPackages) { 16685 pkg = mPackages.get(packageName); 16686 if (pkg == null) { 16687 final PackageSetting ps = mSettings.mPackages.get(packageName); 16688 if (ps != null) { 16689 pkg = ps.pkg; 16690 } 16691 } 16692 16693 if (pkg == null) { 16694 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16695 return false; 16696 } 16697 16698 PackageSetting ps = (PackageSetting) pkg.mExtras; 16699 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16700 } 16701 16702 clearAppDataLIF(pkg, userId, 16703 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16704 16705 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16706 removeKeystoreDataIfNeeded(userId, appId); 16707 16708 UserManagerInternal umInternal = getUserManagerInternal(); 16709 final int flags; 16710 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16711 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16712 } else if (umInternal.isUserRunning(userId)) { 16713 flags = StorageManager.FLAG_STORAGE_DE; 16714 } else { 16715 flags = 0; 16716 } 16717 prepareAppDataContentsLIF(pkg, userId, flags); 16718 16719 return true; 16720 } 16721 16722 /** 16723 * Reverts user permission state changes (permissions and flags) in 16724 * all packages for a given user. 16725 * 16726 * @param userId The device user for which to do a reset. 16727 */ 16728 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16729 final int packageCount = mPackages.size(); 16730 for (int i = 0; i < packageCount; i++) { 16731 PackageParser.Package pkg = mPackages.valueAt(i); 16732 PackageSetting ps = (PackageSetting) pkg.mExtras; 16733 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16734 } 16735 } 16736 16737 private void resetNetworkPolicies(int userId) { 16738 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16739 } 16740 16741 /** 16742 * Reverts user permission state changes (permissions and flags). 16743 * 16744 * @param ps The package for which to reset. 16745 * @param userId The device user for which to do a reset. 16746 */ 16747 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16748 final PackageSetting ps, final int userId) { 16749 if (ps.pkg == null) { 16750 return; 16751 } 16752 16753 // These are flags that can change base on user actions. 16754 final int userSettableMask = FLAG_PERMISSION_USER_SET 16755 | FLAG_PERMISSION_USER_FIXED 16756 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16757 | FLAG_PERMISSION_REVIEW_REQUIRED; 16758 16759 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16760 | FLAG_PERMISSION_POLICY_FIXED; 16761 16762 boolean writeInstallPermissions = false; 16763 boolean writeRuntimePermissions = false; 16764 16765 final int permissionCount = ps.pkg.requestedPermissions.size(); 16766 for (int i = 0; i < permissionCount; i++) { 16767 String permission = ps.pkg.requestedPermissions.get(i); 16768 16769 BasePermission bp = mSettings.mPermissions.get(permission); 16770 if (bp == null) { 16771 continue; 16772 } 16773 16774 // If shared user we just reset the state to which only this app contributed. 16775 if (ps.sharedUser != null) { 16776 boolean used = false; 16777 final int packageCount = ps.sharedUser.packages.size(); 16778 for (int j = 0; j < packageCount; j++) { 16779 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16780 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16781 && pkg.pkg.requestedPermissions.contains(permission)) { 16782 used = true; 16783 break; 16784 } 16785 } 16786 if (used) { 16787 continue; 16788 } 16789 } 16790 16791 PermissionsState permissionsState = ps.getPermissionsState(); 16792 16793 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16794 16795 // Always clear the user settable flags. 16796 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16797 bp.name) != null; 16798 // If permission review is enabled and this is a legacy app, mark the 16799 // permission as requiring a review as this is the initial state. 16800 int flags = 0; 16801 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) 16802 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16803 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16804 } 16805 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16806 if (hasInstallState) { 16807 writeInstallPermissions = true; 16808 } else { 16809 writeRuntimePermissions = true; 16810 } 16811 } 16812 16813 // Below is only runtime permission handling. 16814 if (!bp.isRuntime()) { 16815 continue; 16816 } 16817 16818 // Never clobber system or policy. 16819 if ((oldFlags & policyOrSystemFlags) != 0) { 16820 continue; 16821 } 16822 16823 // If this permission was granted by default, make sure it is. 16824 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16825 if (permissionsState.grantRuntimePermission(bp, userId) 16826 != PERMISSION_OPERATION_FAILURE) { 16827 writeRuntimePermissions = true; 16828 } 16829 // If permission review is enabled the permissions for a legacy apps 16830 // are represented as constantly granted runtime ones, so don't revoke. 16831 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16832 // Otherwise, reset the permission. 16833 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16834 switch (revokeResult) { 16835 case PERMISSION_OPERATION_SUCCESS: 16836 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16837 writeRuntimePermissions = true; 16838 final int appId = ps.appId; 16839 mHandler.post(new Runnable() { 16840 @Override 16841 public void run() { 16842 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16843 } 16844 }); 16845 } break; 16846 } 16847 } 16848 } 16849 16850 // Synchronously write as we are taking permissions away. 16851 if (writeRuntimePermissions) { 16852 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16853 } 16854 16855 // Synchronously write as we are taking permissions away. 16856 if (writeInstallPermissions) { 16857 mSettings.writeLPr(); 16858 } 16859 } 16860 16861 /** 16862 * Remove entries from the keystore daemon. Will only remove it if the 16863 * {@code appId} is valid. 16864 */ 16865 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16866 if (appId < 0) { 16867 return; 16868 } 16869 16870 final KeyStore keyStore = KeyStore.getInstance(); 16871 if (keyStore != null) { 16872 if (userId == UserHandle.USER_ALL) { 16873 for (final int individual : sUserManager.getUserIds()) { 16874 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16875 } 16876 } else { 16877 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16878 } 16879 } else { 16880 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16881 } 16882 } 16883 16884 @Override 16885 public void deleteApplicationCacheFiles(final String packageName, 16886 final IPackageDataObserver observer) { 16887 final int userId = UserHandle.getCallingUserId(); 16888 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16889 } 16890 16891 @Override 16892 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16893 final IPackageDataObserver observer) { 16894 mContext.enforceCallingOrSelfPermission( 16895 android.Manifest.permission.DELETE_CACHE_FILES, null); 16896 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16897 /* requireFullPermission= */ true, /* checkShell= */ false, 16898 "delete application cache files"); 16899 16900 final PackageParser.Package pkg; 16901 synchronized (mPackages) { 16902 pkg = mPackages.get(packageName); 16903 } 16904 16905 // Queue up an async operation since the package deletion may take a little while. 16906 mHandler.post(new Runnable() { 16907 public void run() { 16908 synchronized (mInstallLock) { 16909 final int flags = StorageManager.FLAG_STORAGE_DE 16910 | StorageManager.FLAG_STORAGE_CE; 16911 // We're only clearing cache files, so we don't care if the 16912 // app is unfrozen and still able to run 16913 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16914 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16915 } 16916 clearExternalStorageDataSync(packageName, userId, false); 16917 if (observer != null) { 16918 try { 16919 observer.onRemoveCompleted(packageName, true); 16920 } catch (RemoteException e) { 16921 Log.i(TAG, "Observer no longer exists."); 16922 } 16923 } 16924 } 16925 }); 16926 } 16927 16928 @Override 16929 public void getPackageSizeInfo(final String packageName, int userHandle, 16930 final IPackageStatsObserver observer) { 16931 mContext.enforceCallingOrSelfPermission( 16932 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16933 if (packageName == null) { 16934 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16935 } 16936 16937 PackageStats stats = new PackageStats(packageName, userHandle); 16938 16939 /* 16940 * Queue up an async operation since the package measurement may take a 16941 * little while. 16942 */ 16943 Message msg = mHandler.obtainMessage(INIT_COPY); 16944 msg.obj = new MeasureParams(stats, observer); 16945 mHandler.sendMessage(msg); 16946 } 16947 16948 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16949 final PackageSetting ps; 16950 synchronized (mPackages) { 16951 ps = mSettings.mPackages.get(packageName); 16952 if (ps == null) { 16953 Slog.w(TAG, "Failed to find settings for " + packageName); 16954 return false; 16955 } 16956 } 16957 16958 final String[] packageNames = { packageName }; 16959 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 16960 final String[] codePaths = { ps.codePathString }; 16961 16962 try { 16963 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 16964 ps.appId, ceDataInodes, codePaths, stats); 16965 16966 // For now, ignore code size of packages on system partition 16967 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16968 stats.codeSize = 0; 16969 } 16970 16971 // External clients expect these to be tracked separately 16972 stats.dataSize -= stats.cacheSize; 16973 16974 } catch (InstallerException e) { 16975 Slog.w(TAG, String.valueOf(e)); 16976 return false; 16977 } 16978 16979 return true; 16980 } 16981 16982 private int getUidTargetSdkVersionLockedLPr(int uid) { 16983 Object obj = mSettings.getUserIdLPr(uid); 16984 if (obj instanceof SharedUserSetting) { 16985 final SharedUserSetting sus = (SharedUserSetting) obj; 16986 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16987 final Iterator<PackageSetting> it = sus.packages.iterator(); 16988 while (it.hasNext()) { 16989 final PackageSetting ps = it.next(); 16990 if (ps.pkg != null) { 16991 int v = ps.pkg.applicationInfo.targetSdkVersion; 16992 if (v < vers) vers = v; 16993 } 16994 } 16995 return vers; 16996 } else if (obj instanceof PackageSetting) { 16997 final PackageSetting ps = (PackageSetting) obj; 16998 if (ps.pkg != null) { 16999 return ps.pkg.applicationInfo.targetSdkVersion; 17000 } 17001 } 17002 return Build.VERSION_CODES.CUR_DEVELOPMENT; 17003 } 17004 17005 @Override 17006 public void addPreferredActivity(IntentFilter filter, int match, 17007 ComponentName[] set, ComponentName activity, int userId) { 17008 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17009 "Adding preferred"); 17010 } 17011 17012 private void addPreferredActivityInternal(IntentFilter filter, int match, 17013 ComponentName[] set, ComponentName activity, boolean always, int userId, 17014 String opname) { 17015 // writer 17016 int callingUid = Binder.getCallingUid(); 17017 enforceCrossUserPermission(callingUid, userId, 17018 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 17019 if (filter.countActions() == 0) { 17020 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17021 return; 17022 } 17023 synchronized (mPackages) { 17024 if (mContext.checkCallingOrSelfPermission( 17025 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17026 != PackageManager.PERMISSION_GRANTED) { 17027 if (getUidTargetSdkVersionLockedLPr(callingUid) 17028 < Build.VERSION_CODES.FROYO) { 17029 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 17030 + callingUid); 17031 return; 17032 } 17033 mContext.enforceCallingOrSelfPermission( 17034 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17035 } 17036 17037 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 17038 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 17039 + userId + ":"); 17040 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17041 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 17042 scheduleWritePackageRestrictionsLocked(userId); 17043 postPreferredActivityChangedBroadcast(userId); 17044 } 17045 } 17046 17047 private void postPreferredActivityChangedBroadcast(int userId) { 17048 mHandler.post(() -> { 17049 final IActivityManager am = ActivityManagerNative.getDefault(); 17050 if (am == null) { 17051 return; 17052 } 17053 17054 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 17055 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17056 try { 17057 am.broadcastIntent(null, intent, null, null, 17058 0, null, null, null, android.app.AppOpsManager.OP_NONE, 17059 null, false, false, userId); 17060 } catch (RemoteException e) { 17061 } 17062 }); 17063 } 17064 17065 @Override 17066 public void replacePreferredActivity(IntentFilter filter, int match, 17067 ComponentName[] set, ComponentName activity, int userId) { 17068 if (filter.countActions() != 1) { 17069 throw new IllegalArgumentException( 17070 "replacePreferredActivity expects filter to have only 1 action."); 17071 } 17072 if (filter.countDataAuthorities() != 0 17073 || filter.countDataPaths() != 0 17074 || filter.countDataSchemes() > 1 17075 || filter.countDataTypes() != 0) { 17076 throw new IllegalArgumentException( 17077 "replacePreferredActivity expects filter to have no data authorities, " + 17078 "paths, or types; and at most one scheme."); 17079 } 17080 17081 final int callingUid = Binder.getCallingUid(); 17082 enforceCrossUserPermission(callingUid, userId, 17083 true /* requireFullPermission */, false /* checkShell */, 17084 "replace preferred activity"); 17085 synchronized (mPackages) { 17086 if (mContext.checkCallingOrSelfPermission( 17087 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17088 != PackageManager.PERMISSION_GRANTED) { 17089 if (getUidTargetSdkVersionLockedLPr(callingUid) 17090 < Build.VERSION_CODES.FROYO) { 17091 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 17092 + Binder.getCallingUid()); 17093 return; 17094 } 17095 mContext.enforceCallingOrSelfPermission( 17096 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17097 } 17098 17099 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17100 if (pir != null) { 17101 // Get all of the existing entries that exactly match this filter. 17102 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 17103 if (existing != null && existing.size() == 1) { 17104 PreferredActivity cur = existing.get(0); 17105 if (DEBUG_PREFERRED) { 17106 Slog.i(TAG, "Checking replace of preferred:"); 17107 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17108 if (!cur.mPref.mAlways) { 17109 Slog.i(TAG, " -- CUR; not mAlways!"); 17110 } else { 17111 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 17112 Slog.i(TAG, " -- CUR: mSet=" 17113 + Arrays.toString(cur.mPref.mSetComponents)); 17114 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 17115 Slog.i(TAG, " -- NEW: mMatch=" 17116 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 17117 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17118 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17119 } 17120 } 17121 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17122 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17123 && cur.mPref.sameSet(set)) { 17124 // Setting the preferred activity to what it happens to be already 17125 if (DEBUG_PREFERRED) { 17126 Slog.i(TAG, "Replacing with same preferred activity " 17127 + cur.mPref.mShortComponent + " for user " 17128 + userId + ":"); 17129 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17130 } 17131 return; 17132 } 17133 } 17134 17135 if (existing != null) { 17136 if (DEBUG_PREFERRED) { 17137 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17138 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17139 } 17140 for (int i = 0; i < existing.size(); i++) { 17141 PreferredActivity pa = existing.get(i); 17142 if (DEBUG_PREFERRED) { 17143 Slog.i(TAG, "Removing existing preferred activity " 17144 + pa.mPref.mComponent + ":"); 17145 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17146 } 17147 pir.removeFilter(pa); 17148 } 17149 } 17150 } 17151 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17152 "Replacing preferred"); 17153 } 17154 } 17155 17156 @Override 17157 public void clearPackagePreferredActivities(String packageName) { 17158 final int uid = Binder.getCallingUid(); 17159 // writer 17160 synchronized (mPackages) { 17161 PackageParser.Package pkg = mPackages.get(packageName); 17162 if (pkg == null || pkg.applicationInfo.uid != uid) { 17163 if (mContext.checkCallingOrSelfPermission( 17164 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17165 != PackageManager.PERMISSION_GRANTED) { 17166 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17167 < Build.VERSION_CODES.FROYO) { 17168 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17169 + Binder.getCallingUid()); 17170 return; 17171 } 17172 mContext.enforceCallingOrSelfPermission( 17173 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17174 } 17175 } 17176 17177 int user = UserHandle.getCallingUserId(); 17178 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17179 scheduleWritePackageRestrictionsLocked(user); 17180 } 17181 } 17182 } 17183 17184 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17185 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17186 ArrayList<PreferredActivity> removed = null; 17187 boolean changed = false; 17188 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17189 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17190 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17191 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17192 continue; 17193 } 17194 Iterator<PreferredActivity> it = pir.filterIterator(); 17195 while (it.hasNext()) { 17196 PreferredActivity pa = it.next(); 17197 // Mark entry for removal only if it matches the package name 17198 // and the entry is of type "always". 17199 if (packageName == null || 17200 (pa.mPref.mComponent.getPackageName().equals(packageName) 17201 && pa.mPref.mAlways)) { 17202 if (removed == null) { 17203 removed = new ArrayList<PreferredActivity>(); 17204 } 17205 removed.add(pa); 17206 } 17207 } 17208 if (removed != null) { 17209 for (int j=0; j<removed.size(); j++) { 17210 PreferredActivity pa = removed.get(j); 17211 pir.removeFilter(pa); 17212 } 17213 changed = true; 17214 } 17215 } 17216 if (changed) { 17217 postPreferredActivityChangedBroadcast(userId); 17218 } 17219 return changed; 17220 } 17221 17222 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17223 private void clearIntentFilterVerificationsLPw(int userId) { 17224 final int packageCount = mPackages.size(); 17225 for (int i = 0; i < packageCount; i++) { 17226 PackageParser.Package pkg = mPackages.valueAt(i); 17227 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17228 } 17229 } 17230 17231 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17232 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17233 if (userId == UserHandle.USER_ALL) { 17234 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17235 sUserManager.getUserIds())) { 17236 for (int oneUserId : sUserManager.getUserIds()) { 17237 scheduleWritePackageRestrictionsLocked(oneUserId); 17238 } 17239 } 17240 } else { 17241 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17242 scheduleWritePackageRestrictionsLocked(userId); 17243 } 17244 } 17245 } 17246 17247 void clearDefaultBrowserIfNeeded(String packageName) { 17248 for (int oneUserId : sUserManager.getUserIds()) { 17249 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17250 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17251 if (packageName.equals(defaultBrowserPackageName)) { 17252 setDefaultBrowserPackageName(null, oneUserId); 17253 } 17254 } 17255 } 17256 17257 @Override 17258 public void resetApplicationPreferences(int userId) { 17259 mContext.enforceCallingOrSelfPermission( 17260 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17261 final long identity = Binder.clearCallingIdentity(); 17262 // writer 17263 try { 17264 synchronized (mPackages) { 17265 clearPackagePreferredActivitiesLPw(null, userId); 17266 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17267 // TODO: We have to reset the default SMS and Phone. This requires 17268 // significant refactoring to keep all default apps in the package 17269 // manager (cleaner but more work) or have the services provide 17270 // callbacks to the package manager to request a default app reset. 17271 applyFactoryDefaultBrowserLPw(userId); 17272 clearIntentFilterVerificationsLPw(userId); 17273 primeDomainVerificationsLPw(userId); 17274 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17275 scheduleWritePackageRestrictionsLocked(userId); 17276 } 17277 resetNetworkPolicies(userId); 17278 } finally { 17279 Binder.restoreCallingIdentity(identity); 17280 } 17281 } 17282 17283 @Override 17284 public int getPreferredActivities(List<IntentFilter> outFilters, 17285 List<ComponentName> outActivities, String packageName) { 17286 17287 int num = 0; 17288 final int userId = UserHandle.getCallingUserId(); 17289 // reader 17290 synchronized (mPackages) { 17291 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17292 if (pir != null) { 17293 final Iterator<PreferredActivity> it = pir.filterIterator(); 17294 while (it.hasNext()) { 17295 final PreferredActivity pa = it.next(); 17296 if (packageName == null 17297 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17298 && pa.mPref.mAlways)) { 17299 if (outFilters != null) { 17300 outFilters.add(new IntentFilter(pa)); 17301 } 17302 if (outActivities != null) { 17303 outActivities.add(pa.mPref.mComponent); 17304 } 17305 } 17306 } 17307 } 17308 } 17309 17310 return num; 17311 } 17312 17313 @Override 17314 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17315 int userId) { 17316 int callingUid = Binder.getCallingUid(); 17317 if (callingUid != Process.SYSTEM_UID) { 17318 throw new SecurityException( 17319 "addPersistentPreferredActivity can only be run by the system"); 17320 } 17321 if (filter.countActions() == 0) { 17322 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17323 return; 17324 } 17325 synchronized (mPackages) { 17326 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17327 ":"); 17328 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17329 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17330 new PersistentPreferredActivity(filter, activity)); 17331 scheduleWritePackageRestrictionsLocked(userId); 17332 postPreferredActivityChangedBroadcast(userId); 17333 } 17334 } 17335 17336 @Override 17337 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17338 int callingUid = Binder.getCallingUid(); 17339 if (callingUid != Process.SYSTEM_UID) { 17340 throw new SecurityException( 17341 "clearPackagePersistentPreferredActivities can only be run by the system"); 17342 } 17343 ArrayList<PersistentPreferredActivity> removed = null; 17344 boolean changed = false; 17345 synchronized (mPackages) { 17346 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17347 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17348 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17349 .valueAt(i); 17350 if (userId != thisUserId) { 17351 continue; 17352 } 17353 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17354 while (it.hasNext()) { 17355 PersistentPreferredActivity ppa = it.next(); 17356 // Mark entry for removal only if it matches the package name. 17357 if (ppa.mComponent.getPackageName().equals(packageName)) { 17358 if (removed == null) { 17359 removed = new ArrayList<PersistentPreferredActivity>(); 17360 } 17361 removed.add(ppa); 17362 } 17363 } 17364 if (removed != null) { 17365 for (int j=0; j<removed.size(); j++) { 17366 PersistentPreferredActivity ppa = removed.get(j); 17367 ppir.removeFilter(ppa); 17368 } 17369 changed = true; 17370 } 17371 } 17372 17373 if (changed) { 17374 scheduleWritePackageRestrictionsLocked(userId); 17375 postPreferredActivityChangedBroadcast(userId); 17376 } 17377 } 17378 } 17379 17380 /** 17381 * Common machinery for picking apart a restored XML blob and passing 17382 * it to a caller-supplied functor to be applied to the running system. 17383 */ 17384 private void restoreFromXml(XmlPullParser parser, int userId, 17385 String expectedStartTag, BlobXmlRestorer functor) 17386 throws IOException, XmlPullParserException { 17387 int type; 17388 while ((type = parser.next()) != XmlPullParser.START_TAG 17389 && type != XmlPullParser.END_DOCUMENT) { 17390 } 17391 if (type != XmlPullParser.START_TAG) { 17392 // oops didn't find a start tag?! 17393 if (DEBUG_BACKUP) { 17394 Slog.e(TAG, "Didn't find start tag during restore"); 17395 } 17396 return; 17397 } 17398Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17399 // this is supposed to be TAG_PREFERRED_BACKUP 17400 if (!expectedStartTag.equals(parser.getName())) { 17401 if (DEBUG_BACKUP) { 17402 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17403 } 17404 return; 17405 } 17406 17407 // skip interfering stuff, then we're aligned with the backing implementation 17408 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17409Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17410 functor.apply(parser, userId); 17411 } 17412 17413 private interface BlobXmlRestorer { 17414 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17415 } 17416 17417 /** 17418 * Non-Binder method, support for the backup/restore mechanism: write the 17419 * full set of preferred activities in its canonical XML format. Returns the 17420 * XML output as a byte array, or null if there is none. 17421 */ 17422 @Override 17423 public byte[] getPreferredActivityBackup(int userId) { 17424 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17425 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17426 } 17427 17428 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17429 try { 17430 final XmlSerializer serializer = new FastXmlSerializer(); 17431 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17432 serializer.startDocument(null, true); 17433 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17434 17435 synchronized (mPackages) { 17436 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17437 } 17438 17439 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17440 serializer.endDocument(); 17441 serializer.flush(); 17442 } catch (Exception e) { 17443 if (DEBUG_BACKUP) { 17444 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17445 } 17446 return null; 17447 } 17448 17449 return dataStream.toByteArray(); 17450 } 17451 17452 @Override 17453 public void restorePreferredActivities(byte[] backup, int userId) { 17454 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17455 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17456 } 17457 17458 try { 17459 final XmlPullParser parser = Xml.newPullParser(); 17460 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17461 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17462 new BlobXmlRestorer() { 17463 @Override 17464 public void apply(XmlPullParser parser, int userId) 17465 throws XmlPullParserException, IOException { 17466 synchronized (mPackages) { 17467 mSettings.readPreferredActivitiesLPw(parser, userId); 17468 } 17469 } 17470 } ); 17471 } catch (Exception e) { 17472 if (DEBUG_BACKUP) { 17473 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17474 } 17475 } 17476 } 17477 17478 /** 17479 * Non-Binder method, support for the backup/restore mechanism: write the 17480 * default browser (etc) settings in its canonical XML format. Returns the default 17481 * browser XML representation as a byte array, or null if there is none. 17482 */ 17483 @Override 17484 public byte[] getDefaultAppsBackup(int userId) { 17485 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17486 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17487 } 17488 17489 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17490 try { 17491 final XmlSerializer serializer = new FastXmlSerializer(); 17492 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17493 serializer.startDocument(null, true); 17494 serializer.startTag(null, TAG_DEFAULT_APPS); 17495 17496 synchronized (mPackages) { 17497 mSettings.writeDefaultAppsLPr(serializer, userId); 17498 } 17499 17500 serializer.endTag(null, TAG_DEFAULT_APPS); 17501 serializer.endDocument(); 17502 serializer.flush(); 17503 } catch (Exception e) { 17504 if (DEBUG_BACKUP) { 17505 Slog.e(TAG, "Unable to write default apps for backup", e); 17506 } 17507 return null; 17508 } 17509 17510 return dataStream.toByteArray(); 17511 } 17512 17513 @Override 17514 public void restoreDefaultApps(byte[] backup, int userId) { 17515 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17516 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17517 } 17518 17519 try { 17520 final XmlPullParser parser = Xml.newPullParser(); 17521 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17522 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17523 new BlobXmlRestorer() { 17524 @Override 17525 public void apply(XmlPullParser parser, int userId) 17526 throws XmlPullParserException, IOException { 17527 synchronized (mPackages) { 17528 mSettings.readDefaultAppsLPw(parser, userId); 17529 } 17530 } 17531 } ); 17532 } catch (Exception e) { 17533 if (DEBUG_BACKUP) { 17534 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17535 } 17536 } 17537 } 17538 17539 @Override 17540 public byte[] getIntentFilterVerificationBackup(int userId) { 17541 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17542 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17543 } 17544 17545 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17546 try { 17547 final XmlSerializer serializer = new FastXmlSerializer(); 17548 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17549 serializer.startDocument(null, true); 17550 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17551 17552 synchronized (mPackages) { 17553 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17554 } 17555 17556 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17557 serializer.endDocument(); 17558 serializer.flush(); 17559 } catch (Exception e) { 17560 if (DEBUG_BACKUP) { 17561 Slog.e(TAG, "Unable to write default apps for backup", e); 17562 } 17563 return null; 17564 } 17565 17566 return dataStream.toByteArray(); 17567 } 17568 17569 @Override 17570 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17571 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17572 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17573 } 17574 17575 try { 17576 final XmlPullParser parser = Xml.newPullParser(); 17577 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17578 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17579 new BlobXmlRestorer() { 17580 @Override 17581 public void apply(XmlPullParser parser, int userId) 17582 throws XmlPullParserException, IOException { 17583 synchronized (mPackages) { 17584 mSettings.readAllDomainVerificationsLPr(parser, userId); 17585 mSettings.writeLPr(); 17586 } 17587 } 17588 } ); 17589 } catch (Exception e) { 17590 if (DEBUG_BACKUP) { 17591 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17592 } 17593 } 17594 } 17595 17596 @Override 17597 public byte[] getPermissionGrantBackup(int userId) { 17598 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17599 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17600 } 17601 17602 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17603 try { 17604 final XmlSerializer serializer = new FastXmlSerializer(); 17605 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17606 serializer.startDocument(null, true); 17607 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17608 17609 synchronized (mPackages) { 17610 serializeRuntimePermissionGrantsLPr(serializer, userId); 17611 } 17612 17613 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17614 serializer.endDocument(); 17615 serializer.flush(); 17616 } catch (Exception e) { 17617 if (DEBUG_BACKUP) { 17618 Slog.e(TAG, "Unable to write default apps for backup", e); 17619 } 17620 return null; 17621 } 17622 17623 return dataStream.toByteArray(); 17624 } 17625 17626 @Override 17627 public void restorePermissionGrants(byte[] backup, int userId) { 17628 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17629 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17630 } 17631 17632 try { 17633 final XmlPullParser parser = Xml.newPullParser(); 17634 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17635 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17636 new BlobXmlRestorer() { 17637 @Override 17638 public void apply(XmlPullParser parser, int userId) 17639 throws XmlPullParserException, IOException { 17640 synchronized (mPackages) { 17641 processRestoredPermissionGrantsLPr(parser, userId); 17642 } 17643 } 17644 } ); 17645 } catch (Exception e) { 17646 if (DEBUG_BACKUP) { 17647 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17648 } 17649 } 17650 } 17651 17652 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17653 throws IOException { 17654 serializer.startTag(null, TAG_ALL_GRANTS); 17655 17656 final int N = mSettings.mPackages.size(); 17657 for (int i = 0; i < N; i++) { 17658 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17659 boolean pkgGrantsKnown = false; 17660 17661 PermissionsState packagePerms = ps.getPermissionsState(); 17662 17663 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17664 final int grantFlags = state.getFlags(); 17665 // only look at grants that are not system/policy fixed 17666 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17667 final boolean isGranted = state.isGranted(); 17668 // And only back up the user-twiddled state bits 17669 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17670 final String packageName = mSettings.mPackages.keyAt(i); 17671 if (!pkgGrantsKnown) { 17672 serializer.startTag(null, TAG_GRANT); 17673 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17674 pkgGrantsKnown = true; 17675 } 17676 17677 final boolean userSet = 17678 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17679 final boolean userFixed = 17680 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17681 final boolean revoke = 17682 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17683 17684 serializer.startTag(null, TAG_PERMISSION); 17685 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17686 if (isGranted) { 17687 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17688 } 17689 if (userSet) { 17690 serializer.attribute(null, ATTR_USER_SET, "true"); 17691 } 17692 if (userFixed) { 17693 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17694 } 17695 if (revoke) { 17696 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17697 } 17698 serializer.endTag(null, TAG_PERMISSION); 17699 } 17700 } 17701 } 17702 17703 if (pkgGrantsKnown) { 17704 serializer.endTag(null, TAG_GRANT); 17705 } 17706 } 17707 17708 serializer.endTag(null, TAG_ALL_GRANTS); 17709 } 17710 17711 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17712 throws XmlPullParserException, IOException { 17713 String pkgName = null; 17714 int outerDepth = parser.getDepth(); 17715 int type; 17716 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17717 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17718 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17719 continue; 17720 } 17721 17722 final String tagName = parser.getName(); 17723 if (tagName.equals(TAG_GRANT)) { 17724 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17725 if (DEBUG_BACKUP) { 17726 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17727 } 17728 } else if (tagName.equals(TAG_PERMISSION)) { 17729 17730 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17731 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17732 17733 int newFlagSet = 0; 17734 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17735 newFlagSet |= FLAG_PERMISSION_USER_SET; 17736 } 17737 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17738 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17739 } 17740 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17741 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17742 } 17743 if (DEBUG_BACKUP) { 17744 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17745 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17746 } 17747 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17748 if (ps != null) { 17749 // Already installed so we apply the grant immediately 17750 if (DEBUG_BACKUP) { 17751 Slog.v(TAG, " + already installed; applying"); 17752 } 17753 PermissionsState perms = ps.getPermissionsState(); 17754 BasePermission bp = mSettings.mPermissions.get(permName); 17755 if (bp != null) { 17756 if (isGranted) { 17757 perms.grantRuntimePermission(bp, userId); 17758 } 17759 if (newFlagSet != 0) { 17760 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17761 } 17762 } 17763 } else { 17764 // Need to wait for post-restore install to apply the grant 17765 if (DEBUG_BACKUP) { 17766 Slog.v(TAG, " - not yet installed; saving for later"); 17767 } 17768 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17769 isGranted, newFlagSet, userId); 17770 } 17771 } else { 17772 PackageManagerService.reportSettingsProblem(Log.WARN, 17773 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17774 XmlUtils.skipCurrentTag(parser); 17775 } 17776 } 17777 17778 scheduleWriteSettingsLocked(); 17779 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17780 } 17781 17782 @Override 17783 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17784 int sourceUserId, int targetUserId, int flags) { 17785 mContext.enforceCallingOrSelfPermission( 17786 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17787 int callingUid = Binder.getCallingUid(); 17788 enforceOwnerRights(ownerPackage, callingUid); 17789 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17790 if (intentFilter.countActions() == 0) { 17791 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17792 return; 17793 } 17794 synchronized (mPackages) { 17795 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17796 ownerPackage, targetUserId, flags); 17797 CrossProfileIntentResolver resolver = 17798 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17799 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17800 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17801 if (existing != null) { 17802 int size = existing.size(); 17803 for (int i = 0; i < size; i++) { 17804 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17805 return; 17806 } 17807 } 17808 } 17809 resolver.addFilter(newFilter); 17810 scheduleWritePackageRestrictionsLocked(sourceUserId); 17811 } 17812 } 17813 17814 @Override 17815 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17816 mContext.enforceCallingOrSelfPermission( 17817 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17818 int callingUid = Binder.getCallingUid(); 17819 enforceOwnerRights(ownerPackage, callingUid); 17820 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17821 synchronized (mPackages) { 17822 CrossProfileIntentResolver resolver = 17823 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17824 ArraySet<CrossProfileIntentFilter> set = 17825 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17826 for (CrossProfileIntentFilter filter : set) { 17827 if (filter.getOwnerPackage().equals(ownerPackage)) { 17828 resolver.removeFilter(filter); 17829 } 17830 } 17831 scheduleWritePackageRestrictionsLocked(sourceUserId); 17832 } 17833 } 17834 17835 // Enforcing that callingUid is owning pkg on userId 17836 private void enforceOwnerRights(String pkg, int callingUid) { 17837 // The system owns everything. 17838 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17839 return; 17840 } 17841 int callingUserId = UserHandle.getUserId(callingUid); 17842 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17843 if (pi == null) { 17844 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17845 + callingUserId); 17846 } 17847 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17848 throw new SecurityException("Calling uid " + callingUid 17849 + " does not own package " + pkg); 17850 } 17851 } 17852 17853 @Override 17854 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17855 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17856 } 17857 17858 private Intent getHomeIntent() { 17859 Intent intent = new Intent(Intent.ACTION_MAIN); 17860 intent.addCategory(Intent.CATEGORY_HOME); 17861 intent.addCategory(Intent.CATEGORY_DEFAULT); 17862 return intent; 17863 } 17864 17865 private IntentFilter getHomeFilter() { 17866 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17867 filter.addCategory(Intent.CATEGORY_HOME); 17868 filter.addCategory(Intent.CATEGORY_DEFAULT); 17869 return filter; 17870 } 17871 17872 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17873 int userId) { 17874 Intent intent = getHomeIntent(); 17875 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17876 PackageManager.GET_META_DATA, userId); 17877 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17878 true, false, false, userId); 17879 17880 allHomeCandidates.clear(); 17881 if (list != null) { 17882 for (ResolveInfo ri : list) { 17883 allHomeCandidates.add(ri); 17884 } 17885 } 17886 return (preferred == null || preferred.activityInfo == null) 17887 ? null 17888 : new ComponentName(preferred.activityInfo.packageName, 17889 preferred.activityInfo.name); 17890 } 17891 17892 @Override 17893 public void setHomeActivity(ComponentName comp, int userId) { 17894 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17895 getHomeActivitiesAsUser(homeActivities, userId); 17896 17897 boolean found = false; 17898 17899 final int size = homeActivities.size(); 17900 final ComponentName[] set = new ComponentName[size]; 17901 for (int i = 0; i < size; i++) { 17902 final ResolveInfo candidate = homeActivities.get(i); 17903 final ActivityInfo info = candidate.activityInfo; 17904 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17905 set[i] = activityName; 17906 if (!found && activityName.equals(comp)) { 17907 found = true; 17908 } 17909 } 17910 if (!found) { 17911 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17912 + userId); 17913 } 17914 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17915 set, comp, userId); 17916 } 17917 17918 private @Nullable String getSetupWizardPackageName() { 17919 final Intent intent = new Intent(Intent.ACTION_MAIN); 17920 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17921 17922 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17923 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17924 | MATCH_DISABLED_COMPONENTS, 17925 UserHandle.myUserId()); 17926 if (matches.size() == 1) { 17927 return matches.get(0).getComponentInfo().packageName; 17928 } else { 17929 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17930 + ": matches=" + matches); 17931 return null; 17932 } 17933 } 17934 17935 private @Nullable String getStorageManagerPackageName() { 17936 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 17937 17938 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17939 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17940 | MATCH_DISABLED_COMPONENTS, 17941 UserHandle.myUserId()); 17942 if (matches.size() == 1) { 17943 return matches.get(0).getComponentInfo().packageName; 17944 } else { 17945 Slog.e(TAG, "There should probably be exactly one storage manager; found " 17946 + matches.size() + ": matches=" + matches); 17947 return null; 17948 } 17949 } 17950 17951 @Override 17952 public void setApplicationEnabledSetting(String appPackageName, 17953 int newState, int flags, int userId, String callingPackage) { 17954 if (!sUserManager.exists(userId)) return; 17955 if (callingPackage == null) { 17956 callingPackage = Integer.toString(Binder.getCallingUid()); 17957 } 17958 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17959 } 17960 17961 @Override 17962 public void setComponentEnabledSetting(ComponentName componentName, 17963 int newState, int flags, int userId) { 17964 if (!sUserManager.exists(userId)) return; 17965 setEnabledSetting(componentName.getPackageName(), 17966 componentName.getClassName(), newState, flags, userId, null); 17967 } 17968 17969 private void setEnabledSetting(final String packageName, String className, int newState, 17970 final int flags, int userId, String callingPackage) { 17971 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17972 || newState == COMPONENT_ENABLED_STATE_ENABLED 17973 || newState == COMPONENT_ENABLED_STATE_DISABLED 17974 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17975 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17976 throw new IllegalArgumentException("Invalid new component state: " 17977 + newState); 17978 } 17979 PackageSetting pkgSetting; 17980 final int uid = Binder.getCallingUid(); 17981 final int permission; 17982 if (uid == Process.SYSTEM_UID) { 17983 permission = PackageManager.PERMISSION_GRANTED; 17984 } else { 17985 permission = mContext.checkCallingOrSelfPermission( 17986 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17987 } 17988 enforceCrossUserPermission(uid, userId, 17989 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17990 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17991 boolean sendNow = false; 17992 boolean isApp = (className == null); 17993 String componentName = isApp ? packageName : className; 17994 int packageUid = -1; 17995 ArrayList<String> components; 17996 17997 // writer 17998 synchronized (mPackages) { 17999 pkgSetting = mSettings.mPackages.get(packageName); 18000 if (pkgSetting == null) { 18001 if (className == null) { 18002 throw new IllegalArgumentException("Unknown package: " + packageName); 18003 } 18004 throw new IllegalArgumentException( 18005 "Unknown component: " + packageName + "/" + className); 18006 } 18007 } 18008 18009 // Limit who can change which apps 18010 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 18011 // Don't allow apps that don't have permission to modify other apps 18012 if (!allowedByPermission) { 18013 throw new SecurityException( 18014 "Permission Denial: attempt to change component state from pid=" 18015 + Binder.getCallingPid() 18016 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 18017 } 18018 // Don't allow changing protected packages. 18019 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 18020 throw new SecurityException("Cannot disable a protected package: " + packageName); 18021 } 18022 } 18023 18024 synchronized (mPackages) { 18025 if (uid == Process.SHELL_UID) { 18026 // Shell can only change whole packages between ENABLED and DISABLED_USER states 18027 int oldState = pkgSetting.getEnabled(userId); 18028 if (className == null 18029 && 18030 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 18031 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 18032 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 18033 && 18034 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18035 || newState == COMPONENT_ENABLED_STATE_DEFAULT 18036 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 18037 // ok 18038 } else { 18039 throw new SecurityException( 18040 "Shell cannot change component state for " + packageName + "/" 18041 + className + " to " + newState); 18042 } 18043 } 18044 if (className == null) { 18045 // We're dealing with an application/package level state change 18046 if (pkgSetting.getEnabled(userId) == newState) { 18047 // Nothing to do 18048 return; 18049 } 18050 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 18051 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 18052 // Don't care about who enables an app. 18053 callingPackage = null; 18054 } 18055 pkgSetting.setEnabled(newState, userId, callingPackage); 18056 // pkgSetting.pkg.mSetEnabled = newState; 18057 } else { 18058 // We're dealing with a component level state change 18059 // First, verify that this is a valid class name. 18060 PackageParser.Package pkg = pkgSetting.pkg; 18061 if (pkg == null || !pkg.hasComponentClassName(className)) { 18062 if (pkg != null && 18063 pkg.applicationInfo.targetSdkVersion >= 18064 Build.VERSION_CODES.JELLY_BEAN) { 18065 throw new IllegalArgumentException("Component class " + className 18066 + " does not exist in " + packageName); 18067 } else { 18068 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 18069 + className + " does not exist in " + packageName); 18070 } 18071 } 18072 switch (newState) { 18073 case COMPONENT_ENABLED_STATE_ENABLED: 18074 if (!pkgSetting.enableComponentLPw(className, userId)) { 18075 return; 18076 } 18077 break; 18078 case COMPONENT_ENABLED_STATE_DISABLED: 18079 if (!pkgSetting.disableComponentLPw(className, userId)) { 18080 return; 18081 } 18082 break; 18083 case COMPONENT_ENABLED_STATE_DEFAULT: 18084 if (!pkgSetting.restoreComponentLPw(className, userId)) { 18085 return; 18086 } 18087 break; 18088 default: 18089 Slog.e(TAG, "Invalid new component state: " + newState); 18090 return; 18091 } 18092 } 18093 scheduleWritePackageRestrictionsLocked(userId); 18094 components = mPendingBroadcasts.get(userId, packageName); 18095 final boolean newPackage = components == null; 18096 if (newPackage) { 18097 components = new ArrayList<String>(); 18098 } 18099 if (!components.contains(componentName)) { 18100 components.add(componentName); 18101 } 18102 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 18103 sendNow = true; 18104 // Purge entry from pending broadcast list if another one exists already 18105 // since we are sending one right away. 18106 mPendingBroadcasts.remove(userId, packageName); 18107 } else { 18108 if (newPackage) { 18109 mPendingBroadcasts.put(userId, packageName, components); 18110 } 18111 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 18112 // Schedule a message 18113 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 18114 } 18115 } 18116 } 18117 18118 long callingId = Binder.clearCallingIdentity(); 18119 try { 18120 if (sendNow) { 18121 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18122 sendPackageChangedBroadcast(packageName, 18123 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18124 } 18125 } finally { 18126 Binder.restoreCallingIdentity(callingId); 18127 } 18128 } 18129 18130 @Override 18131 public void flushPackageRestrictionsAsUser(int userId) { 18132 if (!sUserManager.exists(userId)) { 18133 return; 18134 } 18135 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18136 false /* checkShell */, "flushPackageRestrictions"); 18137 synchronized (mPackages) { 18138 mSettings.writePackageRestrictionsLPr(userId); 18139 mDirtyUsers.remove(userId); 18140 if (mDirtyUsers.isEmpty()) { 18141 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18142 } 18143 } 18144 } 18145 18146 private void sendPackageChangedBroadcast(String packageName, 18147 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18148 if (DEBUG_INSTALL) 18149 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18150 + componentNames); 18151 Bundle extras = new Bundle(4); 18152 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18153 String nameList[] = new String[componentNames.size()]; 18154 componentNames.toArray(nameList); 18155 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18156 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18157 extras.putInt(Intent.EXTRA_UID, packageUid); 18158 // If this is not reporting a change of the overall package, then only send it 18159 // to registered receivers. We don't want to launch a swath of apps for every 18160 // little component state change. 18161 final int flags = !componentNames.contains(packageName) 18162 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18163 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18164 new int[] {UserHandle.getUserId(packageUid)}); 18165 } 18166 18167 @Override 18168 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18169 if (!sUserManager.exists(userId)) return; 18170 final int uid = Binder.getCallingUid(); 18171 final int permission = mContext.checkCallingOrSelfPermission( 18172 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18173 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18174 enforceCrossUserPermission(uid, userId, 18175 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18176 // writer 18177 synchronized (mPackages) { 18178 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18179 allowedByPermission, uid, userId)) { 18180 scheduleWritePackageRestrictionsLocked(userId); 18181 } 18182 } 18183 } 18184 18185 @Override 18186 public String getInstallerPackageName(String packageName) { 18187 // reader 18188 synchronized (mPackages) { 18189 return mSettings.getInstallerPackageNameLPr(packageName); 18190 } 18191 } 18192 18193 public boolean isOrphaned(String packageName) { 18194 // reader 18195 synchronized (mPackages) { 18196 return mSettings.isOrphaned(packageName); 18197 } 18198 } 18199 18200 @Override 18201 public int getApplicationEnabledSetting(String packageName, int userId) { 18202 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18203 int uid = Binder.getCallingUid(); 18204 enforceCrossUserPermission(uid, userId, 18205 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18206 // reader 18207 synchronized (mPackages) { 18208 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18209 } 18210 } 18211 18212 @Override 18213 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18214 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18215 int uid = Binder.getCallingUid(); 18216 enforceCrossUserPermission(uid, userId, 18217 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18218 // reader 18219 synchronized (mPackages) { 18220 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18221 } 18222 } 18223 18224 @Override 18225 public void enterSafeMode() { 18226 enforceSystemOrRoot("Only the system can request entering safe mode"); 18227 18228 if (!mSystemReady) { 18229 mSafeMode = true; 18230 } 18231 } 18232 18233 @Override 18234 public void systemReady() { 18235 mSystemReady = true; 18236 18237 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18238 // disabled after already being started. 18239 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18240 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18241 18242 // Read the compatibilty setting when the system is ready. 18243 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18244 mContext.getContentResolver(), 18245 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18246 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18247 if (DEBUG_SETTINGS) { 18248 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18249 } 18250 18251 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18252 18253 synchronized (mPackages) { 18254 // Verify that all of the preferred activity components actually 18255 // exist. It is possible for applications to be updated and at 18256 // that point remove a previously declared activity component that 18257 // had been set as a preferred activity. We try to clean this up 18258 // the next time we encounter that preferred activity, but it is 18259 // possible for the user flow to never be able to return to that 18260 // situation so here we do a sanity check to make sure we haven't 18261 // left any junk around. 18262 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18263 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18264 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18265 removed.clear(); 18266 for (PreferredActivity pa : pir.filterSet()) { 18267 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18268 removed.add(pa); 18269 } 18270 } 18271 if (removed.size() > 0) { 18272 for (int r=0; r<removed.size(); r++) { 18273 PreferredActivity pa = removed.get(r); 18274 Slog.w(TAG, "Removing dangling preferred activity: " 18275 + pa.mPref.mComponent); 18276 pir.removeFilter(pa); 18277 } 18278 mSettings.writePackageRestrictionsLPr( 18279 mSettings.mPreferredActivities.keyAt(i)); 18280 } 18281 } 18282 18283 for (int userId : UserManagerService.getInstance().getUserIds()) { 18284 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18285 grantPermissionsUserIds = ArrayUtils.appendInt( 18286 grantPermissionsUserIds, userId); 18287 } 18288 } 18289 } 18290 sUserManager.systemReady(); 18291 18292 // If we upgraded grant all default permissions before kicking off. 18293 for (int userId : grantPermissionsUserIds) { 18294 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18295 } 18296 18297 // If we did not grant default permissions, we preload from this the 18298 // default permission exceptions lazily to ensure we don't hit the 18299 // disk on a new user creation. 18300 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18301 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18302 } 18303 18304 // Kick off any messages waiting for system ready 18305 if (mPostSystemReadyMessages != null) { 18306 for (Message msg : mPostSystemReadyMessages) { 18307 msg.sendToTarget(); 18308 } 18309 mPostSystemReadyMessages = null; 18310 } 18311 18312 // Watch for external volumes that come and go over time 18313 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18314 storage.registerListener(mStorageListener); 18315 18316 mInstallerService.systemReady(); 18317 mPackageDexOptimizer.systemReady(); 18318 18319 MountServiceInternal mountServiceInternal = LocalServices.getService( 18320 MountServiceInternal.class); 18321 mountServiceInternal.addExternalStoragePolicy( 18322 new MountServiceInternal.ExternalStorageMountPolicy() { 18323 @Override 18324 public int getMountMode(int uid, String packageName) { 18325 if (Process.isIsolated(uid)) { 18326 return Zygote.MOUNT_EXTERNAL_NONE; 18327 } 18328 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18329 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18330 } 18331 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18332 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18333 } 18334 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18335 return Zygote.MOUNT_EXTERNAL_READ; 18336 } 18337 return Zygote.MOUNT_EXTERNAL_WRITE; 18338 } 18339 18340 @Override 18341 public boolean hasExternalStorage(int uid, String packageName) { 18342 return true; 18343 } 18344 }); 18345 18346 // Now that we're mostly running, clean up stale users and apps 18347 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18348 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18349 } 18350 18351 @Override 18352 public boolean isSafeMode() { 18353 return mSafeMode; 18354 } 18355 18356 @Override 18357 public boolean hasSystemUidErrors() { 18358 return mHasSystemUidErrors; 18359 } 18360 18361 static String arrayToString(int[] array) { 18362 StringBuffer buf = new StringBuffer(128); 18363 buf.append('['); 18364 if (array != null) { 18365 for (int i=0; i<array.length; i++) { 18366 if (i > 0) buf.append(", "); 18367 buf.append(array[i]); 18368 } 18369 } 18370 buf.append(']'); 18371 return buf.toString(); 18372 } 18373 18374 static class DumpState { 18375 public static final int DUMP_LIBS = 1 << 0; 18376 public static final int DUMP_FEATURES = 1 << 1; 18377 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18378 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18379 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18380 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18381 public static final int DUMP_PERMISSIONS = 1 << 6; 18382 public static final int DUMP_PACKAGES = 1 << 7; 18383 public static final int DUMP_SHARED_USERS = 1 << 8; 18384 public static final int DUMP_MESSAGES = 1 << 9; 18385 public static final int DUMP_PROVIDERS = 1 << 10; 18386 public static final int DUMP_VERIFIERS = 1 << 11; 18387 public static final int DUMP_PREFERRED = 1 << 12; 18388 public static final int DUMP_PREFERRED_XML = 1 << 13; 18389 public static final int DUMP_KEYSETS = 1 << 14; 18390 public static final int DUMP_VERSION = 1 << 15; 18391 public static final int DUMP_INSTALLS = 1 << 16; 18392 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18393 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18394 public static final int DUMP_FROZEN = 1 << 19; 18395 public static final int DUMP_DEXOPT = 1 << 20; 18396 public static final int DUMP_COMPILER_STATS = 1 << 21; 18397 18398 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18399 18400 private int mTypes; 18401 18402 private int mOptions; 18403 18404 private boolean mTitlePrinted; 18405 18406 private SharedUserSetting mSharedUser; 18407 18408 public boolean isDumping(int type) { 18409 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18410 return true; 18411 } 18412 18413 return (mTypes & type) != 0; 18414 } 18415 18416 public void setDump(int type) { 18417 mTypes |= type; 18418 } 18419 18420 public boolean isOptionEnabled(int option) { 18421 return (mOptions & option) != 0; 18422 } 18423 18424 public void setOptionEnabled(int option) { 18425 mOptions |= option; 18426 } 18427 18428 public boolean onTitlePrinted() { 18429 final boolean printed = mTitlePrinted; 18430 mTitlePrinted = true; 18431 return printed; 18432 } 18433 18434 public boolean getTitlePrinted() { 18435 return mTitlePrinted; 18436 } 18437 18438 public void setTitlePrinted(boolean enabled) { 18439 mTitlePrinted = enabled; 18440 } 18441 18442 public SharedUserSetting getSharedUser() { 18443 return mSharedUser; 18444 } 18445 18446 public void setSharedUser(SharedUserSetting user) { 18447 mSharedUser = user; 18448 } 18449 } 18450 18451 @Override 18452 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18453 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18454 (new PackageManagerShellCommand(this)).exec( 18455 this, in, out, err, args, resultReceiver); 18456 } 18457 18458 @Override 18459 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18460 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18461 != PackageManager.PERMISSION_GRANTED) { 18462 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18463 + Binder.getCallingPid() 18464 + ", uid=" + Binder.getCallingUid() 18465 + " without permission " 18466 + android.Manifest.permission.DUMP); 18467 return; 18468 } 18469 18470 DumpState dumpState = new DumpState(); 18471 boolean fullPreferred = false; 18472 boolean checkin = false; 18473 18474 String packageName = null; 18475 ArraySet<String> permissionNames = null; 18476 18477 int opti = 0; 18478 while (opti < args.length) { 18479 String opt = args[opti]; 18480 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18481 break; 18482 } 18483 opti++; 18484 18485 if ("-a".equals(opt)) { 18486 // Right now we only know how to print all. 18487 } else if ("-h".equals(opt)) { 18488 pw.println("Package manager dump options:"); 18489 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18490 pw.println(" --checkin: dump for a checkin"); 18491 pw.println(" -f: print details of intent filters"); 18492 pw.println(" -h: print this help"); 18493 pw.println(" cmd may be one of:"); 18494 pw.println(" l[ibraries]: list known shared libraries"); 18495 pw.println(" f[eatures]: list device features"); 18496 pw.println(" k[eysets]: print known keysets"); 18497 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18498 pw.println(" perm[issions]: dump permissions"); 18499 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18500 pw.println(" pref[erred]: print preferred package settings"); 18501 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18502 pw.println(" prov[iders]: dump content providers"); 18503 pw.println(" p[ackages]: dump installed packages"); 18504 pw.println(" s[hared-users]: dump shared user IDs"); 18505 pw.println(" m[essages]: print collected runtime messages"); 18506 pw.println(" v[erifiers]: print package verifier info"); 18507 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18508 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18509 pw.println(" version: print database version info"); 18510 pw.println(" write: write current settings now"); 18511 pw.println(" installs: details about install sessions"); 18512 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18513 pw.println(" dexopt: dump dexopt state"); 18514 pw.println(" compiler-stats: dump compiler statistics"); 18515 pw.println(" <package.name>: info about given package"); 18516 return; 18517 } else if ("--checkin".equals(opt)) { 18518 checkin = true; 18519 } else if ("-f".equals(opt)) { 18520 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18521 } else { 18522 pw.println("Unknown argument: " + opt + "; use -h for help"); 18523 } 18524 } 18525 18526 // Is the caller requesting to dump a particular piece of data? 18527 if (opti < args.length) { 18528 String cmd = args[opti]; 18529 opti++; 18530 // Is this a package name? 18531 if ("android".equals(cmd) || cmd.contains(".")) { 18532 packageName = cmd; 18533 // When dumping a single package, we always dump all of its 18534 // filter information since the amount of data will be reasonable. 18535 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18536 } else if ("check-permission".equals(cmd)) { 18537 if (opti >= args.length) { 18538 pw.println("Error: check-permission missing permission argument"); 18539 return; 18540 } 18541 String perm = args[opti]; 18542 opti++; 18543 if (opti >= args.length) { 18544 pw.println("Error: check-permission missing package argument"); 18545 return; 18546 } 18547 String pkg = args[opti]; 18548 opti++; 18549 int user = UserHandle.getUserId(Binder.getCallingUid()); 18550 if (opti < args.length) { 18551 try { 18552 user = Integer.parseInt(args[opti]); 18553 } catch (NumberFormatException e) { 18554 pw.println("Error: check-permission user argument is not a number: " 18555 + args[opti]); 18556 return; 18557 } 18558 } 18559 pw.println(checkPermission(perm, pkg, user)); 18560 return; 18561 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18562 dumpState.setDump(DumpState.DUMP_LIBS); 18563 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18564 dumpState.setDump(DumpState.DUMP_FEATURES); 18565 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18566 if (opti >= args.length) { 18567 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18568 | DumpState.DUMP_SERVICE_RESOLVERS 18569 | DumpState.DUMP_RECEIVER_RESOLVERS 18570 | DumpState.DUMP_CONTENT_RESOLVERS); 18571 } else { 18572 while (opti < args.length) { 18573 String name = args[opti]; 18574 if ("a".equals(name) || "activity".equals(name)) { 18575 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18576 } else if ("s".equals(name) || "service".equals(name)) { 18577 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18578 } else if ("r".equals(name) || "receiver".equals(name)) { 18579 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18580 } else if ("c".equals(name) || "content".equals(name)) { 18581 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18582 } else { 18583 pw.println("Error: unknown resolver table type: " + name); 18584 return; 18585 } 18586 opti++; 18587 } 18588 } 18589 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18590 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18591 } else if ("permission".equals(cmd)) { 18592 if (opti >= args.length) { 18593 pw.println("Error: permission requires permission name"); 18594 return; 18595 } 18596 permissionNames = new ArraySet<>(); 18597 while (opti < args.length) { 18598 permissionNames.add(args[opti]); 18599 opti++; 18600 } 18601 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18602 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18603 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18604 dumpState.setDump(DumpState.DUMP_PREFERRED); 18605 } else if ("preferred-xml".equals(cmd)) { 18606 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18607 if (opti < args.length && "--full".equals(args[opti])) { 18608 fullPreferred = true; 18609 opti++; 18610 } 18611 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18612 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18613 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18614 dumpState.setDump(DumpState.DUMP_PACKAGES); 18615 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18616 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18617 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18618 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18619 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18620 dumpState.setDump(DumpState.DUMP_MESSAGES); 18621 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18622 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18623 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18624 || "intent-filter-verifiers".equals(cmd)) { 18625 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18626 } else if ("version".equals(cmd)) { 18627 dumpState.setDump(DumpState.DUMP_VERSION); 18628 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18629 dumpState.setDump(DumpState.DUMP_KEYSETS); 18630 } else if ("installs".equals(cmd)) { 18631 dumpState.setDump(DumpState.DUMP_INSTALLS); 18632 } else if ("frozen".equals(cmd)) { 18633 dumpState.setDump(DumpState.DUMP_FROZEN); 18634 } else if ("dexopt".equals(cmd)) { 18635 dumpState.setDump(DumpState.DUMP_DEXOPT); 18636 } else if ("compiler-stats".equals(cmd)) { 18637 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18638 } else if ("write".equals(cmd)) { 18639 synchronized (mPackages) { 18640 mSettings.writeLPr(); 18641 pw.println("Settings written."); 18642 return; 18643 } 18644 } 18645 } 18646 18647 if (checkin) { 18648 pw.println("vers,1"); 18649 } 18650 18651 // reader 18652 synchronized (mPackages) { 18653 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18654 if (!checkin) { 18655 if (dumpState.onTitlePrinted()) 18656 pw.println(); 18657 pw.println("Database versions:"); 18658 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18659 } 18660 } 18661 18662 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18663 if (!checkin) { 18664 if (dumpState.onTitlePrinted()) 18665 pw.println(); 18666 pw.println("Verifiers:"); 18667 pw.print(" Required: "); 18668 pw.print(mRequiredVerifierPackage); 18669 pw.print(" (uid="); 18670 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18671 UserHandle.USER_SYSTEM)); 18672 pw.println(")"); 18673 } else if (mRequiredVerifierPackage != null) { 18674 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18675 pw.print(","); 18676 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18677 UserHandle.USER_SYSTEM)); 18678 } 18679 } 18680 18681 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18682 packageName == null) { 18683 if (mIntentFilterVerifierComponent != null) { 18684 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18685 if (!checkin) { 18686 if (dumpState.onTitlePrinted()) 18687 pw.println(); 18688 pw.println("Intent Filter Verifier:"); 18689 pw.print(" Using: "); 18690 pw.print(verifierPackageName); 18691 pw.print(" (uid="); 18692 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18693 UserHandle.USER_SYSTEM)); 18694 pw.println(")"); 18695 } else if (verifierPackageName != null) { 18696 pw.print("ifv,"); pw.print(verifierPackageName); 18697 pw.print(","); 18698 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18699 UserHandle.USER_SYSTEM)); 18700 } 18701 } else { 18702 pw.println(); 18703 pw.println("No Intent Filter Verifier available!"); 18704 } 18705 } 18706 18707 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18708 boolean printedHeader = false; 18709 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18710 while (it.hasNext()) { 18711 String name = it.next(); 18712 SharedLibraryEntry ent = mSharedLibraries.get(name); 18713 if (!checkin) { 18714 if (!printedHeader) { 18715 if (dumpState.onTitlePrinted()) 18716 pw.println(); 18717 pw.println("Libraries:"); 18718 printedHeader = true; 18719 } 18720 pw.print(" "); 18721 } else { 18722 pw.print("lib,"); 18723 } 18724 pw.print(name); 18725 if (!checkin) { 18726 pw.print(" -> "); 18727 } 18728 if (ent.path != null) { 18729 if (!checkin) { 18730 pw.print("(jar) "); 18731 pw.print(ent.path); 18732 } else { 18733 pw.print(",jar,"); 18734 pw.print(ent.path); 18735 } 18736 } else { 18737 if (!checkin) { 18738 pw.print("(apk) "); 18739 pw.print(ent.apk); 18740 } else { 18741 pw.print(",apk,"); 18742 pw.print(ent.apk); 18743 } 18744 } 18745 pw.println(); 18746 } 18747 } 18748 18749 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18750 if (dumpState.onTitlePrinted()) 18751 pw.println(); 18752 if (!checkin) { 18753 pw.println("Features:"); 18754 } 18755 18756 for (FeatureInfo feat : mAvailableFeatures.values()) { 18757 if (checkin) { 18758 pw.print("feat,"); 18759 pw.print(feat.name); 18760 pw.print(","); 18761 pw.println(feat.version); 18762 } else { 18763 pw.print(" "); 18764 pw.print(feat.name); 18765 if (feat.version > 0) { 18766 pw.print(" version="); 18767 pw.print(feat.version); 18768 } 18769 pw.println(); 18770 } 18771 } 18772 } 18773 18774 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18775 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18776 : "Activity Resolver Table:", " ", packageName, 18777 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18778 dumpState.setTitlePrinted(true); 18779 } 18780 } 18781 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18782 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18783 : "Receiver Resolver Table:", " ", packageName, 18784 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18785 dumpState.setTitlePrinted(true); 18786 } 18787 } 18788 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18789 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18790 : "Service Resolver Table:", " ", packageName, 18791 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18792 dumpState.setTitlePrinted(true); 18793 } 18794 } 18795 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18796 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18797 : "Provider Resolver Table:", " ", packageName, 18798 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18799 dumpState.setTitlePrinted(true); 18800 } 18801 } 18802 18803 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18804 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18805 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18806 int user = mSettings.mPreferredActivities.keyAt(i); 18807 if (pir.dump(pw, 18808 dumpState.getTitlePrinted() 18809 ? "\nPreferred Activities User " + user + ":" 18810 : "Preferred Activities User " + user + ":", " ", 18811 packageName, true, false)) { 18812 dumpState.setTitlePrinted(true); 18813 } 18814 } 18815 } 18816 18817 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18818 pw.flush(); 18819 FileOutputStream fout = new FileOutputStream(fd); 18820 BufferedOutputStream str = new BufferedOutputStream(fout); 18821 XmlSerializer serializer = new FastXmlSerializer(); 18822 try { 18823 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18824 serializer.startDocument(null, true); 18825 serializer.setFeature( 18826 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18827 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18828 serializer.endDocument(); 18829 serializer.flush(); 18830 } catch (IllegalArgumentException e) { 18831 pw.println("Failed writing: " + e); 18832 } catch (IllegalStateException e) { 18833 pw.println("Failed writing: " + e); 18834 } catch (IOException e) { 18835 pw.println("Failed writing: " + e); 18836 } 18837 } 18838 18839 if (!checkin 18840 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18841 && packageName == null) { 18842 pw.println(); 18843 int count = mSettings.mPackages.size(); 18844 if (count == 0) { 18845 pw.println("No applications!"); 18846 pw.println(); 18847 } else { 18848 final String prefix = " "; 18849 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18850 if (allPackageSettings.size() == 0) { 18851 pw.println("No domain preferred apps!"); 18852 pw.println(); 18853 } else { 18854 pw.println("App verification status:"); 18855 pw.println(); 18856 count = 0; 18857 for (PackageSetting ps : allPackageSettings) { 18858 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18859 if (ivi == null || ivi.getPackageName() == null) continue; 18860 pw.println(prefix + "Package: " + ivi.getPackageName()); 18861 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18862 pw.println(prefix + "Status: " + ivi.getStatusString()); 18863 pw.println(); 18864 count++; 18865 } 18866 if (count == 0) { 18867 pw.println(prefix + "No app verification established."); 18868 pw.println(); 18869 } 18870 for (int userId : sUserManager.getUserIds()) { 18871 pw.println("App linkages for user " + userId + ":"); 18872 pw.println(); 18873 count = 0; 18874 for (PackageSetting ps : allPackageSettings) { 18875 final long status = ps.getDomainVerificationStatusForUser(userId); 18876 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18877 continue; 18878 } 18879 pw.println(prefix + "Package: " + ps.name); 18880 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18881 String statusStr = IntentFilterVerificationInfo. 18882 getStatusStringFromValue(status); 18883 pw.println(prefix + "Status: " + statusStr); 18884 pw.println(); 18885 count++; 18886 } 18887 if (count == 0) { 18888 pw.println(prefix + "No configured app linkages."); 18889 pw.println(); 18890 } 18891 } 18892 } 18893 } 18894 } 18895 18896 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18897 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18898 if (packageName == null && permissionNames == null) { 18899 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18900 if (iperm == 0) { 18901 if (dumpState.onTitlePrinted()) 18902 pw.println(); 18903 pw.println("AppOp Permissions:"); 18904 } 18905 pw.print(" AppOp Permission "); 18906 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18907 pw.println(":"); 18908 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18909 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18910 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18911 } 18912 } 18913 } 18914 } 18915 18916 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18917 boolean printedSomething = false; 18918 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18919 if (packageName != null && !packageName.equals(p.info.packageName)) { 18920 continue; 18921 } 18922 if (!printedSomething) { 18923 if (dumpState.onTitlePrinted()) 18924 pw.println(); 18925 pw.println("Registered ContentProviders:"); 18926 printedSomething = true; 18927 } 18928 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18929 pw.print(" "); pw.println(p.toString()); 18930 } 18931 printedSomething = false; 18932 for (Map.Entry<String, PackageParser.Provider> entry : 18933 mProvidersByAuthority.entrySet()) { 18934 PackageParser.Provider p = entry.getValue(); 18935 if (packageName != null && !packageName.equals(p.info.packageName)) { 18936 continue; 18937 } 18938 if (!printedSomething) { 18939 if (dumpState.onTitlePrinted()) 18940 pw.println(); 18941 pw.println("ContentProvider Authorities:"); 18942 printedSomething = true; 18943 } 18944 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18945 pw.print(" "); pw.println(p.toString()); 18946 if (p.info != null && p.info.applicationInfo != null) { 18947 final String appInfo = p.info.applicationInfo.toString(); 18948 pw.print(" applicationInfo="); pw.println(appInfo); 18949 } 18950 } 18951 } 18952 18953 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18954 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18955 } 18956 18957 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18958 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18959 } 18960 18961 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18962 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18963 } 18964 18965 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18966 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18967 } 18968 18969 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18970 // XXX should handle packageName != null by dumping only install data that 18971 // the given package is involved with. 18972 if (dumpState.onTitlePrinted()) pw.println(); 18973 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18974 } 18975 18976 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18977 // XXX should handle packageName != null by dumping only install data that 18978 // the given package is involved with. 18979 if (dumpState.onTitlePrinted()) pw.println(); 18980 18981 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18982 ipw.println(); 18983 ipw.println("Frozen packages:"); 18984 ipw.increaseIndent(); 18985 if (mFrozenPackages.size() == 0) { 18986 ipw.println("(none)"); 18987 } else { 18988 for (int i = 0; i < mFrozenPackages.size(); i++) { 18989 ipw.println(mFrozenPackages.valueAt(i)); 18990 } 18991 } 18992 ipw.decreaseIndent(); 18993 } 18994 18995 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18996 if (dumpState.onTitlePrinted()) pw.println(); 18997 dumpDexoptStateLPr(pw, packageName); 18998 } 18999 19000 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 19001 if (dumpState.onTitlePrinted()) pw.println(); 19002 dumpCompilerStatsLPr(pw, packageName); 19003 } 19004 19005 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 19006 if (dumpState.onTitlePrinted()) pw.println(); 19007 mSettings.dumpReadMessagesLPr(pw, dumpState); 19008 19009 pw.println(); 19010 pw.println("Package warning messages:"); 19011 BufferedReader in = null; 19012 String line = null; 19013 try { 19014 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19015 while ((line = in.readLine()) != null) { 19016 if (line.contains("ignored: updated version")) continue; 19017 pw.println(line); 19018 } 19019 } catch (IOException ignored) { 19020 } finally { 19021 IoUtils.closeQuietly(in); 19022 } 19023 } 19024 19025 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 19026 BufferedReader in = null; 19027 String line = null; 19028 try { 19029 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19030 while ((line = in.readLine()) != null) { 19031 if (line.contains("ignored: updated version")) continue; 19032 pw.print("msg,"); 19033 pw.println(line); 19034 } 19035 } catch (IOException ignored) { 19036 } finally { 19037 IoUtils.closeQuietly(in); 19038 } 19039 } 19040 } 19041 } 19042 19043 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 19044 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19045 ipw.println(); 19046 ipw.println("Dexopt state:"); 19047 ipw.increaseIndent(); 19048 Collection<PackageParser.Package> packages = null; 19049 if (packageName != null) { 19050 PackageParser.Package targetPackage = mPackages.get(packageName); 19051 if (targetPackage != null) { 19052 packages = Collections.singletonList(targetPackage); 19053 } else { 19054 ipw.println("Unable to find package: " + packageName); 19055 return; 19056 } 19057 } else { 19058 packages = mPackages.values(); 19059 } 19060 19061 for (PackageParser.Package pkg : packages) { 19062 ipw.println("[" + pkg.packageName + "]"); 19063 ipw.increaseIndent(); 19064 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 19065 ipw.decreaseIndent(); 19066 } 19067 } 19068 19069 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 19070 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19071 ipw.println(); 19072 ipw.println("Compiler stats:"); 19073 ipw.increaseIndent(); 19074 Collection<PackageParser.Package> packages = null; 19075 if (packageName != null) { 19076 PackageParser.Package targetPackage = mPackages.get(packageName); 19077 if (targetPackage != null) { 19078 packages = Collections.singletonList(targetPackage); 19079 } else { 19080 ipw.println("Unable to find package: " + packageName); 19081 return; 19082 } 19083 } else { 19084 packages = mPackages.values(); 19085 } 19086 19087 for (PackageParser.Package pkg : packages) { 19088 ipw.println("[" + pkg.packageName + "]"); 19089 ipw.increaseIndent(); 19090 19091 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 19092 if (stats == null) { 19093 ipw.println("(No recorded stats)"); 19094 } else { 19095 stats.dump(ipw); 19096 } 19097 ipw.decreaseIndent(); 19098 } 19099 } 19100 19101 private String dumpDomainString(String packageName) { 19102 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 19103 .getList(); 19104 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 19105 19106 ArraySet<String> result = new ArraySet<>(); 19107 if (iviList.size() > 0) { 19108 for (IntentFilterVerificationInfo ivi : iviList) { 19109 for (String host : ivi.getDomains()) { 19110 result.add(host); 19111 } 19112 } 19113 } 19114 if (filters != null && filters.size() > 0) { 19115 for (IntentFilter filter : filters) { 19116 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 19117 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19118 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19119 result.addAll(filter.getHostsList()); 19120 } 19121 } 19122 } 19123 19124 StringBuilder sb = new StringBuilder(result.size() * 16); 19125 for (String domain : result) { 19126 if (sb.length() > 0) sb.append(" "); 19127 sb.append(domain); 19128 } 19129 return sb.toString(); 19130 } 19131 19132 // ------- apps on sdcard specific code ------- 19133 static final boolean DEBUG_SD_INSTALL = false; 19134 19135 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19136 19137 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19138 19139 private boolean mMediaMounted = false; 19140 19141 static String getEncryptKey() { 19142 try { 19143 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19144 SD_ENCRYPTION_KEYSTORE_NAME); 19145 if (sdEncKey == null) { 19146 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19147 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19148 if (sdEncKey == null) { 19149 Slog.e(TAG, "Failed to create encryption keys"); 19150 return null; 19151 } 19152 } 19153 return sdEncKey; 19154 } catch (NoSuchAlgorithmException nsae) { 19155 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19156 return null; 19157 } catch (IOException ioe) { 19158 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19159 return null; 19160 } 19161 } 19162 19163 /* 19164 * Update media status on PackageManager. 19165 */ 19166 @Override 19167 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19168 int callingUid = Binder.getCallingUid(); 19169 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19170 throw new SecurityException("Media status can only be updated by the system"); 19171 } 19172 // reader; this apparently protects mMediaMounted, but should probably 19173 // be a different lock in that case. 19174 synchronized (mPackages) { 19175 Log.i(TAG, "Updating external media status from " 19176 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19177 + (mediaStatus ? "mounted" : "unmounted")); 19178 if (DEBUG_SD_INSTALL) 19179 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19180 + ", mMediaMounted=" + mMediaMounted); 19181 if (mediaStatus == mMediaMounted) { 19182 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19183 : 0, -1); 19184 mHandler.sendMessage(msg); 19185 return; 19186 } 19187 mMediaMounted = mediaStatus; 19188 } 19189 // Queue up an async operation since the package installation may take a 19190 // little while. 19191 mHandler.post(new Runnable() { 19192 public void run() { 19193 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19194 } 19195 }); 19196 } 19197 19198 /** 19199 * Called by MountService when the initial ASECs to scan are available. 19200 * Should block until all the ASEC containers are finished being scanned. 19201 */ 19202 public void scanAvailableAsecs() { 19203 updateExternalMediaStatusInner(true, false, false); 19204 } 19205 19206 /* 19207 * Collect information of applications on external media, map them against 19208 * existing containers and update information based on current mount status. 19209 * Please note that we always have to report status if reportStatus has been 19210 * set to true especially when unloading packages. 19211 */ 19212 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19213 boolean externalStorage) { 19214 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19215 int[] uidArr = EmptyArray.INT; 19216 19217 final String[] list = PackageHelper.getSecureContainerList(); 19218 if (ArrayUtils.isEmpty(list)) { 19219 Log.i(TAG, "No secure containers found"); 19220 } else { 19221 // Process list of secure containers and categorize them 19222 // as active or stale based on their package internal state. 19223 19224 // reader 19225 synchronized (mPackages) { 19226 for (String cid : list) { 19227 // Leave stages untouched for now; installer service owns them 19228 if (PackageInstallerService.isStageName(cid)) continue; 19229 19230 if (DEBUG_SD_INSTALL) 19231 Log.i(TAG, "Processing container " + cid); 19232 String pkgName = getAsecPackageName(cid); 19233 if (pkgName == null) { 19234 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19235 continue; 19236 } 19237 if (DEBUG_SD_INSTALL) 19238 Log.i(TAG, "Looking for pkg : " + pkgName); 19239 19240 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19241 if (ps == null) { 19242 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19243 continue; 19244 } 19245 19246 /* 19247 * Skip packages that are not external if we're unmounting 19248 * external storage. 19249 */ 19250 if (externalStorage && !isMounted && !isExternal(ps)) { 19251 continue; 19252 } 19253 19254 final AsecInstallArgs args = new AsecInstallArgs(cid, 19255 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19256 // The package status is changed only if the code path 19257 // matches between settings and the container id. 19258 if (ps.codePathString != null 19259 && ps.codePathString.startsWith(args.getCodePath())) { 19260 if (DEBUG_SD_INSTALL) { 19261 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19262 + " at code path: " + ps.codePathString); 19263 } 19264 19265 // We do have a valid package installed on sdcard 19266 processCids.put(args, ps.codePathString); 19267 final int uid = ps.appId; 19268 if (uid != -1) { 19269 uidArr = ArrayUtils.appendInt(uidArr, uid); 19270 } 19271 } else { 19272 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19273 + ps.codePathString); 19274 } 19275 } 19276 } 19277 19278 Arrays.sort(uidArr); 19279 } 19280 19281 // Process packages with valid entries. 19282 if (isMounted) { 19283 if (DEBUG_SD_INSTALL) 19284 Log.i(TAG, "Loading packages"); 19285 loadMediaPackages(processCids, uidArr, externalStorage); 19286 startCleaningPackages(); 19287 mInstallerService.onSecureContainersAvailable(); 19288 } else { 19289 if (DEBUG_SD_INSTALL) 19290 Log.i(TAG, "Unloading packages"); 19291 unloadMediaPackages(processCids, uidArr, reportStatus); 19292 } 19293 } 19294 19295 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19296 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19297 final int size = infos.size(); 19298 final String[] packageNames = new String[size]; 19299 final int[] packageUids = new int[size]; 19300 for (int i = 0; i < size; i++) { 19301 final ApplicationInfo info = infos.get(i); 19302 packageNames[i] = info.packageName; 19303 packageUids[i] = info.uid; 19304 } 19305 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19306 finishedReceiver); 19307 } 19308 19309 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19310 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19311 sendResourcesChangedBroadcast(mediaStatus, replacing, 19312 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19313 } 19314 19315 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19316 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19317 int size = pkgList.length; 19318 if (size > 0) { 19319 // Send broadcasts here 19320 Bundle extras = new Bundle(); 19321 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19322 if (uidArr != null) { 19323 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19324 } 19325 if (replacing) { 19326 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19327 } 19328 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19329 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19330 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19331 } 19332 } 19333 19334 /* 19335 * Look at potentially valid container ids from processCids If package 19336 * information doesn't match the one on record or package scanning fails, 19337 * the cid is added to list of removeCids. We currently don't delete stale 19338 * containers. 19339 */ 19340 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19341 boolean externalStorage) { 19342 ArrayList<String> pkgList = new ArrayList<String>(); 19343 Set<AsecInstallArgs> keys = processCids.keySet(); 19344 19345 for (AsecInstallArgs args : keys) { 19346 String codePath = processCids.get(args); 19347 if (DEBUG_SD_INSTALL) 19348 Log.i(TAG, "Loading container : " + args.cid); 19349 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19350 try { 19351 // Make sure there are no container errors first. 19352 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19353 Slog.e(TAG, "Failed to mount cid : " + args.cid 19354 + " when installing from sdcard"); 19355 continue; 19356 } 19357 // Check code path here. 19358 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19359 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19360 + " does not match one in settings " + codePath); 19361 continue; 19362 } 19363 // Parse package 19364 int parseFlags = mDefParseFlags; 19365 if (args.isExternalAsec()) { 19366 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19367 } 19368 if (args.isFwdLocked()) { 19369 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19370 } 19371 19372 synchronized (mInstallLock) { 19373 PackageParser.Package pkg = null; 19374 try { 19375 // Sadly we don't know the package name yet to freeze it 19376 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19377 SCAN_IGNORE_FROZEN, 0, null); 19378 } catch (PackageManagerException e) { 19379 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19380 } 19381 // Scan the package 19382 if (pkg != null) { 19383 /* 19384 * TODO why is the lock being held? doPostInstall is 19385 * called in other places without the lock. This needs 19386 * to be straightened out. 19387 */ 19388 // writer 19389 synchronized (mPackages) { 19390 retCode = PackageManager.INSTALL_SUCCEEDED; 19391 pkgList.add(pkg.packageName); 19392 // Post process args 19393 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19394 pkg.applicationInfo.uid); 19395 } 19396 } else { 19397 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19398 } 19399 } 19400 19401 } finally { 19402 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19403 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19404 } 19405 } 19406 } 19407 // writer 19408 synchronized (mPackages) { 19409 // If the platform SDK has changed since the last time we booted, 19410 // we need to re-grant app permission to catch any new ones that 19411 // appear. This is really a hack, and means that apps can in some 19412 // cases get permissions that the user didn't initially explicitly 19413 // allow... it would be nice to have some better way to handle 19414 // this situation. 19415 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19416 : mSettings.getInternalVersion(); 19417 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19418 : StorageManager.UUID_PRIVATE_INTERNAL; 19419 19420 int updateFlags = UPDATE_PERMISSIONS_ALL; 19421 if (ver.sdkVersion != mSdkVersion) { 19422 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19423 + mSdkVersion + "; regranting permissions for external"); 19424 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19425 } 19426 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19427 19428 // Yay, everything is now upgraded 19429 ver.forceCurrent(); 19430 19431 // can downgrade to reader 19432 // Persist settings 19433 mSettings.writeLPr(); 19434 } 19435 // Send a broadcast to let everyone know we are done processing 19436 if (pkgList.size() > 0) { 19437 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19438 } 19439 } 19440 19441 /* 19442 * Utility method to unload a list of specified containers 19443 */ 19444 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19445 // Just unmount all valid containers. 19446 for (AsecInstallArgs arg : cidArgs) { 19447 synchronized (mInstallLock) { 19448 arg.doPostDeleteLI(false); 19449 } 19450 } 19451 } 19452 19453 /* 19454 * Unload packages mounted on external media. This involves deleting package 19455 * data from internal structures, sending broadcasts about disabled packages, 19456 * gc'ing to free up references, unmounting all secure containers 19457 * corresponding to packages on external media, and posting a 19458 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19459 * that we always have to post this message if status has been requested no 19460 * matter what. 19461 */ 19462 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19463 final boolean reportStatus) { 19464 if (DEBUG_SD_INSTALL) 19465 Log.i(TAG, "unloading media packages"); 19466 ArrayList<String> pkgList = new ArrayList<String>(); 19467 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19468 final Set<AsecInstallArgs> keys = processCids.keySet(); 19469 for (AsecInstallArgs args : keys) { 19470 String pkgName = args.getPackageName(); 19471 if (DEBUG_SD_INSTALL) 19472 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19473 // Delete package internally 19474 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19475 synchronized (mInstallLock) { 19476 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19477 final boolean res; 19478 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19479 "unloadMediaPackages")) { 19480 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19481 null); 19482 } 19483 if (res) { 19484 pkgList.add(pkgName); 19485 } else { 19486 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19487 failedList.add(args); 19488 } 19489 } 19490 } 19491 19492 // reader 19493 synchronized (mPackages) { 19494 // We didn't update the settings after removing each package; 19495 // write them now for all packages. 19496 mSettings.writeLPr(); 19497 } 19498 19499 // We have to absolutely send UPDATED_MEDIA_STATUS only 19500 // after confirming that all the receivers processed the ordered 19501 // broadcast when packages get disabled, force a gc to clean things up. 19502 // and unload all the containers. 19503 if (pkgList.size() > 0) { 19504 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19505 new IIntentReceiver.Stub() { 19506 public void performReceive(Intent intent, int resultCode, String data, 19507 Bundle extras, boolean ordered, boolean sticky, 19508 int sendingUser) throws RemoteException { 19509 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19510 reportStatus ? 1 : 0, 1, keys); 19511 mHandler.sendMessage(msg); 19512 } 19513 }); 19514 } else { 19515 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19516 keys); 19517 mHandler.sendMessage(msg); 19518 } 19519 } 19520 19521 private void loadPrivatePackages(final VolumeInfo vol) { 19522 mHandler.post(new Runnable() { 19523 @Override 19524 public void run() { 19525 loadPrivatePackagesInner(vol); 19526 } 19527 }); 19528 } 19529 19530 private void loadPrivatePackagesInner(VolumeInfo vol) { 19531 final String volumeUuid = vol.fsUuid; 19532 if (TextUtils.isEmpty(volumeUuid)) { 19533 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19534 return; 19535 } 19536 19537 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19538 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19539 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19540 19541 final VersionInfo ver; 19542 final List<PackageSetting> packages; 19543 synchronized (mPackages) { 19544 ver = mSettings.findOrCreateVersion(volumeUuid); 19545 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19546 } 19547 19548 for (PackageSetting ps : packages) { 19549 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19550 synchronized (mInstallLock) { 19551 final PackageParser.Package pkg; 19552 try { 19553 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19554 loaded.add(pkg.applicationInfo); 19555 19556 } catch (PackageManagerException e) { 19557 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19558 } 19559 19560 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19561 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19562 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19563 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19564 } 19565 } 19566 } 19567 19568 // Reconcile app data for all started/unlocked users 19569 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19570 final UserManager um = mContext.getSystemService(UserManager.class); 19571 UserManagerInternal umInternal = getUserManagerInternal(); 19572 for (UserInfo user : um.getUsers()) { 19573 final int flags; 19574 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19575 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19576 } else if (umInternal.isUserRunning(user.id)) { 19577 flags = StorageManager.FLAG_STORAGE_DE; 19578 } else { 19579 continue; 19580 } 19581 19582 try { 19583 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19584 synchronized (mInstallLock) { 19585 reconcileAppsDataLI(volumeUuid, user.id, flags); 19586 } 19587 } catch (IllegalStateException e) { 19588 // Device was probably ejected, and we'll process that event momentarily 19589 Slog.w(TAG, "Failed to prepare storage: " + e); 19590 } 19591 } 19592 19593 synchronized (mPackages) { 19594 int updateFlags = UPDATE_PERMISSIONS_ALL; 19595 if (ver.sdkVersion != mSdkVersion) { 19596 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19597 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19598 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19599 } 19600 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19601 19602 // Yay, everything is now upgraded 19603 ver.forceCurrent(); 19604 19605 mSettings.writeLPr(); 19606 } 19607 19608 for (PackageFreezer freezer : freezers) { 19609 freezer.close(); 19610 } 19611 19612 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19613 sendResourcesChangedBroadcast(true, false, loaded, null); 19614 } 19615 19616 private void unloadPrivatePackages(final VolumeInfo vol) { 19617 mHandler.post(new Runnable() { 19618 @Override 19619 public void run() { 19620 unloadPrivatePackagesInner(vol); 19621 } 19622 }); 19623 } 19624 19625 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19626 final String volumeUuid = vol.fsUuid; 19627 if (TextUtils.isEmpty(volumeUuid)) { 19628 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19629 return; 19630 } 19631 19632 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19633 synchronized (mInstallLock) { 19634 synchronized (mPackages) { 19635 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19636 for (PackageSetting ps : packages) { 19637 if (ps.pkg == null) continue; 19638 19639 final ApplicationInfo info = ps.pkg.applicationInfo; 19640 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19641 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19642 19643 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19644 "unloadPrivatePackagesInner")) { 19645 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19646 false, null)) { 19647 unloaded.add(info); 19648 } else { 19649 Slog.w(TAG, "Failed to unload " + ps.codePath); 19650 } 19651 } 19652 19653 // Try very hard to release any references to this package 19654 // so we don't risk the system server being killed due to 19655 // open FDs 19656 AttributeCache.instance().removePackage(ps.name); 19657 } 19658 19659 mSettings.writeLPr(); 19660 } 19661 } 19662 19663 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19664 sendResourcesChangedBroadcast(false, false, unloaded, null); 19665 19666 // Try very hard to release any references to this path so we don't risk 19667 // the system server being killed due to open FDs 19668 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19669 19670 for (int i = 0; i < 3; i++) { 19671 System.gc(); 19672 System.runFinalization(); 19673 } 19674 } 19675 19676 /** 19677 * Prepare storage areas for given user on all mounted devices. 19678 */ 19679 void prepareUserData(int userId, int userSerial, int flags) { 19680 synchronized (mInstallLock) { 19681 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19682 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19683 final String volumeUuid = vol.getFsUuid(); 19684 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19685 } 19686 } 19687 } 19688 19689 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19690 boolean allowRecover) { 19691 // Prepare storage and verify that serial numbers are consistent; if 19692 // there's a mismatch we need to destroy to avoid leaking data 19693 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19694 try { 19695 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19696 19697 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19698 UserManagerService.enforceSerialNumber( 19699 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19700 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19701 UserManagerService.enforceSerialNumber( 19702 Environment.getDataSystemDeDirectory(userId), userSerial); 19703 } 19704 } 19705 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19706 UserManagerService.enforceSerialNumber( 19707 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19708 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19709 UserManagerService.enforceSerialNumber( 19710 Environment.getDataSystemCeDirectory(userId), userSerial); 19711 } 19712 } 19713 19714 synchronized (mInstallLock) { 19715 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19716 } 19717 } catch (Exception e) { 19718 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19719 + " because we failed to prepare: " + e); 19720 destroyUserDataLI(volumeUuid, userId, 19721 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19722 19723 if (allowRecover) { 19724 // Try one last time; if we fail again we're really in trouble 19725 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19726 } 19727 } 19728 } 19729 19730 /** 19731 * Destroy storage areas for given user on all mounted devices. 19732 */ 19733 void destroyUserData(int userId, int flags) { 19734 synchronized (mInstallLock) { 19735 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19736 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19737 final String volumeUuid = vol.getFsUuid(); 19738 destroyUserDataLI(volumeUuid, userId, flags); 19739 } 19740 } 19741 } 19742 19743 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19744 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19745 try { 19746 // Clean up app data, profile data, and media data 19747 mInstaller.destroyUserData(volumeUuid, userId, flags); 19748 19749 // Clean up system data 19750 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19751 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19752 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19753 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19754 } 19755 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19756 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19757 } 19758 } 19759 19760 // Data with special labels is now gone, so finish the job 19761 storage.destroyUserStorage(volumeUuid, userId, flags); 19762 19763 } catch (Exception e) { 19764 logCriticalInfo(Log.WARN, 19765 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19766 } 19767 } 19768 19769 /** 19770 * Examine all users present on given mounted volume, and destroy data 19771 * belonging to users that are no longer valid, or whose user ID has been 19772 * recycled. 19773 */ 19774 private void reconcileUsers(String volumeUuid) { 19775 final List<File> files = new ArrayList<>(); 19776 Collections.addAll(files, FileUtils 19777 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19778 Collections.addAll(files, FileUtils 19779 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19780 Collections.addAll(files, FileUtils 19781 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19782 Collections.addAll(files, FileUtils 19783 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19784 for (File file : files) { 19785 if (!file.isDirectory()) continue; 19786 19787 final int userId; 19788 final UserInfo info; 19789 try { 19790 userId = Integer.parseInt(file.getName()); 19791 info = sUserManager.getUserInfo(userId); 19792 } catch (NumberFormatException e) { 19793 Slog.w(TAG, "Invalid user directory " + file); 19794 continue; 19795 } 19796 19797 boolean destroyUser = false; 19798 if (info == null) { 19799 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19800 + " because no matching user was found"); 19801 destroyUser = true; 19802 } else if (!mOnlyCore) { 19803 try { 19804 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19805 } catch (IOException e) { 19806 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19807 + " because we failed to enforce serial number: " + e); 19808 destroyUser = true; 19809 } 19810 } 19811 19812 if (destroyUser) { 19813 synchronized (mInstallLock) { 19814 destroyUserDataLI(volumeUuid, userId, 19815 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19816 } 19817 } 19818 } 19819 } 19820 19821 private void assertPackageKnown(String volumeUuid, String packageName) 19822 throws PackageManagerException { 19823 synchronized (mPackages) { 19824 final PackageSetting ps = mSettings.mPackages.get(packageName); 19825 if (ps == null) { 19826 throw new PackageManagerException("Package " + packageName + " is unknown"); 19827 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19828 throw new PackageManagerException( 19829 "Package " + packageName + " found on unknown volume " + volumeUuid 19830 + "; expected volume " + ps.volumeUuid); 19831 } 19832 } 19833 } 19834 19835 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19836 throws PackageManagerException { 19837 synchronized (mPackages) { 19838 final PackageSetting ps = mSettings.mPackages.get(packageName); 19839 if (ps == null) { 19840 throw new PackageManagerException("Package " + packageName + " is unknown"); 19841 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19842 throw new PackageManagerException( 19843 "Package " + packageName + " found on unknown volume " + volumeUuid 19844 + "; expected volume " + ps.volumeUuid); 19845 } else if (!ps.getInstalled(userId)) { 19846 throw new PackageManagerException( 19847 "Package " + packageName + " not installed for user " + userId); 19848 } 19849 } 19850 } 19851 19852 /** 19853 * Examine all apps present on given mounted volume, and destroy apps that 19854 * aren't expected, either due to uninstallation or reinstallation on 19855 * another volume. 19856 */ 19857 private void reconcileApps(String volumeUuid) { 19858 final File[] files = FileUtils 19859 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19860 for (File file : files) { 19861 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19862 && !PackageInstallerService.isStageName(file.getName()); 19863 if (!isPackage) { 19864 // Ignore entries which are not packages 19865 continue; 19866 } 19867 19868 try { 19869 final PackageLite pkg = PackageParser.parsePackageLite(file, 19870 PackageParser.PARSE_MUST_BE_APK); 19871 assertPackageKnown(volumeUuid, pkg.packageName); 19872 19873 } catch (PackageParserException | PackageManagerException e) { 19874 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19875 synchronized (mInstallLock) { 19876 removeCodePathLI(file); 19877 } 19878 } 19879 } 19880 } 19881 19882 /** 19883 * Reconcile all app data for the given user. 19884 * <p> 19885 * Verifies that directories exist and that ownership and labeling is 19886 * correct for all installed apps on all mounted volumes. 19887 */ 19888 void reconcileAppsData(int userId, int flags) { 19889 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19890 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19891 final String volumeUuid = vol.getFsUuid(); 19892 synchronized (mInstallLock) { 19893 reconcileAppsDataLI(volumeUuid, userId, flags); 19894 } 19895 } 19896 } 19897 19898 /** 19899 * Reconcile all app data on given mounted volume. 19900 * <p> 19901 * Destroys app data that isn't expected, either due to uninstallation or 19902 * reinstallation on another volume. 19903 * <p> 19904 * Verifies that directories exist and that ownership and labeling is 19905 * correct for all installed apps. 19906 */ 19907 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19908 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19909 + Integer.toHexString(flags)); 19910 19911 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19912 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19913 19914 // First look for stale data that doesn't belong, and check if things 19915 // have changed since we did our last restorecon 19916 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19917 if (StorageManager.isFileEncryptedNativeOrEmulated() 19918 && !StorageManager.isUserKeyUnlocked(userId)) { 19919 throw new RuntimeException( 19920 "Yikes, someone asked us to reconcile CE storage while " + userId 19921 + " was still locked; this would have caused massive data loss!"); 19922 } 19923 19924 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19925 for (File file : files) { 19926 final String packageName = file.getName(); 19927 try { 19928 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19929 } catch (PackageManagerException e) { 19930 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19931 try { 19932 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19933 StorageManager.FLAG_STORAGE_CE, 0); 19934 } catch (InstallerException e2) { 19935 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19936 } 19937 } 19938 } 19939 } 19940 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19941 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19942 for (File file : files) { 19943 final String packageName = file.getName(); 19944 try { 19945 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19946 } catch (PackageManagerException e) { 19947 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19948 try { 19949 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19950 StorageManager.FLAG_STORAGE_DE, 0); 19951 } catch (InstallerException e2) { 19952 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19953 } 19954 } 19955 } 19956 } 19957 19958 // Ensure that data directories are ready to roll for all packages 19959 // installed for this volume and user 19960 final List<PackageSetting> packages; 19961 synchronized (mPackages) { 19962 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19963 } 19964 int preparedCount = 0; 19965 for (PackageSetting ps : packages) { 19966 final String packageName = ps.name; 19967 if (ps.pkg == null) { 19968 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19969 // TODO: might be due to legacy ASEC apps; we should circle back 19970 // and reconcile again once they're scanned 19971 continue; 19972 } 19973 19974 if (ps.getInstalled(userId)) { 19975 prepareAppDataLIF(ps.pkg, userId, flags); 19976 19977 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19978 // We may have just shuffled around app data directories, so 19979 // prepare them one more time 19980 prepareAppDataLIF(ps.pkg, userId, flags); 19981 } 19982 19983 preparedCount++; 19984 } 19985 } 19986 19987 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 19988 } 19989 19990 /** 19991 * Prepare app data for the given app just after it was installed or 19992 * upgraded. This method carefully only touches users that it's installed 19993 * for, and it forces a restorecon to handle any seinfo changes. 19994 * <p> 19995 * Verifies that directories exist and that ownership and labeling is 19996 * correct for all installed apps. If there is an ownership mismatch, it 19997 * will try recovering system apps by wiping data; third-party app data is 19998 * left intact. 19999 * <p> 20000 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 20001 */ 20002 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 20003 final PackageSetting ps; 20004 synchronized (mPackages) { 20005 ps = mSettings.mPackages.get(pkg.packageName); 20006 mSettings.writeKernelMappingLPr(ps); 20007 } 20008 20009 final UserManager um = mContext.getSystemService(UserManager.class); 20010 UserManagerInternal umInternal = getUserManagerInternal(); 20011 for (UserInfo user : um.getUsers()) { 20012 final int flags; 20013 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20014 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20015 } else if (umInternal.isUserRunning(user.id)) { 20016 flags = StorageManager.FLAG_STORAGE_DE; 20017 } else { 20018 continue; 20019 } 20020 20021 if (ps.getInstalled(user.id)) { 20022 // TODO: when user data is locked, mark that we're still dirty 20023 prepareAppDataLIF(pkg, user.id, flags); 20024 } 20025 } 20026 } 20027 20028 /** 20029 * Prepare app data for the given app. 20030 * <p> 20031 * Verifies that directories exist and that ownership and labeling is 20032 * correct for all installed apps. If there is an ownership mismatch, this 20033 * will try recovering system apps by wiping data; third-party app data is 20034 * left intact. 20035 */ 20036 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 20037 if (pkg == null) { 20038 Slog.wtf(TAG, "Package was null!", new Throwable()); 20039 return; 20040 } 20041 prepareAppDataLeafLIF(pkg, userId, flags); 20042 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20043 for (int i = 0; i < childCount; i++) { 20044 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 20045 } 20046 } 20047 20048 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20049 if (DEBUG_APP_DATA) { 20050 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 20051 + Integer.toHexString(flags)); 20052 } 20053 20054 final String volumeUuid = pkg.volumeUuid; 20055 final String packageName = pkg.packageName; 20056 final ApplicationInfo app = pkg.applicationInfo; 20057 final int appId = UserHandle.getAppId(app.uid); 20058 20059 Preconditions.checkNotNull(app.seinfo); 20060 20061 long ceDataInode = -1; 20062 try { 20063 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20064 appId, app.seinfo, app.targetSdkVersion); 20065 } catch (InstallerException e) { 20066 if (app.isSystemApp()) { 20067 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 20068 + ", but trying to recover: " + e); 20069 destroyAppDataLeafLIF(pkg, userId, flags); 20070 try { 20071 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20072 appId, app.seinfo, app.targetSdkVersion); 20073 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 20074 } catch (InstallerException e2) { 20075 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 20076 } 20077 } else { 20078 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 20079 } 20080 } 20081 20082 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 20083 // TODO: mark this structure as dirty so we persist it! 20084 synchronized (mPackages) { 20085 final PackageSetting ps = mSettings.mPackages.get(packageName); 20086 if (ps != null) { 20087 ps.setCeDataInode(ceDataInode, userId); 20088 } 20089 } 20090 } 20091 20092 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20093 } 20094 20095 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 20096 if (pkg == null) { 20097 Slog.wtf(TAG, "Package was null!", new Throwable()); 20098 return; 20099 } 20100 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20101 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20102 for (int i = 0; i < childCount; i++) { 20103 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 20104 } 20105 } 20106 20107 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20108 final String volumeUuid = pkg.volumeUuid; 20109 final String packageName = pkg.packageName; 20110 final ApplicationInfo app = pkg.applicationInfo; 20111 20112 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20113 // Create a native library symlink only if we have native libraries 20114 // and if the native libraries are 32 bit libraries. We do not provide 20115 // this symlink for 64 bit libraries. 20116 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20117 final String nativeLibPath = app.nativeLibraryDir; 20118 try { 20119 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20120 nativeLibPath, userId); 20121 } catch (InstallerException e) { 20122 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20123 } 20124 } 20125 } 20126 } 20127 20128 /** 20129 * For system apps on non-FBE devices, this method migrates any existing 20130 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20131 * requested by the app. 20132 */ 20133 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20134 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20135 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20136 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20137 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20138 try { 20139 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20140 storageTarget); 20141 } catch (InstallerException e) { 20142 logCriticalInfo(Log.WARN, 20143 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20144 } 20145 return true; 20146 } else { 20147 return false; 20148 } 20149 } 20150 20151 public PackageFreezer freezePackage(String packageName, String killReason) { 20152 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20153 } 20154 20155 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20156 return new PackageFreezer(packageName, userId, killReason); 20157 } 20158 20159 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20160 String killReason) { 20161 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20162 } 20163 20164 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20165 String killReason) { 20166 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20167 return new PackageFreezer(); 20168 } else { 20169 return freezePackage(packageName, userId, killReason); 20170 } 20171 } 20172 20173 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20174 String killReason) { 20175 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20176 } 20177 20178 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20179 String killReason) { 20180 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20181 return new PackageFreezer(); 20182 } else { 20183 return freezePackage(packageName, userId, killReason); 20184 } 20185 } 20186 20187 /** 20188 * Class that freezes and kills the given package upon creation, and 20189 * unfreezes it upon closing. This is typically used when doing surgery on 20190 * app code/data to prevent the app from running while you're working. 20191 */ 20192 private class PackageFreezer implements AutoCloseable { 20193 private final String mPackageName; 20194 private final PackageFreezer[] mChildren; 20195 20196 private final boolean mWeFroze; 20197 20198 private final AtomicBoolean mClosed = new AtomicBoolean(); 20199 private final CloseGuard mCloseGuard = CloseGuard.get(); 20200 20201 /** 20202 * Create and return a stub freezer that doesn't actually do anything, 20203 * typically used when someone requested 20204 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20205 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20206 */ 20207 public PackageFreezer() { 20208 mPackageName = null; 20209 mChildren = null; 20210 mWeFroze = false; 20211 mCloseGuard.open("close"); 20212 } 20213 20214 public PackageFreezer(String packageName, int userId, String killReason) { 20215 synchronized (mPackages) { 20216 mPackageName = packageName; 20217 mWeFroze = mFrozenPackages.add(mPackageName); 20218 20219 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20220 if (ps != null) { 20221 killApplication(ps.name, ps.appId, userId, killReason); 20222 } 20223 20224 final PackageParser.Package p = mPackages.get(packageName); 20225 if (p != null && p.childPackages != null) { 20226 final int N = p.childPackages.size(); 20227 mChildren = new PackageFreezer[N]; 20228 for (int i = 0; i < N; i++) { 20229 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20230 userId, killReason); 20231 } 20232 } else { 20233 mChildren = null; 20234 } 20235 } 20236 mCloseGuard.open("close"); 20237 } 20238 20239 @Override 20240 protected void finalize() throws Throwable { 20241 try { 20242 mCloseGuard.warnIfOpen(); 20243 close(); 20244 } finally { 20245 super.finalize(); 20246 } 20247 } 20248 20249 @Override 20250 public void close() { 20251 mCloseGuard.close(); 20252 if (mClosed.compareAndSet(false, true)) { 20253 synchronized (mPackages) { 20254 if (mWeFroze) { 20255 mFrozenPackages.remove(mPackageName); 20256 } 20257 20258 if (mChildren != null) { 20259 for (PackageFreezer freezer : mChildren) { 20260 freezer.close(); 20261 } 20262 } 20263 } 20264 } 20265 } 20266 } 20267 20268 /** 20269 * Verify that given package is currently frozen. 20270 */ 20271 private void checkPackageFrozen(String packageName) { 20272 synchronized (mPackages) { 20273 if (!mFrozenPackages.contains(packageName)) { 20274 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20275 } 20276 } 20277 } 20278 20279 @Override 20280 public int movePackage(final String packageName, final String volumeUuid) { 20281 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20282 20283 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20284 final int moveId = mNextMoveId.getAndIncrement(); 20285 mHandler.post(new Runnable() { 20286 @Override 20287 public void run() { 20288 try { 20289 movePackageInternal(packageName, volumeUuid, moveId, user); 20290 } catch (PackageManagerException e) { 20291 Slog.w(TAG, "Failed to move " + packageName, e); 20292 mMoveCallbacks.notifyStatusChanged(moveId, 20293 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20294 } 20295 } 20296 }); 20297 return moveId; 20298 } 20299 20300 private void movePackageInternal(final String packageName, final String volumeUuid, 20301 final int moveId, UserHandle user) throws PackageManagerException { 20302 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20303 final PackageManager pm = mContext.getPackageManager(); 20304 20305 final boolean currentAsec; 20306 final String currentVolumeUuid; 20307 final File codeFile; 20308 final String installerPackageName; 20309 final String packageAbiOverride; 20310 final int appId; 20311 final String seinfo; 20312 final String label; 20313 final int targetSdkVersion; 20314 final PackageFreezer freezer; 20315 final int[] installedUserIds; 20316 20317 // reader 20318 synchronized (mPackages) { 20319 final PackageParser.Package pkg = mPackages.get(packageName); 20320 final PackageSetting ps = mSettings.mPackages.get(packageName); 20321 if (pkg == null || ps == null) { 20322 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20323 } 20324 20325 if (pkg.applicationInfo.isSystemApp()) { 20326 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20327 "Cannot move system application"); 20328 } 20329 20330 if (pkg.applicationInfo.isExternalAsec()) { 20331 currentAsec = true; 20332 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20333 } else if (pkg.applicationInfo.isForwardLocked()) { 20334 currentAsec = true; 20335 currentVolumeUuid = "forward_locked"; 20336 } else { 20337 currentAsec = false; 20338 currentVolumeUuid = ps.volumeUuid; 20339 20340 final File probe = new File(pkg.codePath); 20341 final File probeOat = new File(probe, "oat"); 20342 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20343 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20344 "Move only supported for modern cluster style installs"); 20345 } 20346 } 20347 20348 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20349 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20350 "Package already moved to " + volumeUuid); 20351 } 20352 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20353 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20354 "Device admin cannot be moved"); 20355 } 20356 20357 if (mFrozenPackages.contains(packageName)) { 20358 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20359 "Failed to move already frozen package"); 20360 } 20361 20362 codeFile = new File(pkg.codePath); 20363 installerPackageName = ps.installerPackageName; 20364 packageAbiOverride = ps.cpuAbiOverrideString; 20365 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20366 seinfo = pkg.applicationInfo.seinfo; 20367 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20368 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20369 freezer = freezePackage(packageName, "movePackageInternal"); 20370 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20371 } 20372 20373 final Bundle extras = new Bundle(); 20374 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20375 extras.putString(Intent.EXTRA_TITLE, label); 20376 mMoveCallbacks.notifyCreated(moveId, extras); 20377 20378 int installFlags; 20379 final boolean moveCompleteApp; 20380 final File measurePath; 20381 20382 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20383 installFlags = INSTALL_INTERNAL; 20384 moveCompleteApp = !currentAsec; 20385 measurePath = Environment.getDataAppDirectory(volumeUuid); 20386 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20387 installFlags = INSTALL_EXTERNAL; 20388 moveCompleteApp = false; 20389 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20390 } else { 20391 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20392 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20393 || !volume.isMountedWritable()) { 20394 freezer.close(); 20395 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20396 "Move location not mounted private volume"); 20397 } 20398 20399 Preconditions.checkState(!currentAsec); 20400 20401 installFlags = INSTALL_INTERNAL; 20402 moveCompleteApp = true; 20403 measurePath = Environment.getDataAppDirectory(volumeUuid); 20404 } 20405 20406 final PackageStats stats = new PackageStats(null, -1); 20407 synchronized (mInstaller) { 20408 for (int userId : installedUserIds) { 20409 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20410 freezer.close(); 20411 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20412 "Failed to measure package size"); 20413 } 20414 } 20415 } 20416 20417 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20418 + stats.dataSize); 20419 20420 final long startFreeBytes = measurePath.getFreeSpace(); 20421 final long sizeBytes; 20422 if (moveCompleteApp) { 20423 sizeBytes = stats.codeSize + stats.dataSize; 20424 } else { 20425 sizeBytes = stats.codeSize; 20426 } 20427 20428 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20429 freezer.close(); 20430 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20431 "Not enough free space to move"); 20432 } 20433 20434 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20435 20436 final CountDownLatch installedLatch = new CountDownLatch(1); 20437 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20438 @Override 20439 public void onUserActionRequired(Intent intent) throws RemoteException { 20440 throw new IllegalStateException(); 20441 } 20442 20443 @Override 20444 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20445 Bundle extras) throws RemoteException { 20446 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20447 + PackageManager.installStatusToString(returnCode, msg)); 20448 20449 installedLatch.countDown(); 20450 freezer.close(); 20451 20452 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20453 switch (status) { 20454 case PackageInstaller.STATUS_SUCCESS: 20455 mMoveCallbacks.notifyStatusChanged(moveId, 20456 PackageManager.MOVE_SUCCEEDED); 20457 break; 20458 case PackageInstaller.STATUS_FAILURE_STORAGE: 20459 mMoveCallbacks.notifyStatusChanged(moveId, 20460 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20461 break; 20462 default: 20463 mMoveCallbacks.notifyStatusChanged(moveId, 20464 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20465 break; 20466 } 20467 } 20468 }; 20469 20470 final MoveInfo move; 20471 if (moveCompleteApp) { 20472 // Kick off a thread to report progress estimates 20473 new Thread() { 20474 @Override 20475 public void run() { 20476 while (true) { 20477 try { 20478 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20479 break; 20480 } 20481 } catch (InterruptedException ignored) { 20482 } 20483 20484 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20485 final int progress = 10 + (int) MathUtils.constrain( 20486 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20487 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20488 } 20489 } 20490 }.start(); 20491 20492 final String dataAppName = codeFile.getName(); 20493 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20494 dataAppName, appId, seinfo, targetSdkVersion); 20495 } else { 20496 move = null; 20497 } 20498 20499 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20500 20501 final Message msg = mHandler.obtainMessage(INIT_COPY); 20502 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20503 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20504 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20505 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20506 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20507 msg.obj = params; 20508 20509 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20510 System.identityHashCode(msg.obj)); 20511 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20512 System.identityHashCode(msg.obj)); 20513 20514 mHandler.sendMessage(msg); 20515 } 20516 20517 @Override 20518 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20519 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20520 20521 final int realMoveId = mNextMoveId.getAndIncrement(); 20522 final Bundle extras = new Bundle(); 20523 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20524 mMoveCallbacks.notifyCreated(realMoveId, extras); 20525 20526 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20527 @Override 20528 public void onCreated(int moveId, Bundle extras) { 20529 // Ignored 20530 } 20531 20532 @Override 20533 public void onStatusChanged(int moveId, int status, long estMillis) { 20534 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20535 } 20536 }; 20537 20538 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20539 storage.setPrimaryStorageUuid(volumeUuid, callback); 20540 return realMoveId; 20541 } 20542 20543 @Override 20544 public int getMoveStatus(int moveId) { 20545 mContext.enforceCallingOrSelfPermission( 20546 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20547 return mMoveCallbacks.mLastStatus.get(moveId); 20548 } 20549 20550 @Override 20551 public void registerMoveCallback(IPackageMoveObserver callback) { 20552 mContext.enforceCallingOrSelfPermission( 20553 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20554 mMoveCallbacks.register(callback); 20555 } 20556 20557 @Override 20558 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20559 mContext.enforceCallingOrSelfPermission( 20560 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20561 mMoveCallbacks.unregister(callback); 20562 } 20563 20564 @Override 20565 public boolean setInstallLocation(int loc) { 20566 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20567 null); 20568 if (getInstallLocation() == loc) { 20569 return true; 20570 } 20571 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20572 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20573 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20574 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20575 return true; 20576 } 20577 return false; 20578 } 20579 20580 @Override 20581 public int getInstallLocation() { 20582 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20583 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20584 PackageHelper.APP_INSTALL_AUTO); 20585 } 20586 20587 /** Called by UserManagerService */ 20588 void cleanUpUser(UserManagerService userManager, int userHandle) { 20589 synchronized (mPackages) { 20590 mDirtyUsers.remove(userHandle); 20591 mUserNeedsBadging.delete(userHandle); 20592 mSettings.removeUserLPw(userHandle); 20593 mPendingBroadcasts.remove(userHandle); 20594 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20595 removeUnusedPackagesLPw(userManager, userHandle); 20596 } 20597 } 20598 20599 /** 20600 * We're removing userHandle and would like to remove any downloaded packages 20601 * that are no longer in use by any other user. 20602 * @param userHandle the user being removed 20603 */ 20604 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20605 final boolean DEBUG_CLEAN_APKS = false; 20606 int [] users = userManager.getUserIds(); 20607 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20608 while (psit.hasNext()) { 20609 PackageSetting ps = psit.next(); 20610 if (ps.pkg == null) { 20611 continue; 20612 } 20613 final String packageName = ps.pkg.packageName; 20614 // Skip over if system app 20615 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20616 continue; 20617 } 20618 if (DEBUG_CLEAN_APKS) { 20619 Slog.i(TAG, "Checking package " + packageName); 20620 } 20621 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20622 if (keep) { 20623 if (DEBUG_CLEAN_APKS) { 20624 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20625 } 20626 } else { 20627 for (int i = 0; i < users.length; i++) { 20628 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20629 keep = true; 20630 if (DEBUG_CLEAN_APKS) { 20631 Slog.i(TAG, " Keeping package " + packageName + " for user " 20632 + users[i]); 20633 } 20634 break; 20635 } 20636 } 20637 } 20638 if (!keep) { 20639 if (DEBUG_CLEAN_APKS) { 20640 Slog.i(TAG, " Removing package " + packageName); 20641 } 20642 mHandler.post(new Runnable() { 20643 public void run() { 20644 deletePackageX(packageName, userHandle, 0); 20645 } //end run 20646 }); 20647 } 20648 } 20649 } 20650 20651 /** Called by UserManagerService */ 20652 void createNewUser(int userId) { 20653 synchronized (mInstallLock) { 20654 mSettings.createNewUserLI(this, mInstaller, userId); 20655 } 20656 synchronized (mPackages) { 20657 scheduleWritePackageRestrictionsLocked(userId); 20658 scheduleWritePackageListLocked(userId); 20659 applyFactoryDefaultBrowserLPw(userId); 20660 primeDomainVerificationsLPw(userId); 20661 } 20662 } 20663 20664 void onNewUserCreated(final int userId) { 20665 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20666 // If permission review for legacy apps is required, we represent 20667 // dagerous permissions for such apps as always granted runtime 20668 // permissions to keep per user flag state whether review is needed. 20669 // Hence, if a new user is added we have to propagate dangerous 20670 // permission grants for these legacy apps. 20671 if (mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) { 20672 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20673 | UPDATE_PERMISSIONS_REPLACE_ALL); 20674 } 20675 } 20676 20677 @Override 20678 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20679 mContext.enforceCallingOrSelfPermission( 20680 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20681 "Only package verification agents can read the verifier device identity"); 20682 20683 synchronized (mPackages) { 20684 return mSettings.getVerifierDeviceIdentityLPw(); 20685 } 20686 } 20687 20688 @Override 20689 public void setPermissionEnforced(String permission, boolean enforced) { 20690 // TODO: Now that we no longer change GID for storage, this should to away. 20691 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20692 "setPermissionEnforced"); 20693 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20694 synchronized (mPackages) { 20695 if (mSettings.mReadExternalStorageEnforced == null 20696 || mSettings.mReadExternalStorageEnforced != enforced) { 20697 mSettings.mReadExternalStorageEnforced = enforced; 20698 mSettings.writeLPr(); 20699 } 20700 } 20701 // kill any non-foreground processes so we restart them and 20702 // grant/revoke the GID. 20703 final IActivityManager am = ActivityManagerNative.getDefault(); 20704 if (am != null) { 20705 final long token = Binder.clearCallingIdentity(); 20706 try { 20707 am.killProcessesBelowForeground("setPermissionEnforcement"); 20708 } catch (RemoteException e) { 20709 } finally { 20710 Binder.restoreCallingIdentity(token); 20711 } 20712 } 20713 } else { 20714 throw new IllegalArgumentException("No selective enforcement for " + permission); 20715 } 20716 } 20717 20718 @Override 20719 @Deprecated 20720 public boolean isPermissionEnforced(String permission) { 20721 return true; 20722 } 20723 20724 @Override 20725 public boolean isStorageLow() { 20726 final long token = Binder.clearCallingIdentity(); 20727 try { 20728 final DeviceStorageMonitorInternal 20729 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20730 if (dsm != null) { 20731 return dsm.isMemoryLow(); 20732 } else { 20733 return false; 20734 } 20735 } finally { 20736 Binder.restoreCallingIdentity(token); 20737 } 20738 } 20739 20740 @Override 20741 public IPackageInstaller getPackageInstaller() { 20742 return mInstallerService; 20743 } 20744 20745 private boolean userNeedsBadging(int userId) { 20746 int index = mUserNeedsBadging.indexOfKey(userId); 20747 if (index < 0) { 20748 final UserInfo userInfo; 20749 final long token = Binder.clearCallingIdentity(); 20750 try { 20751 userInfo = sUserManager.getUserInfo(userId); 20752 } finally { 20753 Binder.restoreCallingIdentity(token); 20754 } 20755 final boolean b; 20756 if (userInfo != null && userInfo.isManagedProfile()) { 20757 b = true; 20758 } else { 20759 b = false; 20760 } 20761 mUserNeedsBadging.put(userId, b); 20762 return b; 20763 } 20764 return mUserNeedsBadging.valueAt(index); 20765 } 20766 20767 @Override 20768 public KeySet getKeySetByAlias(String packageName, String alias) { 20769 if (packageName == null || alias == null) { 20770 return null; 20771 } 20772 synchronized(mPackages) { 20773 final PackageParser.Package pkg = mPackages.get(packageName); 20774 if (pkg == null) { 20775 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20776 throw new IllegalArgumentException("Unknown package: " + packageName); 20777 } 20778 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20779 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20780 } 20781 } 20782 20783 @Override 20784 public KeySet getSigningKeySet(String packageName) { 20785 if (packageName == null) { 20786 return null; 20787 } 20788 synchronized(mPackages) { 20789 final PackageParser.Package pkg = mPackages.get(packageName); 20790 if (pkg == null) { 20791 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20792 throw new IllegalArgumentException("Unknown package: " + packageName); 20793 } 20794 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20795 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20796 throw new SecurityException("May not access signing KeySet of other apps."); 20797 } 20798 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20799 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20800 } 20801 } 20802 20803 @Override 20804 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20805 if (packageName == null || ks == null) { 20806 return false; 20807 } 20808 synchronized(mPackages) { 20809 final PackageParser.Package pkg = mPackages.get(packageName); 20810 if (pkg == null) { 20811 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20812 throw new IllegalArgumentException("Unknown package: " + packageName); 20813 } 20814 IBinder ksh = ks.getToken(); 20815 if (ksh instanceof KeySetHandle) { 20816 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20817 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20818 } 20819 return false; 20820 } 20821 } 20822 20823 @Override 20824 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20825 if (packageName == null || ks == null) { 20826 return false; 20827 } 20828 synchronized(mPackages) { 20829 final PackageParser.Package pkg = mPackages.get(packageName); 20830 if (pkg == null) { 20831 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20832 throw new IllegalArgumentException("Unknown package: " + packageName); 20833 } 20834 IBinder ksh = ks.getToken(); 20835 if (ksh instanceof KeySetHandle) { 20836 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20837 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20838 } 20839 return false; 20840 } 20841 } 20842 20843 private void deletePackageIfUnusedLPr(final String packageName) { 20844 PackageSetting ps = mSettings.mPackages.get(packageName); 20845 if (ps == null) { 20846 return; 20847 } 20848 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20849 // TODO Implement atomic delete if package is unused 20850 // It is currently possible that the package will be deleted even if it is installed 20851 // after this method returns. 20852 mHandler.post(new Runnable() { 20853 public void run() { 20854 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20855 } 20856 }); 20857 } 20858 } 20859 20860 /** 20861 * Check and throw if the given before/after packages would be considered a 20862 * downgrade. 20863 */ 20864 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20865 throws PackageManagerException { 20866 if (after.versionCode < before.mVersionCode) { 20867 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20868 "Update version code " + after.versionCode + " is older than current " 20869 + before.mVersionCode); 20870 } else if (after.versionCode == before.mVersionCode) { 20871 if (after.baseRevisionCode < before.baseRevisionCode) { 20872 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20873 "Update base revision code " + after.baseRevisionCode 20874 + " is older than current " + before.baseRevisionCode); 20875 } 20876 20877 if (!ArrayUtils.isEmpty(after.splitNames)) { 20878 for (int i = 0; i < after.splitNames.length; i++) { 20879 final String splitName = after.splitNames[i]; 20880 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20881 if (j != -1) { 20882 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20883 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20884 "Update split " + splitName + " revision code " 20885 + after.splitRevisionCodes[i] + " is older than current " 20886 + before.splitRevisionCodes[j]); 20887 } 20888 } 20889 } 20890 } 20891 } 20892 } 20893 20894 private static class MoveCallbacks extends Handler { 20895 private static final int MSG_CREATED = 1; 20896 private static final int MSG_STATUS_CHANGED = 2; 20897 20898 private final RemoteCallbackList<IPackageMoveObserver> 20899 mCallbacks = new RemoteCallbackList<>(); 20900 20901 private final SparseIntArray mLastStatus = new SparseIntArray(); 20902 20903 public MoveCallbacks(Looper looper) { 20904 super(looper); 20905 } 20906 20907 public void register(IPackageMoveObserver callback) { 20908 mCallbacks.register(callback); 20909 } 20910 20911 public void unregister(IPackageMoveObserver callback) { 20912 mCallbacks.unregister(callback); 20913 } 20914 20915 @Override 20916 public void handleMessage(Message msg) { 20917 final SomeArgs args = (SomeArgs) msg.obj; 20918 final int n = mCallbacks.beginBroadcast(); 20919 for (int i = 0; i < n; i++) { 20920 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20921 try { 20922 invokeCallback(callback, msg.what, args); 20923 } catch (RemoteException ignored) { 20924 } 20925 } 20926 mCallbacks.finishBroadcast(); 20927 args.recycle(); 20928 } 20929 20930 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20931 throws RemoteException { 20932 switch (what) { 20933 case MSG_CREATED: { 20934 callback.onCreated(args.argi1, (Bundle) args.arg2); 20935 break; 20936 } 20937 case MSG_STATUS_CHANGED: { 20938 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20939 break; 20940 } 20941 } 20942 } 20943 20944 private void notifyCreated(int moveId, Bundle extras) { 20945 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20946 20947 final SomeArgs args = SomeArgs.obtain(); 20948 args.argi1 = moveId; 20949 args.arg2 = extras; 20950 obtainMessage(MSG_CREATED, args).sendToTarget(); 20951 } 20952 20953 private void notifyStatusChanged(int moveId, int status) { 20954 notifyStatusChanged(moveId, status, -1); 20955 } 20956 20957 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20958 Slog.v(TAG, "Move " + moveId + " status " + status); 20959 20960 final SomeArgs args = SomeArgs.obtain(); 20961 args.argi1 = moveId; 20962 args.argi2 = status; 20963 args.arg3 = estMillis; 20964 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20965 20966 synchronized (mLastStatus) { 20967 mLastStatus.put(moveId, status); 20968 } 20969 } 20970 } 20971 20972 private final static class OnPermissionChangeListeners extends Handler { 20973 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20974 20975 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20976 new RemoteCallbackList<>(); 20977 20978 public OnPermissionChangeListeners(Looper looper) { 20979 super(looper); 20980 } 20981 20982 @Override 20983 public void handleMessage(Message msg) { 20984 switch (msg.what) { 20985 case MSG_ON_PERMISSIONS_CHANGED: { 20986 final int uid = msg.arg1; 20987 handleOnPermissionsChanged(uid); 20988 } break; 20989 } 20990 } 20991 20992 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20993 mPermissionListeners.register(listener); 20994 20995 } 20996 20997 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20998 mPermissionListeners.unregister(listener); 20999 } 21000 21001 public void onPermissionsChanged(int uid) { 21002 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 21003 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 21004 } 21005 } 21006 21007 private void handleOnPermissionsChanged(int uid) { 21008 final int count = mPermissionListeners.beginBroadcast(); 21009 try { 21010 for (int i = 0; i < count; i++) { 21011 IOnPermissionsChangeListener callback = mPermissionListeners 21012 .getBroadcastItem(i); 21013 try { 21014 callback.onPermissionsChanged(uid); 21015 } catch (RemoteException e) { 21016 Log.e(TAG, "Permission listener is dead", e); 21017 } 21018 } 21019 } finally { 21020 mPermissionListeners.finishBroadcast(); 21021 } 21022 } 21023 } 21024 21025 private class PackageManagerInternalImpl extends PackageManagerInternal { 21026 @Override 21027 public void setLocationPackagesProvider(PackagesProvider provider) { 21028 synchronized (mPackages) { 21029 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 21030 } 21031 } 21032 21033 @Override 21034 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 21035 synchronized (mPackages) { 21036 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 21037 } 21038 } 21039 21040 @Override 21041 public void setSmsAppPackagesProvider(PackagesProvider provider) { 21042 synchronized (mPackages) { 21043 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 21044 } 21045 } 21046 21047 @Override 21048 public void setDialerAppPackagesProvider(PackagesProvider provider) { 21049 synchronized (mPackages) { 21050 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 21051 } 21052 } 21053 21054 @Override 21055 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 21056 synchronized (mPackages) { 21057 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 21058 } 21059 } 21060 21061 @Override 21062 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 21063 synchronized (mPackages) { 21064 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 21065 } 21066 } 21067 21068 @Override 21069 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 21070 synchronized (mPackages) { 21071 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 21072 packageName, userId); 21073 } 21074 } 21075 21076 @Override 21077 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 21078 synchronized (mPackages) { 21079 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 21080 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 21081 packageName, userId); 21082 } 21083 } 21084 21085 @Override 21086 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 21087 synchronized (mPackages) { 21088 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 21089 packageName, userId); 21090 } 21091 } 21092 21093 @Override 21094 public void setKeepUninstalledPackages(final List<String> packageList) { 21095 Preconditions.checkNotNull(packageList); 21096 List<String> removedFromList = null; 21097 synchronized (mPackages) { 21098 if (mKeepUninstalledPackages != null) { 21099 final int packagesCount = mKeepUninstalledPackages.size(); 21100 for (int i = 0; i < packagesCount; i++) { 21101 String oldPackage = mKeepUninstalledPackages.get(i); 21102 if (packageList != null && packageList.contains(oldPackage)) { 21103 continue; 21104 } 21105 if (removedFromList == null) { 21106 removedFromList = new ArrayList<>(); 21107 } 21108 removedFromList.add(oldPackage); 21109 } 21110 } 21111 mKeepUninstalledPackages = new ArrayList<>(packageList); 21112 if (removedFromList != null) { 21113 final int removedCount = removedFromList.size(); 21114 for (int i = 0; i < removedCount; i++) { 21115 deletePackageIfUnusedLPr(removedFromList.get(i)); 21116 } 21117 } 21118 } 21119 } 21120 21121 @Override 21122 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21123 synchronized (mPackages) { 21124 // If we do not support permission review, done. 21125 if (!mPermissionReviewRequired && !Build.PERMISSIONS_REVIEW_REQUIRED) { 21126 return false; 21127 } 21128 21129 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21130 if (packageSetting == null) { 21131 return false; 21132 } 21133 21134 // Permission review applies only to apps not supporting the new permission model. 21135 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21136 return false; 21137 } 21138 21139 // Legacy apps have the permission and get user consent on launch. 21140 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21141 return permissionsState.isPermissionReviewRequired(userId); 21142 } 21143 } 21144 21145 @Override 21146 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21147 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21148 } 21149 21150 @Override 21151 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21152 int userId) { 21153 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21154 } 21155 21156 @Override 21157 public void setDeviceAndProfileOwnerPackages( 21158 int deviceOwnerUserId, String deviceOwnerPackage, 21159 SparseArray<String> profileOwnerPackages) { 21160 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21161 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21162 } 21163 21164 @Override 21165 public boolean isPackageDataProtected(int userId, String packageName) { 21166 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21167 } 21168 21169 @Override 21170 public boolean wasPackageEverLaunched(String packageName, int userId) { 21171 synchronized (mPackages) { 21172 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21173 } 21174 } 21175 } 21176 21177 @Override 21178 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21179 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21180 synchronized (mPackages) { 21181 final long identity = Binder.clearCallingIdentity(); 21182 try { 21183 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21184 packageNames, userId); 21185 } finally { 21186 Binder.restoreCallingIdentity(identity); 21187 } 21188 } 21189 } 21190 21191 @Override 21192 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 21193 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 21194 synchronized (mPackages) { 21195 final long identity = Binder.clearCallingIdentity(); 21196 try { 21197 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 21198 packageNames, userId); 21199 } finally { 21200 Binder.restoreCallingIdentity(identity); 21201 } 21202 } 21203 } 21204 21205 private static void enforceSystemOrPhoneCaller(String tag) { 21206 int callingUid = Binder.getCallingUid(); 21207 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21208 throw new SecurityException( 21209 "Cannot call " + tag + " from UID " + callingUid); 21210 } 21211 } 21212 21213 boolean isHistoricalPackageUsageAvailable() { 21214 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21215 } 21216 21217 /** 21218 * Return a <b>copy</b> of the collection of packages known to the package manager. 21219 * @return A copy of the values of mPackages. 21220 */ 21221 Collection<PackageParser.Package> getPackages() { 21222 synchronized (mPackages) { 21223 return new ArrayList<>(mPackages.values()); 21224 } 21225 } 21226 21227 /** 21228 * Logs process start information (including base APK hash) to the security log. 21229 * @hide 21230 */ 21231 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21232 String apkFile, int pid) { 21233 if (!SecurityLog.isLoggingEnabled()) { 21234 return; 21235 } 21236 Bundle data = new Bundle(); 21237 data.putLong("startTimestamp", System.currentTimeMillis()); 21238 data.putString("processName", processName); 21239 data.putInt("uid", uid); 21240 data.putString("seinfo", seinfo); 21241 data.putString("apkFile", apkFile); 21242 data.putInt("pid", pid); 21243 Message msg = mProcessLoggingHandler.obtainMessage( 21244 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21245 msg.setData(data); 21246 mProcessLoggingHandler.sendMessage(msg); 21247 } 21248 21249 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21250 return mCompilerStats.getPackageStats(pkgName); 21251 } 21252 21253 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21254 return getOrCreateCompilerPackageStats(pkg.packageName); 21255 } 21256 21257 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21258 return mCompilerStats.getOrCreatePackageStats(pkgName); 21259 } 21260 21261 public void deleteCompilerPackageStats(String pkgName) { 21262 mCompilerStats.deletePackageStats(pkgName); 21263 } 21264} 21265