PackageManagerService.java revision 44f1b306663f2b9b04934c05dc35640821419c59
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_ANY_USER; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 69import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 70import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 71import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 72import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 73import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 74import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 75import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 76import static android.content.pm.PackageManager.PERMISSION_DENIED; 77import static android.content.pm.PackageManager.PERMISSION_GRANTED; 78import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 79import static android.content.pm.PackageParser.isApkFile; 80import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 81import static android.system.OsConstants.O_CREAT; 82import static android.system.OsConstants.O_RDWR; 83 84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 86import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 87import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 88import static com.android.internal.util.ArrayUtils.appendInt; 89import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 90import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 93import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 94import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 101 102import android.Manifest; 103import android.annotation.NonNull; 104import android.annotation.Nullable; 105import android.annotation.UserIdInt; 106import android.app.ActivityManager; 107import android.app.AppOpsManager; 108import android.app.IActivityManager; 109import android.app.ResourcesManager; 110import android.app.admin.IDevicePolicyManager; 111import android.app.admin.SecurityLog; 112import android.app.backup.IBackupManager; 113import android.content.BroadcastReceiver; 114import android.content.ComponentName; 115import android.content.ContentResolver; 116import android.content.Context; 117import android.content.IIntentReceiver; 118import android.content.Intent; 119import android.content.IntentFilter; 120import android.content.IntentSender; 121import android.content.IntentSender.SendIntentException; 122import android.content.ServiceConnection; 123import android.content.pm.ActivityInfo; 124import android.content.pm.ApplicationInfo; 125import android.content.pm.AppsQueryHelper; 126import android.content.pm.ComponentInfo; 127import android.content.pm.EphemeralApplicationInfo; 128import android.content.pm.EphemeralRequest; 129import android.content.pm.EphemeralResolveInfo; 130import android.content.pm.EphemeralResponse; 131import android.content.pm.FeatureInfo; 132import android.content.pm.IOnPermissionsChangeListener; 133import android.content.pm.IPackageDataObserver; 134import android.content.pm.IPackageDeleteObserver; 135import android.content.pm.IPackageDeleteObserver2; 136import android.content.pm.IPackageInstallObserver2; 137import android.content.pm.IPackageInstaller; 138import android.content.pm.IPackageManager; 139import android.content.pm.IPackageMoveObserver; 140import android.content.pm.IPackageStatsObserver; 141import android.content.pm.InstrumentationInfo; 142import android.content.pm.IntentFilterVerificationInfo; 143import android.content.pm.KeySet; 144import android.content.pm.PackageCleanItem; 145import android.content.pm.PackageInfo; 146import android.content.pm.PackageInfoLite; 147import android.content.pm.PackageInstaller; 148import android.content.pm.PackageManager; 149import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 150import android.content.pm.PackageManagerInternal; 151import android.content.pm.PackageParser; 152import android.content.pm.PackageParser.ActivityIntentInfo; 153import android.content.pm.PackageParser.PackageLite; 154import android.content.pm.PackageParser.PackageParserException; 155import android.content.pm.PackageStats; 156import android.content.pm.PackageUserState; 157import android.content.pm.ParceledListSlice; 158import android.content.pm.PermissionGroupInfo; 159import android.content.pm.PermissionInfo; 160import android.content.pm.ProviderInfo; 161import android.content.pm.ResolveInfo; 162import android.content.pm.ServiceInfo; 163import android.content.pm.Signature; 164import android.content.pm.UserInfo; 165import android.content.pm.VerifierDeviceIdentity; 166import android.content.pm.VerifierInfo; 167import android.content.res.Resources; 168import android.graphics.Bitmap; 169import android.hardware.display.DisplayManager; 170import android.net.Uri; 171import android.os.Binder; 172import android.os.Build; 173import android.os.Bundle; 174import android.os.Debug; 175import android.os.Environment; 176import android.os.Environment.UserEnvironment; 177import android.os.FileUtils; 178import android.os.Handler; 179import android.os.IBinder; 180import android.os.Looper; 181import android.os.Message; 182import android.os.Parcel; 183import android.os.ParcelFileDescriptor; 184import android.os.PatternMatcher; 185import android.os.Process; 186import android.os.RemoteCallbackList; 187import android.os.RemoteException; 188import android.os.ResultReceiver; 189import android.os.SELinux; 190import android.os.ServiceManager; 191import android.os.ShellCallback; 192import android.os.SystemClock; 193import android.os.SystemProperties; 194import android.os.Trace; 195import android.os.UserHandle; 196import android.os.UserManager; 197import android.os.UserManagerInternal; 198import android.os.storage.IStorageManager; 199import android.os.storage.StorageManagerInternal; 200import android.os.storage.StorageEventListener; 201import android.os.storage.StorageManager; 202import android.os.storage.VolumeInfo; 203import android.os.storage.VolumeRecord; 204import android.provider.Settings.Global; 205import android.provider.Settings.Secure; 206import android.security.KeyStore; 207import android.security.SystemKeyStore; 208import android.system.ErrnoException; 209import android.system.Os; 210import android.text.TextUtils; 211import android.text.format.DateUtils; 212import android.util.ArrayMap; 213import android.util.ArraySet; 214import android.util.Base64; 215import android.util.DisplayMetrics; 216import android.util.EventLog; 217import android.util.ExceptionUtils; 218import android.util.Log; 219import android.util.LogPrinter; 220import android.util.MathUtils; 221import android.util.Pair; 222import android.util.PrintStreamPrinter; 223import android.util.Slog; 224import android.util.SparseArray; 225import android.util.SparseBooleanArray; 226import android.util.SparseIntArray; 227import android.util.Xml; 228import android.util.jar.StrictJarFile; 229import android.view.Display; 230 231import com.android.internal.R; 232import com.android.internal.annotations.GuardedBy; 233import com.android.internal.app.IMediaContainerService; 234import com.android.internal.app.ResolverActivity; 235import com.android.internal.content.NativeLibraryHelper; 236import com.android.internal.content.PackageHelper; 237import com.android.internal.logging.MetricsLogger; 238import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 239import com.android.internal.os.IParcelFileDescriptorFactory; 240import com.android.internal.os.RoSystemProperties; 241import com.android.internal.os.SomeArgs; 242import com.android.internal.os.Zygote; 243import com.android.internal.telephony.CarrierAppUtils; 244import com.android.internal.util.ArrayUtils; 245import com.android.internal.util.FastPrintWriter; 246import com.android.internal.util.FastXmlSerializer; 247import com.android.internal.util.IndentingPrintWriter; 248import com.android.internal.util.Preconditions; 249import com.android.internal.util.XmlUtils; 250import com.android.server.AttributeCache; 251import com.android.server.EventLogTags; 252import com.android.server.FgThread; 253import com.android.server.IntentResolver; 254import com.android.server.LocalServices; 255import com.android.server.ServiceThread; 256import com.android.server.SystemConfig; 257import com.android.server.Watchdog; 258import com.android.server.net.NetworkPolicyManagerInternal; 259import com.android.server.pm.Installer.InstallerException; 260import com.android.server.pm.PermissionsState.PermissionState; 261import com.android.server.pm.Settings.DatabaseVersion; 262import com.android.server.pm.Settings.VersionInfo; 263import com.android.server.pm.dex.DexManager; 264import com.android.server.storage.DeviceStorageMonitorInternal; 265 266import dalvik.system.CloseGuard; 267import dalvik.system.DexFile; 268import dalvik.system.VMRuntime; 269 270import libcore.io.IoUtils; 271import libcore.util.EmptyArray; 272 273import org.xmlpull.v1.XmlPullParser; 274import org.xmlpull.v1.XmlPullParserException; 275import org.xmlpull.v1.XmlSerializer; 276 277import java.io.BufferedOutputStream; 278import java.io.BufferedReader; 279import java.io.ByteArrayInputStream; 280import java.io.ByteArrayOutputStream; 281import java.io.File; 282import java.io.FileDescriptor; 283import java.io.FileInputStream; 284import java.io.FileNotFoundException; 285import java.io.FileOutputStream; 286import java.io.FileReader; 287import java.io.FilenameFilter; 288import java.io.IOException; 289import java.io.PrintWriter; 290import java.nio.charset.StandardCharsets; 291import java.security.DigestInputStream; 292import java.security.MessageDigest; 293import java.security.NoSuchAlgorithmException; 294import java.security.PublicKey; 295import java.security.SecureRandom; 296import java.security.cert.Certificate; 297import java.security.cert.CertificateEncodingException; 298import java.security.cert.CertificateException; 299import java.text.SimpleDateFormat; 300import java.util.ArrayList; 301import java.util.Arrays; 302import java.util.Collection; 303import java.util.Collections; 304import java.util.Comparator; 305import java.util.Date; 306import java.util.HashSet; 307import java.util.HashMap; 308import java.util.Iterator; 309import java.util.List; 310import java.util.Map; 311import java.util.Objects; 312import java.util.Set; 313import java.util.concurrent.CountDownLatch; 314import java.util.concurrent.TimeUnit; 315import java.util.concurrent.atomic.AtomicBoolean; 316import java.util.concurrent.atomic.AtomicInteger; 317 318/** 319 * Keep track of all those APKs everywhere. 320 * <p> 321 * Internally there are two important locks: 322 * <ul> 323 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 324 * and other related state. It is a fine-grained lock that should only be held 325 * momentarily, as it's one of the most contended locks in the system. 326 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 327 * operations typically involve heavy lifting of application data on disk. Since 328 * {@code installd} is single-threaded, and it's operations can often be slow, 329 * this lock should never be acquired while already holding {@link #mPackages}. 330 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 331 * holding {@link #mInstallLock}. 332 * </ul> 333 * Many internal methods rely on the caller to hold the appropriate locks, and 334 * this contract is expressed through method name suffixes: 335 * <ul> 336 * <li>fooLI(): the caller must hold {@link #mInstallLock} 337 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 338 * being modified must be frozen 339 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 340 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 341 * </ul> 342 * <p> 343 * Because this class is very central to the platform's security; please run all 344 * CTS and unit tests whenever making modifications: 345 * 346 * <pre> 347 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 348 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 349 * </pre> 350 */ 351public class PackageManagerService extends IPackageManager.Stub { 352 static final String TAG = "PackageManager"; 353 static final boolean DEBUG_SETTINGS = false; 354 static final boolean DEBUG_PREFERRED = false; 355 static final boolean DEBUG_UPGRADE = false; 356 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 357 private static final boolean DEBUG_BACKUP = false; 358 private static final boolean DEBUG_INSTALL = false; 359 private static final boolean DEBUG_REMOVE = false; 360 private static final boolean DEBUG_BROADCASTS = false; 361 private static final boolean DEBUG_SHOW_INFO = false; 362 private static final boolean DEBUG_PACKAGE_INFO = false; 363 private static final boolean DEBUG_INTENT_MATCHING = false; 364 private static final boolean DEBUG_PACKAGE_SCANNING = false; 365 private static final boolean DEBUG_VERIFY = false; 366 private static final boolean DEBUG_FILTERS = false; 367 368 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 369 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 370 // user, but by default initialize to this. 371 static final boolean DEBUG_DEXOPT = false; 372 373 private static final boolean DEBUG_ABI_SELECTION = false; 374 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 375 private static final boolean DEBUG_TRIAGED_MISSING = false; 376 private static final boolean DEBUG_APP_DATA = false; 377 378 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 379 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 380 381 private static final boolean DISABLE_EPHEMERAL_APPS = false; 382 private static final boolean HIDE_EPHEMERAL_APIS = true; 383 384 private static final boolean ENABLE_QUOTA = 385 SystemProperties.getBoolean("persist.fw.quota", false); 386 387 private static final int RADIO_UID = Process.PHONE_UID; 388 private static final int LOG_UID = Process.LOG_UID; 389 private static final int NFC_UID = Process.NFC_UID; 390 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 391 private static final int SHELL_UID = Process.SHELL_UID; 392 393 // Cap the size of permission trees that 3rd party apps can define 394 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 395 396 // Suffix used during package installation when copying/moving 397 // package apks to install directory. 398 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 399 400 static final int SCAN_NO_DEX = 1<<1; 401 static final int SCAN_FORCE_DEX = 1<<2; 402 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 403 static final int SCAN_NEW_INSTALL = 1<<4; 404 static final int SCAN_UPDATE_TIME = 1<<5; 405 static final int SCAN_BOOTING = 1<<6; 406 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 407 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 408 static final int SCAN_REPLACING = 1<<9; 409 static final int SCAN_REQUIRE_KNOWN = 1<<10; 410 static final int SCAN_MOVE = 1<<11; 411 static final int SCAN_INITIAL = 1<<12; 412 static final int SCAN_CHECK_ONLY = 1<<13; 413 static final int SCAN_DONT_KILL_APP = 1<<14; 414 static final int SCAN_IGNORE_FROZEN = 1<<15; 415 static final int REMOVE_CHATTY = 1<<16; 416 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17; 417 418 private static final int[] EMPTY_INT_ARRAY = new int[0]; 419 420 /** 421 * Timeout (in milliseconds) after which the watchdog should declare that 422 * our handler thread is wedged. The usual default for such things is one 423 * minute but we sometimes do very lengthy I/O operations on this thread, 424 * such as installing multi-gigabyte applications, so ours needs to be longer. 425 */ 426 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 427 428 /** 429 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 430 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 431 * settings entry if available, otherwise we use the hardcoded default. If it's been 432 * more than this long since the last fstrim, we force one during the boot sequence. 433 * 434 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 435 * one gets run at the next available charging+idle time. This final mandatory 436 * no-fstrim check kicks in only of the other scheduling criteria is never met. 437 */ 438 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 439 440 /** 441 * Whether verification is enabled by default. 442 */ 443 private static final boolean DEFAULT_VERIFY_ENABLE = true; 444 445 /** 446 * The default maximum time to wait for the verification agent to return in 447 * milliseconds. 448 */ 449 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 450 451 /** 452 * The default response for package verification timeout. 453 * 454 * This can be either PackageManager.VERIFICATION_ALLOW or 455 * PackageManager.VERIFICATION_REJECT. 456 */ 457 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 458 459 static final String PLATFORM_PACKAGE_NAME = "android"; 460 461 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 462 463 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 464 DEFAULT_CONTAINER_PACKAGE, 465 "com.android.defcontainer.DefaultContainerService"); 466 467 private static final String KILL_APP_REASON_GIDS_CHANGED = 468 "permission grant or revoke changed gids"; 469 470 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 471 "permissions revoked"; 472 473 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 474 475 private static final String PACKAGE_SCHEME = "package"; 476 477 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 478 /** 479 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 480 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 481 * VENDOR_OVERLAY_DIR. 482 */ 483 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 484 /** 485 * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever 486 * is in VENDOR_OVERLAY_THEME_PROPERTY. 487 */ 488 private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY 489 = "persist.vendor.overlay.theme"; 490 491 /** Permission grant: not grant the permission. */ 492 private static final int GRANT_DENIED = 1; 493 494 /** Permission grant: grant the permission as an install permission. */ 495 private static final int GRANT_INSTALL = 2; 496 497 /** Permission grant: grant the permission as a runtime one. */ 498 private static final int GRANT_RUNTIME = 3; 499 500 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 501 private static final int GRANT_UPGRADE = 4; 502 503 /** Canonical intent used to identify what counts as a "web browser" app */ 504 private static final Intent sBrowserIntent; 505 static { 506 sBrowserIntent = new Intent(); 507 sBrowserIntent.setAction(Intent.ACTION_VIEW); 508 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 509 sBrowserIntent.setData(Uri.parse("http:")); 510 } 511 512 /** 513 * The set of all protected actions [i.e. those actions for which a high priority 514 * intent filter is disallowed]. 515 */ 516 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 517 static { 518 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 519 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 520 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 521 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 522 } 523 524 // Compilation reasons. 525 public static final int REASON_FIRST_BOOT = 0; 526 public static final int REASON_BOOT = 1; 527 public static final int REASON_INSTALL = 2; 528 public static final int REASON_BACKGROUND_DEXOPT = 3; 529 public static final int REASON_AB_OTA = 4; 530 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 531 public static final int REASON_SHARED_APK = 6; 532 public static final int REASON_FORCED_DEXOPT = 7; 533 public static final int REASON_CORE_APP = 8; 534 535 public static final int REASON_LAST = REASON_CORE_APP; 536 537 /** Special library name that skips shared libraries check during compilation. */ 538 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 539 540 /** All dangerous permission names in the same order as the events in MetricsEvent */ 541 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 542 Manifest.permission.READ_CALENDAR, 543 Manifest.permission.WRITE_CALENDAR, 544 Manifest.permission.CAMERA, 545 Manifest.permission.READ_CONTACTS, 546 Manifest.permission.WRITE_CONTACTS, 547 Manifest.permission.GET_ACCOUNTS, 548 Manifest.permission.ACCESS_FINE_LOCATION, 549 Manifest.permission.ACCESS_COARSE_LOCATION, 550 Manifest.permission.RECORD_AUDIO, 551 Manifest.permission.READ_PHONE_STATE, 552 Manifest.permission.CALL_PHONE, 553 Manifest.permission.READ_CALL_LOG, 554 Manifest.permission.WRITE_CALL_LOG, 555 Manifest.permission.ADD_VOICEMAIL, 556 Manifest.permission.USE_SIP, 557 Manifest.permission.PROCESS_OUTGOING_CALLS, 558 Manifest.permission.READ_CELL_BROADCASTS, 559 Manifest.permission.BODY_SENSORS, 560 Manifest.permission.SEND_SMS, 561 Manifest.permission.RECEIVE_SMS, 562 Manifest.permission.READ_SMS, 563 Manifest.permission.RECEIVE_WAP_PUSH, 564 Manifest.permission.RECEIVE_MMS, 565 Manifest.permission.READ_EXTERNAL_STORAGE, 566 Manifest.permission.WRITE_EXTERNAL_STORAGE, 567 Manifest.permission.READ_PHONE_NUMBER); 568 569 final ServiceThread mHandlerThread; 570 571 final PackageHandler mHandler; 572 573 private final ProcessLoggingHandler mProcessLoggingHandler; 574 575 /** 576 * Messages for {@link #mHandler} that need to wait for system ready before 577 * being dispatched. 578 */ 579 private ArrayList<Message> mPostSystemReadyMessages; 580 581 final int mSdkVersion = Build.VERSION.SDK_INT; 582 583 final Context mContext; 584 final boolean mFactoryTest; 585 final boolean mOnlyCore; 586 final DisplayMetrics mMetrics; 587 final int mDefParseFlags; 588 final String[] mSeparateProcesses; 589 final boolean mIsUpgrade; 590 final boolean mIsPreNUpgrade; 591 final boolean mIsPreNMR1Upgrade; 592 593 @GuardedBy("mPackages") 594 private boolean mDexOptDialogShown; 595 596 /** The location for ASEC container files on internal storage. */ 597 final String mAsecInternalPath; 598 599 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 600 // LOCK HELD. Can be called with mInstallLock held. 601 @GuardedBy("mInstallLock") 602 final Installer mInstaller; 603 604 /** Directory where installed third-party apps stored */ 605 final File mAppInstallDir; 606 final File mEphemeralInstallDir; 607 608 /** 609 * Directory to which applications installed internally have their 610 * 32 bit native libraries copied. 611 */ 612 private File mAppLib32InstallDir; 613 614 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 615 // apps. 616 final File mDrmAppPrivateInstallDir; 617 618 // ---------------------------------------------------------------- 619 620 // Lock for state used when installing and doing other long running 621 // operations. Methods that must be called with this lock held have 622 // the suffix "LI". 623 final Object mInstallLock = new Object(); 624 625 // ---------------------------------------------------------------- 626 627 // Keys are String (package name), values are Package. This also serves 628 // as the lock for the global state. Methods that must be called with 629 // this lock held have the prefix "LP". 630 @GuardedBy("mPackages") 631 final ArrayMap<String, PackageParser.Package> mPackages = 632 new ArrayMap<String, PackageParser.Package>(); 633 634 final ArrayMap<String, Set<String>> mKnownCodebase = 635 new ArrayMap<String, Set<String>>(); 636 637 // Tracks available target package names -> overlay package paths. 638 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 639 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 640 641 /** 642 * Tracks new system packages [received in an OTA] that we expect to 643 * find updated user-installed versions. Keys are package name, values 644 * are package location. 645 */ 646 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 647 /** 648 * Tracks high priority intent filters for protected actions. During boot, certain 649 * filter actions are protected and should never be allowed to have a high priority 650 * intent filter for them. However, there is one, and only one exception -- the 651 * setup wizard. It must be able to define a high priority intent filter for these 652 * actions to ensure there are no escapes from the wizard. We need to delay processing 653 * of these during boot as we need to look at all of the system packages in order 654 * to know which component is the setup wizard. 655 */ 656 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 657 /** 658 * Whether or not processing protected filters should be deferred. 659 */ 660 private boolean mDeferProtectedFilters = true; 661 662 /** 663 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 664 */ 665 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 666 /** 667 * Whether or not system app permissions should be promoted from install to runtime. 668 */ 669 boolean mPromoteSystemApps; 670 671 @GuardedBy("mPackages") 672 final Settings mSettings; 673 674 /** 675 * Set of package names that are currently "frozen", which means active 676 * surgery is being done on the code/data for that package. The platform 677 * will refuse to launch frozen packages to avoid race conditions. 678 * 679 * @see PackageFreezer 680 */ 681 @GuardedBy("mPackages") 682 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 683 684 final ProtectedPackages mProtectedPackages; 685 686 boolean mFirstBoot; 687 688 // System configuration read by SystemConfig. 689 final int[] mGlobalGids; 690 final SparseArray<ArraySet<String>> mSystemPermissions; 691 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 692 693 // If mac_permissions.xml was found for seinfo labeling. 694 boolean mFoundPolicyFile; 695 696 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 697 698 public static final class SharedLibraryEntry { 699 public final String path; 700 public final String apk; 701 702 SharedLibraryEntry(String _path, String _apk) { 703 path = _path; 704 apk = _apk; 705 } 706 } 707 708 // Currently known shared libraries. 709 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 710 new ArrayMap<String, SharedLibraryEntry>(); 711 712 // All available activities, for your resolving pleasure. 713 final ActivityIntentResolver mActivities = 714 new ActivityIntentResolver(); 715 716 // All available receivers, for your resolving pleasure. 717 final ActivityIntentResolver mReceivers = 718 new ActivityIntentResolver(); 719 720 // All available services, for your resolving pleasure. 721 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 722 723 // All available providers, for your resolving pleasure. 724 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 725 726 // Mapping from provider base names (first directory in content URI codePath) 727 // to the provider information. 728 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 729 new ArrayMap<String, PackageParser.Provider>(); 730 731 // Mapping from instrumentation class names to info about them. 732 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 733 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 734 735 // Mapping from permission names to info about them. 736 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 737 new ArrayMap<String, PackageParser.PermissionGroup>(); 738 739 // Packages whose data we have transfered into another package, thus 740 // should no longer exist. 741 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 742 743 // Broadcast actions that are only available to the system. 744 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 745 746 /** List of packages waiting for verification. */ 747 final SparseArray<PackageVerificationState> mPendingVerification 748 = new SparseArray<PackageVerificationState>(); 749 750 /** Set of packages associated with each app op permission. */ 751 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 752 753 final PackageInstallerService mInstallerService; 754 755 private final PackageDexOptimizer mPackageDexOptimizer; 756 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 757 // is used by other apps). 758 private final DexManager mDexManager; 759 760 private AtomicInteger mNextMoveId = new AtomicInteger(); 761 private final MoveCallbacks mMoveCallbacks; 762 763 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 764 765 // Cache of users who need badging. 766 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 767 768 /** Token for keys in mPendingVerification. */ 769 private int mPendingVerificationToken = 0; 770 771 volatile boolean mSystemReady; 772 volatile boolean mSafeMode; 773 volatile boolean mHasSystemUidErrors; 774 775 ApplicationInfo mAndroidApplication; 776 final ActivityInfo mResolveActivity = new ActivityInfo(); 777 final ResolveInfo mResolveInfo = new ResolveInfo(); 778 ComponentName mResolveComponentName; 779 PackageParser.Package mPlatformPackage; 780 ComponentName mCustomResolverComponentName; 781 782 boolean mResolverReplaced = false; 783 784 private final @Nullable ComponentName mIntentFilterVerifierComponent; 785 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 786 787 private int mIntentFilterVerificationToken = 0; 788 789 /** The service connection to the ephemeral resolver */ 790 final EphemeralResolverConnection mEphemeralResolverConnection; 791 792 /** Component used to install ephemeral applications */ 793 ComponentName mEphemeralInstallerComponent; 794 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 795 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 796 797 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 798 = new SparseArray<IntentFilterVerificationState>(); 799 800 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 801 802 // List of packages names to keep cached, even if they are uninstalled for all users 803 private List<String> mKeepUninstalledPackages; 804 805 private UserManagerInternal mUserManagerInternal; 806 807 private static class IFVerificationParams { 808 PackageParser.Package pkg; 809 boolean replacing; 810 int userId; 811 int verifierUid; 812 813 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 814 int _userId, int _verifierUid) { 815 pkg = _pkg; 816 replacing = _replacing; 817 userId = _userId; 818 replacing = _replacing; 819 verifierUid = _verifierUid; 820 } 821 } 822 823 private interface IntentFilterVerifier<T extends IntentFilter> { 824 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 825 T filter, String packageName); 826 void startVerifications(int userId); 827 void receiveVerificationResponse(int verificationId); 828 } 829 830 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 831 private Context mContext; 832 private ComponentName mIntentFilterVerifierComponent; 833 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 834 835 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 836 mContext = context; 837 mIntentFilterVerifierComponent = verifierComponent; 838 } 839 840 private String getDefaultScheme() { 841 return IntentFilter.SCHEME_HTTPS; 842 } 843 844 @Override 845 public void startVerifications(int userId) { 846 // Launch verifications requests 847 int count = mCurrentIntentFilterVerifications.size(); 848 for (int n=0; n<count; n++) { 849 int verificationId = mCurrentIntentFilterVerifications.get(n); 850 final IntentFilterVerificationState ivs = 851 mIntentFilterVerificationStates.get(verificationId); 852 853 String packageName = ivs.getPackageName(); 854 855 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 856 final int filterCount = filters.size(); 857 ArraySet<String> domainsSet = new ArraySet<>(); 858 for (int m=0; m<filterCount; m++) { 859 PackageParser.ActivityIntentInfo filter = filters.get(m); 860 domainsSet.addAll(filter.getHostsList()); 861 } 862 synchronized (mPackages) { 863 if (mSettings.createIntentFilterVerificationIfNeededLPw( 864 packageName, domainsSet) != null) { 865 scheduleWriteSettingsLocked(); 866 } 867 } 868 sendVerificationRequest(userId, verificationId, ivs); 869 } 870 mCurrentIntentFilterVerifications.clear(); 871 } 872 873 private void sendVerificationRequest(int userId, int verificationId, 874 IntentFilterVerificationState ivs) { 875 876 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 877 verificationIntent.putExtra( 878 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 879 verificationId); 880 verificationIntent.putExtra( 881 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 882 getDefaultScheme()); 883 verificationIntent.putExtra( 884 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 885 ivs.getHostsString()); 886 verificationIntent.putExtra( 887 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 888 ivs.getPackageName()); 889 verificationIntent.setComponent(mIntentFilterVerifierComponent); 890 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 891 892 UserHandle user = new UserHandle(userId); 893 mContext.sendBroadcastAsUser(verificationIntent, user); 894 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 895 "Sending IntentFilter verification broadcast"); 896 } 897 898 public void receiveVerificationResponse(int verificationId) { 899 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 900 901 final boolean verified = ivs.isVerified(); 902 903 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 904 final int count = filters.size(); 905 if (DEBUG_DOMAIN_VERIFICATION) { 906 Slog.i(TAG, "Received verification response " + verificationId 907 + " for " + count + " filters, verified=" + verified); 908 } 909 for (int n=0; n<count; n++) { 910 PackageParser.ActivityIntentInfo filter = filters.get(n); 911 filter.setVerified(verified); 912 913 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 914 + " verified with result:" + verified + " and hosts:" 915 + ivs.getHostsString()); 916 } 917 918 mIntentFilterVerificationStates.remove(verificationId); 919 920 final String packageName = ivs.getPackageName(); 921 IntentFilterVerificationInfo ivi = null; 922 923 synchronized (mPackages) { 924 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 925 } 926 if (ivi == null) { 927 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 928 + verificationId + " packageName:" + packageName); 929 return; 930 } 931 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 932 "Updating IntentFilterVerificationInfo for package " + packageName 933 +" verificationId:" + verificationId); 934 935 synchronized (mPackages) { 936 if (verified) { 937 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 938 } else { 939 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 940 } 941 scheduleWriteSettingsLocked(); 942 943 final int userId = ivs.getUserId(); 944 if (userId != UserHandle.USER_ALL) { 945 final int userStatus = 946 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 947 948 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 949 boolean needUpdate = false; 950 951 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 952 // already been set by the User thru the Disambiguation dialog 953 switch (userStatus) { 954 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 955 if (verified) { 956 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 957 } else { 958 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 959 } 960 needUpdate = true; 961 break; 962 963 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 964 if (verified) { 965 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 966 needUpdate = true; 967 } 968 break; 969 970 default: 971 // Nothing to do 972 } 973 974 if (needUpdate) { 975 mSettings.updateIntentFilterVerificationStatusLPw( 976 packageName, updatedStatus, userId); 977 scheduleWritePackageRestrictionsLocked(userId); 978 } 979 } 980 } 981 } 982 983 @Override 984 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 985 ActivityIntentInfo filter, String packageName) { 986 if (!hasValidDomains(filter)) { 987 return false; 988 } 989 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 990 if (ivs == null) { 991 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 992 packageName); 993 } 994 if (DEBUG_DOMAIN_VERIFICATION) { 995 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 996 } 997 ivs.addFilter(filter); 998 return true; 999 } 1000 1001 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1002 int userId, int verificationId, String packageName) { 1003 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1004 verifierUid, userId, packageName); 1005 ivs.setPendingState(); 1006 synchronized (mPackages) { 1007 mIntentFilterVerificationStates.append(verificationId, ivs); 1008 mCurrentIntentFilterVerifications.add(verificationId); 1009 } 1010 return ivs; 1011 } 1012 } 1013 1014 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1015 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1016 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1017 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1018 } 1019 1020 // Set of pending broadcasts for aggregating enable/disable of components. 1021 static class PendingPackageBroadcasts { 1022 // for each user id, a map of <package name -> components within that package> 1023 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1024 1025 public PendingPackageBroadcasts() { 1026 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1027 } 1028 1029 public ArrayList<String> get(int userId, String packageName) { 1030 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1031 return packages.get(packageName); 1032 } 1033 1034 public void put(int userId, String packageName, ArrayList<String> components) { 1035 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1036 packages.put(packageName, components); 1037 } 1038 1039 public void remove(int userId, String packageName) { 1040 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1041 if (packages != null) { 1042 packages.remove(packageName); 1043 } 1044 } 1045 1046 public void remove(int userId) { 1047 mUidMap.remove(userId); 1048 } 1049 1050 public int userIdCount() { 1051 return mUidMap.size(); 1052 } 1053 1054 public int userIdAt(int n) { 1055 return mUidMap.keyAt(n); 1056 } 1057 1058 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1059 return mUidMap.get(userId); 1060 } 1061 1062 public int size() { 1063 // total number of pending broadcast entries across all userIds 1064 int num = 0; 1065 for (int i = 0; i< mUidMap.size(); i++) { 1066 num += mUidMap.valueAt(i).size(); 1067 } 1068 return num; 1069 } 1070 1071 public void clear() { 1072 mUidMap.clear(); 1073 } 1074 1075 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1076 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1077 if (map == null) { 1078 map = new ArrayMap<String, ArrayList<String>>(); 1079 mUidMap.put(userId, map); 1080 } 1081 return map; 1082 } 1083 } 1084 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1085 1086 // Service Connection to remote media container service to copy 1087 // package uri's from external media onto secure containers 1088 // or internal storage. 1089 private IMediaContainerService mContainerService = null; 1090 1091 static final int SEND_PENDING_BROADCAST = 1; 1092 static final int MCS_BOUND = 3; 1093 static final int END_COPY = 4; 1094 static final int INIT_COPY = 5; 1095 static final int MCS_UNBIND = 6; 1096 static final int START_CLEANING_PACKAGE = 7; 1097 static final int FIND_INSTALL_LOC = 8; 1098 static final int POST_INSTALL = 9; 1099 static final int MCS_RECONNECT = 10; 1100 static final int MCS_GIVE_UP = 11; 1101 static final int UPDATED_MEDIA_STATUS = 12; 1102 static final int WRITE_SETTINGS = 13; 1103 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1104 static final int PACKAGE_VERIFIED = 15; 1105 static final int CHECK_PENDING_VERIFICATION = 16; 1106 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1107 static final int INTENT_FILTER_VERIFIED = 18; 1108 static final int WRITE_PACKAGE_LIST = 19; 1109 static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20; 1110 1111 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1112 1113 // Delay time in millisecs 1114 static final int BROADCAST_DELAY = 10 * 1000; 1115 1116 static UserManagerService sUserManager; 1117 1118 // Stores a list of users whose package restrictions file needs to be updated 1119 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1120 1121 final private DefaultContainerConnection mDefContainerConn = 1122 new DefaultContainerConnection(); 1123 class DefaultContainerConnection implements ServiceConnection { 1124 public void onServiceConnected(ComponentName name, IBinder service) { 1125 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1126 final IMediaContainerService imcs = IMediaContainerService.Stub 1127 .asInterface(Binder.allowBlocking(service)); 1128 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1129 } 1130 1131 public void onServiceDisconnected(ComponentName name) { 1132 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1133 } 1134 } 1135 1136 // Recordkeeping of restore-after-install operations that are currently in flight 1137 // between the Package Manager and the Backup Manager 1138 static class PostInstallData { 1139 public InstallArgs args; 1140 public PackageInstalledInfo res; 1141 1142 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1143 args = _a; 1144 res = _r; 1145 } 1146 } 1147 1148 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1149 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1150 1151 // XML tags for backup/restore of various bits of state 1152 private static final String TAG_PREFERRED_BACKUP = "pa"; 1153 private static final String TAG_DEFAULT_APPS = "da"; 1154 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1155 1156 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1157 private static final String TAG_ALL_GRANTS = "rt-grants"; 1158 private static final String TAG_GRANT = "grant"; 1159 private static final String ATTR_PACKAGE_NAME = "pkg"; 1160 1161 private static final String TAG_PERMISSION = "perm"; 1162 private static final String ATTR_PERMISSION_NAME = "name"; 1163 private static final String ATTR_IS_GRANTED = "g"; 1164 private static final String ATTR_USER_SET = "set"; 1165 private static final String ATTR_USER_FIXED = "fixed"; 1166 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1167 1168 // System/policy permission grants are not backed up 1169 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1170 FLAG_PERMISSION_POLICY_FIXED 1171 | FLAG_PERMISSION_SYSTEM_FIXED 1172 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1173 1174 // And we back up these user-adjusted states 1175 private static final int USER_RUNTIME_GRANT_MASK = 1176 FLAG_PERMISSION_USER_SET 1177 | FLAG_PERMISSION_USER_FIXED 1178 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1179 1180 final @Nullable String mRequiredVerifierPackage; 1181 final @NonNull String mRequiredInstallerPackage; 1182 final @NonNull String mRequiredUninstallerPackage; 1183 final @Nullable String mSetupWizardPackage; 1184 final @Nullable String mStorageManagerPackage; 1185 final @NonNull String mServicesSystemSharedLibraryPackageName; 1186 final @NonNull String mSharedSystemSharedLibraryPackageName; 1187 1188 final boolean mPermissionReviewRequired; 1189 1190 private final PackageUsage mPackageUsage = new PackageUsage(); 1191 private final CompilerStats mCompilerStats = new CompilerStats(); 1192 1193 class PackageHandler extends Handler { 1194 private boolean mBound = false; 1195 final ArrayList<HandlerParams> mPendingInstalls = 1196 new ArrayList<HandlerParams>(); 1197 1198 private boolean connectToService() { 1199 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1200 " DefaultContainerService"); 1201 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1202 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1203 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1204 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1205 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1206 mBound = true; 1207 return true; 1208 } 1209 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1210 return false; 1211 } 1212 1213 private void disconnectService() { 1214 mContainerService = null; 1215 mBound = false; 1216 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1217 mContext.unbindService(mDefContainerConn); 1218 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1219 } 1220 1221 PackageHandler(Looper looper) { 1222 super(looper); 1223 } 1224 1225 public void handleMessage(Message msg) { 1226 try { 1227 doHandleMessage(msg); 1228 } finally { 1229 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1230 } 1231 } 1232 1233 void doHandleMessage(Message msg) { 1234 switch (msg.what) { 1235 case INIT_COPY: { 1236 HandlerParams params = (HandlerParams) msg.obj; 1237 int idx = mPendingInstalls.size(); 1238 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1239 // If a bind was already initiated we dont really 1240 // need to do anything. The pending install 1241 // will be processed later on. 1242 if (!mBound) { 1243 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1244 System.identityHashCode(mHandler)); 1245 // If this is the only one pending we might 1246 // have to bind to the service again. 1247 if (!connectToService()) { 1248 Slog.e(TAG, "Failed to bind to media container service"); 1249 params.serviceError(); 1250 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1251 System.identityHashCode(mHandler)); 1252 if (params.traceMethod != null) { 1253 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1254 params.traceCookie); 1255 } 1256 return; 1257 } else { 1258 // Once we bind to the service, the first 1259 // pending request will be processed. 1260 mPendingInstalls.add(idx, params); 1261 } 1262 } else { 1263 mPendingInstalls.add(idx, params); 1264 // Already bound to the service. Just make 1265 // sure we trigger off processing the first request. 1266 if (idx == 0) { 1267 mHandler.sendEmptyMessage(MCS_BOUND); 1268 } 1269 } 1270 break; 1271 } 1272 case MCS_BOUND: { 1273 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1274 if (msg.obj != null) { 1275 mContainerService = (IMediaContainerService) msg.obj; 1276 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1277 System.identityHashCode(mHandler)); 1278 } 1279 if (mContainerService == null) { 1280 if (!mBound) { 1281 // Something seriously wrong since we are not bound and we are not 1282 // waiting for connection. Bail out. 1283 Slog.e(TAG, "Cannot bind to media container service"); 1284 for (HandlerParams params : mPendingInstalls) { 1285 // Indicate service bind error 1286 params.serviceError(); 1287 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1288 System.identityHashCode(params)); 1289 if (params.traceMethod != null) { 1290 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1291 params.traceMethod, params.traceCookie); 1292 } 1293 return; 1294 } 1295 mPendingInstalls.clear(); 1296 } else { 1297 Slog.w(TAG, "Waiting to connect to media container service"); 1298 } 1299 } else if (mPendingInstalls.size() > 0) { 1300 HandlerParams params = mPendingInstalls.get(0); 1301 if (params != null) { 1302 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1303 System.identityHashCode(params)); 1304 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1305 if (params.startCopy()) { 1306 // We are done... look for more work or to 1307 // go idle. 1308 if (DEBUG_SD_INSTALL) Log.i(TAG, 1309 "Checking for more work or unbind..."); 1310 // Delete pending install 1311 if (mPendingInstalls.size() > 0) { 1312 mPendingInstalls.remove(0); 1313 } 1314 if (mPendingInstalls.size() == 0) { 1315 if (mBound) { 1316 if (DEBUG_SD_INSTALL) Log.i(TAG, 1317 "Posting delayed MCS_UNBIND"); 1318 removeMessages(MCS_UNBIND); 1319 Message ubmsg = obtainMessage(MCS_UNBIND); 1320 // Unbind after a little delay, to avoid 1321 // continual thrashing. 1322 sendMessageDelayed(ubmsg, 10000); 1323 } 1324 } else { 1325 // There are more pending requests in queue. 1326 // Just post MCS_BOUND message to trigger processing 1327 // of next pending install. 1328 if (DEBUG_SD_INSTALL) Log.i(TAG, 1329 "Posting MCS_BOUND for next work"); 1330 mHandler.sendEmptyMessage(MCS_BOUND); 1331 } 1332 } 1333 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1334 } 1335 } else { 1336 // Should never happen ideally. 1337 Slog.w(TAG, "Empty queue"); 1338 } 1339 break; 1340 } 1341 case MCS_RECONNECT: { 1342 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1343 if (mPendingInstalls.size() > 0) { 1344 if (mBound) { 1345 disconnectService(); 1346 } 1347 if (!connectToService()) { 1348 Slog.e(TAG, "Failed to bind to media container service"); 1349 for (HandlerParams params : mPendingInstalls) { 1350 // Indicate service bind error 1351 params.serviceError(); 1352 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1353 System.identityHashCode(params)); 1354 } 1355 mPendingInstalls.clear(); 1356 } 1357 } 1358 break; 1359 } 1360 case MCS_UNBIND: { 1361 // If there is no actual work left, then time to unbind. 1362 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1363 1364 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1365 if (mBound) { 1366 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1367 1368 disconnectService(); 1369 } 1370 } else if (mPendingInstalls.size() > 0) { 1371 // There are more pending requests in queue. 1372 // Just post MCS_BOUND message to trigger processing 1373 // of next pending install. 1374 mHandler.sendEmptyMessage(MCS_BOUND); 1375 } 1376 1377 break; 1378 } 1379 case MCS_GIVE_UP: { 1380 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1381 HandlerParams params = mPendingInstalls.remove(0); 1382 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1383 System.identityHashCode(params)); 1384 break; 1385 } 1386 case SEND_PENDING_BROADCAST: { 1387 String packages[]; 1388 ArrayList<String> components[]; 1389 int size = 0; 1390 int uids[]; 1391 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1392 synchronized (mPackages) { 1393 if (mPendingBroadcasts == null) { 1394 return; 1395 } 1396 size = mPendingBroadcasts.size(); 1397 if (size <= 0) { 1398 // Nothing to be done. Just return 1399 return; 1400 } 1401 packages = new String[size]; 1402 components = new ArrayList[size]; 1403 uids = new int[size]; 1404 int i = 0; // filling out the above arrays 1405 1406 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1407 int packageUserId = mPendingBroadcasts.userIdAt(n); 1408 Iterator<Map.Entry<String, ArrayList<String>>> it 1409 = mPendingBroadcasts.packagesForUserId(packageUserId) 1410 .entrySet().iterator(); 1411 while (it.hasNext() && i < size) { 1412 Map.Entry<String, ArrayList<String>> ent = it.next(); 1413 packages[i] = ent.getKey(); 1414 components[i] = ent.getValue(); 1415 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1416 uids[i] = (ps != null) 1417 ? UserHandle.getUid(packageUserId, ps.appId) 1418 : -1; 1419 i++; 1420 } 1421 } 1422 size = i; 1423 mPendingBroadcasts.clear(); 1424 } 1425 // Send broadcasts 1426 for (int i = 0; i < size; i++) { 1427 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1428 } 1429 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1430 break; 1431 } 1432 case START_CLEANING_PACKAGE: { 1433 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1434 final String packageName = (String)msg.obj; 1435 final int userId = msg.arg1; 1436 final boolean andCode = msg.arg2 != 0; 1437 synchronized (mPackages) { 1438 if (userId == UserHandle.USER_ALL) { 1439 int[] users = sUserManager.getUserIds(); 1440 for (int user : users) { 1441 mSettings.addPackageToCleanLPw( 1442 new PackageCleanItem(user, packageName, andCode)); 1443 } 1444 } else { 1445 mSettings.addPackageToCleanLPw( 1446 new PackageCleanItem(userId, packageName, andCode)); 1447 } 1448 } 1449 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1450 startCleaningPackages(); 1451 } break; 1452 case POST_INSTALL: { 1453 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1454 1455 PostInstallData data = mRunningInstalls.get(msg.arg1); 1456 final boolean didRestore = (msg.arg2 != 0); 1457 mRunningInstalls.delete(msg.arg1); 1458 1459 if (data != null) { 1460 InstallArgs args = data.args; 1461 PackageInstalledInfo parentRes = data.res; 1462 1463 final boolean grantPermissions = (args.installFlags 1464 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1465 final boolean killApp = (args.installFlags 1466 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1467 final String[] grantedPermissions = args.installGrantPermissions; 1468 1469 // Handle the parent package 1470 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1471 grantedPermissions, didRestore, args.installerPackageName, 1472 args.observer); 1473 1474 // Handle the child packages 1475 final int childCount = (parentRes.addedChildPackages != null) 1476 ? parentRes.addedChildPackages.size() : 0; 1477 for (int i = 0; i < childCount; i++) { 1478 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1479 handlePackagePostInstall(childRes, grantPermissions, killApp, 1480 grantedPermissions, false, args.installerPackageName, 1481 args.observer); 1482 } 1483 1484 // Log tracing if needed 1485 if (args.traceMethod != null) { 1486 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1487 args.traceCookie); 1488 } 1489 } else { 1490 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1491 } 1492 1493 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1494 } break; 1495 case UPDATED_MEDIA_STATUS: { 1496 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1497 boolean reportStatus = msg.arg1 == 1; 1498 boolean doGc = msg.arg2 == 1; 1499 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1500 if (doGc) { 1501 // Force a gc to clear up stale containers. 1502 Runtime.getRuntime().gc(); 1503 } 1504 if (msg.obj != null) { 1505 @SuppressWarnings("unchecked") 1506 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1507 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1508 // Unload containers 1509 unloadAllContainers(args); 1510 } 1511 if (reportStatus) { 1512 try { 1513 if (DEBUG_SD_INSTALL) Log.i(TAG, 1514 "Invoking StorageManagerService call back"); 1515 PackageHelper.getStorageManager().finishMediaUpdate(); 1516 } catch (RemoteException e) { 1517 Log.e(TAG, "StorageManagerService not running?"); 1518 } 1519 } 1520 } break; 1521 case WRITE_SETTINGS: { 1522 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1523 synchronized (mPackages) { 1524 removeMessages(WRITE_SETTINGS); 1525 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1526 mSettings.writeLPr(); 1527 mDirtyUsers.clear(); 1528 } 1529 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1530 } break; 1531 case WRITE_PACKAGE_RESTRICTIONS: { 1532 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1533 synchronized (mPackages) { 1534 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1535 for (int userId : mDirtyUsers) { 1536 mSettings.writePackageRestrictionsLPr(userId); 1537 } 1538 mDirtyUsers.clear(); 1539 } 1540 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1541 } break; 1542 case WRITE_PACKAGE_LIST: { 1543 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1544 synchronized (mPackages) { 1545 removeMessages(WRITE_PACKAGE_LIST); 1546 mSettings.writePackageListLPr(msg.arg1); 1547 } 1548 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1549 } break; 1550 case CHECK_PENDING_VERIFICATION: { 1551 final int verificationId = msg.arg1; 1552 final PackageVerificationState state = mPendingVerification.get(verificationId); 1553 1554 if ((state != null) && !state.timeoutExtended()) { 1555 final InstallArgs args = state.getInstallArgs(); 1556 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1557 1558 Slog.i(TAG, "Verification timed out for " + originUri); 1559 mPendingVerification.remove(verificationId); 1560 1561 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1562 1563 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1564 Slog.i(TAG, "Continuing with installation of " + originUri); 1565 state.setVerifierResponse(Binder.getCallingUid(), 1566 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1567 broadcastPackageVerified(verificationId, originUri, 1568 PackageManager.VERIFICATION_ALLOW, 1569 state.getInstallArgs().getUser()); 1570 try { 1571 ret = args.copyApk(mContainerService, true); 1572 } catch (RemoteException e) { 1573 Slog.e(TAG, "Could not contact the ContainerService"); 1574 } 1575 } else { 1576 broadcastPackageVerified(verificationId, originUri, 1577 PackageManager.VERIFICATION_REJECT, 1578 state.getInstallArgs().getUser()); 1579 } 1580 1581 Trace.asyncTraceEnd( 1582 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1583 1584 processPendingInstall(args, ret); 1585 mHandler.sendEmptyMessage(MCS_UNBIND); 1586 } 1587 break; 1588 } 1589 case PACKAGE_VERIFIED: { 1590 final int verificationId = msg.arg1; 1591 1592 final PackageVerificationState state = mPendingVerification.get(verificationId); 1593 if (state == null) { 1594 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1595 break; 1596 } 1597 1598 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1599 1600 state.setVerifierResponse(response.callerUid, response.code); 1601 1602 if (state.isVerificationComplete()) { 1603 mPendingVerification.remove(verificationId); 1604 1605 final InstallArgs args = state.getInstallArgs(); 1606 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1607 1608 int ret; 1609 if (state.isInstallAllowed()) { 1610 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1611 broadcastPackageVerified(verificationId, originUri, 1612 response.code, state.getInstallArgs().getUser()); 1613 try { 1614 ret = args.copyApk(mContainerService, true); 1615 } catch (RemoteException e) { 1616 Slog.e(TAG, "Could not contact the ContainerService"); 1617 } 1618 } else { 1619 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1620 } 1621 1622 Trace.asyncTraceEnd( 1623 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1624 1625 processPendingInstall(args, ret); 1626 mHandler.sendEmptyMessage(MCS_UNBIND); 1627 } 1628 1629 break; 1630 } 1631 case START_INTENT_FILTER_VERIFICATIONS: { 1632 IFVerificationParams params = (IFVerificationParams) msg.obj; 1633 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1634 params.replacing, params.pkg); 1635 break; 1636 } 1637 case INTENT_FILTER_VERIFIED: { 1638 final int verificationId = msg.arg1; 1639 1640 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1641 verificationId); 1642 if (state == null) { 1643 Slog.w(TAG, "Invalid IntentFilter verification token " 1644 + verificationId + " received"); 1645 break; 1646 } 1647 1648 final int userId = state.getUserId(); 1649 1650 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1651 "Processing IntentFilter verification with token:" 1652 + verificationId + " and userId:" + userId); 1653 1654 final IntentFilterVerificationResponse response = 1655 (IntentFilterVerificationResponse) msg.obj; 1656 1657 state.setVerifierResponse(response.callerUid, response.code); 1658 1659 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1660 "IntentFilter verification with token:" + verificationId 1661 + " and userId:" + userId 1662 + " is settings verifier response with response code:" 1663 + response.code); 1664 1665 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1666 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1667 + response.getFailedDomainsString()); 1668 } 1669 1670 if (state.isVerificationComplete()) { 1671 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1672 } else { 1673 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1674 "IntentFilter verification with token:" + verificationId 1675 + " was not said to be complete"); 1676 } 1677 1678 break; 1679 } 1680 case EPHEMERAL_RESOLUTION_PHASE_TWO: { 1681 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1682 mEphemeralResolverConnection, 1683 (EphemeralRequest) msg.obj, 1684 mEphemeralInstallerActivity, 1685 mHandler); 1686 } 1687 } 1688 } 1689 } 1690 1691 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1692 boolean killApp, String[] grantedPermissions, 1693 boolean launchedForRestore, String installerPackage, 1694 IPackageInstallObserver2 installObserver) { 1695 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1696 // Send the removed broadcasts 1697 if (res.removedInfo != null) { 1698 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1699 } 1700 1701 // Now that we successfully installed the package, grant runtime 1702 // permissions if requested before broadcasting the install. 1703 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1704 >= Build.VERSION_CODES.M) { 1705 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1706 } 1707 1708 final boolean update = res.removedInfo != null 1709 && res.removedInfo.removedPackage != null; 1710 1711 // If this is the first time we have child packages for a disabled privileged 1712 // app that had no children, we grant requested runtime permissions to the new 1713 // children if the parent on the system image had them already granted. 1714 if (res.pkg.parentPackage != null) { 1715 synchronized (mPackages) { 1716 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1717 } 1718 } 1719 1720 synchronized (mPackages) { 1721 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1722 } 1723 1724 final String packageName = res.pkg.applicationInfo.packageName; 1725 1726 // Determine the set of users who are adding this package for 1727 // the first time vs. those who are seeing an update. 1728 int[] firstUsers = EMPTY_INT_ARRAY; 1729 int[] updateUsers = EMPTY_INT_ARRAY; 1730 if (res.origUsers == null || res.origUsers.length == 0) { 1731 firstUsers = res.newUsers; 1732 } else { 1733 for (int newUser : res.newUsers) { 1734 boolean isNew = true; 1735 for (int origUser : res.origUsers) { 1736 if (origUser == newUser) { 1737 isNew = false; 1738 break; 1739 } 1740 } 1741 if (isNew) { 1742 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1743 } else { 1744 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1745 } 1746 } 1747 } 1748 1749 // Send installed broadcasts if the install/update is not ephemeral 1750 if (!isEphemeral(res.pkg)) { 1751 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1752 1753 // Send added for users that see the package for the first time 1754 // sendPackageAddedForNewUsers also deals with system apps 1755 int appId = UserHandle.getAppId(res.uid); 1756 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1757 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1758 1759 // Send added for users that don't see the package for the first time 1760 Bundle extras = new Bundle(1); 1761 extras.putInt(Intent.EXTRA_UID, res.uid); 1762 if (update) { 1763 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1764 } 1765 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1766 extras, 0 /*flags*/, null /*targetPackage*/, 1767 null /*finishedReceiver*/, updateUsers); 1768 1769 // Send replaced for users that don't see the package for the first time 1770 if (update) { 1771 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1772 packageName, extras, 0 /*flags*/, 1773 null /*targetPackage*/, null /*finishedReceiver*/, 1774 updateUsers); 1775 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1776 null /*package*/, null /*extras*/, 0 /*flags*/, 1777 packageName /*targetPackage*/, 1778 null /*finishedReceiver*/, updateUsers); 1779 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1780 // First-install and we did a restore, so we're responsible for the 1781 // first-launch broadcast. 1782 if (DEBUG_BACKUP) { 1783 Slog.i(TAG, "Post-restore of " + packageName 1784 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1785 } 1786 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1787 } 1788 1789 // Send broadcast package appeared if forward locked/external for all users 1790 // treat asec-hosted packages like removable media on upgrade 1791 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1792 if (DEBUG_INSTALL) { 1793 Slog.i(TAG, "upgrading pkg " + res.pkg 1794 + " is ASEC-hosted -> AVAILABLE"); 1795 } 1796 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1797 ArrayList<String> pkgList = new ArrayList<>(1); 1798 pkgList.add(packageName); 1799 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1800 } 1801 } 1802 1803 // Work that needs to happen on first install within each user 1804 if (firstUsers != null && firstUsers.length > 0) { 1805 synchronized (mPackages) { 1806 for (int userId : firstUsers) { 1807 // If this app is a browser and it's newly-installed for some 1808 // users, clear any default-browser state in those users. The 1809 // app's nature doesn't depend on the user, so we can just check 1810 // its browser nature in any user and generalize. 1811 if (packageIsBrowser(packageName, userId)) { 1812 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1813 } 1814 1815 // We may also need to apply pending (restored) runtime 1816 // permission grants within these users. 1817 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1818 } 1819 } 1820 } 1821 1822 // Log current value of "unknown sources" setting 1823 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1824 getUnknownSourcesSettings()); 1825 1826 // Force a gc to clear up things 1827 Runtime.getRuntime().gc(); 1828 1829 // Remove the replaced package's older resources safely now 1830 // We delete after a gc for applications on sdcard. 1831 if (res.removedInfo != null && res.removedInfo.args != null) { 1832 synchronized (mInstallLock) { 1833 res.removedInfo.args.doPostDeleteLI(true); 1834 } 1835 } 1836 } 1837 1838 // If someone is watching installs - notify them 1839 if (installObserver != null) { 1840 try { 1841 Bundle extras = extrasForInstallResult(res); 1842 installObserver.onPackageInstalled(res.name, res.returnCode, 1843 res.returnMsg, extras); 1844 } catch (RemoteException e) { 1845 Slog.i(TAG, "Observer no longer exists."); 1846 } 1847 } 1848 } 1849 1850 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1851 PackageParser.Package pkg) { 1852 if (pkg.parentPackage == null) { 1853 return; 1854 } 1855 if (pkg.requestedPermissions == null) { 1856 return; 1857 } 1858 final PackageSetting disabledSysParentPs = mSettings 1859 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1860 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1861 || !disabledSysParentPs.isPrivileged() 1862 || (disabledSysParentPs.childPackageNames != null 1863 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1864 return; 1865 } 1866 final int[] allUserIds = sUserManager.getUserIds(); 1867 final int permCount = pkg.requestedPermissions.size(); 1868 for (int i = 0; i < permCount; i++) { 1869 String permission = pkg.requestedPermissions.get(i); 1870 BasePermission bp = mSettings.mPermissions.get(permission); 1871 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1872 continue; 1873 } 1874 for (int userId : allUserIds) { 1875 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1876 permission, userId)) { 1877 grantRuntimePermission(pkg.packageName, permission, userId); 1878 } 1879 } 1880 } 1881 } 1882 1883 private StorageEventListener mStorageListener = new StorageEventListener() { 1884 @Override 1885 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1886 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1887 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1888 final String volumeUuid = vol.getFsUuid(); 1889 1890 // Clean up any users or apps that were removed or recreated 1891 // while this volume was missing 1892 reconcileUsers(volumeUuid); 1893 reconcileApps(volumeUuid); 1894 1895 // Clean up any install sessions that expired or were 1896 // cancelled while this volume was missing 1897 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1898 1899 loadPrivatePackages(vol); 1900 1901 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1902 unloadPrivatePackages(vol); 1903 } 1904 } 1905 1906 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1907 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1908 updateExternalMediaStatus(true, false); 1909 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1910 updateExternalMediaStatus(false, false); 1911 } 1912 } 1913 } 1914 1915 @Override 1916 public void onVolumeForgotten(String fsUuid) { 1917 if (TextUtils.isEmpty(fsUuid)) { 1918 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1919 return; 1920 } 1921 1922 // Remove any apps installed on the forgotten volume 1923 synchronized (mPackages) { 1924 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1925 for (PackageSetting ps : packages) { 1926 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1927 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1928 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1929 1930 // Try very hard to release any references to this package 1931 // so we don't risk the system server being killed due to 1932 // open FDs 1933 AttributeCache.instance().removePackage(ps.name); 1934 } 1935 1936 mSettings.onVolumeForgotten(fsUuid); 1937 mSettings.writeLPr(); 1938 } 1939 } 1940 }; 1941 1942 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1943 String[] grantedPermissions) { 1944 for (int userId : userIds) { 1945 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1946 } 1947 1948 // We could have touched GID membership, so flush out packages.list 1949 synchronized (mPackages) { 1950 mSettings.writePackageListLPr(); 1951 } 1952 } 1953 1954 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1955 String[] grantedPermissions) { 1956 SettingBase sb = (SettingBase) pkg.mExtras; 1957 if (sb == null) { 1958 return; 1959 } 1960 1961 PermissionsState permissionsState = sb.getPermissionsState(); 1962 1963 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1964 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1965 1966 for (String permission : pkg.requestedPermissions) { 1967 final BasePermission bp; 1968 synchronized (mPackages) { 1969 bp = mSettings.mPermissions.get(permission); 1970 } 1971 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1972 && (grantedPermissions == null 1973 || ArrayUtils.contains(grantedPermissions, permission))) { 1974 final int flags = permissionsState.getPermissionFlags(permission, userId); 1975 // Installer cannot change immutable permissions. 1976 if ((flags & immutableFlags) == 0) { 1977 grantRuntimePermission(pkg.packageName, permission, userId); 1978 } 1979 } 1980 } 1981 } 1982 1983 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1984 Bundle extras = null; 1985 switch (res.returnCode) { 1986 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1987 extras = new Bundle(); 1988 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1989 res.origPermission); 1990 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1991 res.origPackage); 1992 break; 1993 } 1994 case PackageManager.INSTALL_SUCCEEDED: { 1995 extras = new Bundle(); 1996 extras.putBoolean(Intent.EXTRA_REPLACING, 1997 res.removedInfo != null && res.removedInfo.removedPackage != null); 1998 break; 1999 } 2000 } 2001 return extras; 2002 } 2003 2004 void scheduleWriteSettingsLocked() { 2005 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2006 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2007 } 2008 } 2009 2010 void scheduleWritePackageListLocked(int userId) { 2011 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2012 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2013 msg.arg1 = userId; 2014 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2015 } 2016 } 2017 2018 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2019 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2020 scheduleWritePackageRestrictionsLocked(userId); 2021 } 2022 2023 void scheduleWritePackageRestrictionsLocked(int userId) { 2024 final int[] userIds = (userId == UserHandle.USER_ALL) 2025 ? sUserManager.getUserIds() : new int[]{userId}; 2026 for (int nextUserId : userIds) { 2027 if (!sUserManager.exists(nextUserId)) return; 2028 mDirtyUsers.add(nextUserId); 2029 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2030 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2031 } 2032 } 2033 } 2034 2035 public static PackageManagerService main(Context context, Installer installer, 2036 boolean factoryTest, boolean onlyCore) { 2037 // Self-check for initial settings. 2038 PackageManagerServiceCompilerMapping.checkProperties(); 2039 2040 PackageManagerService m = new PackageManagerService(context, installer, 2041 factoryTest, onlyCore); 2042 m.enableSystemUserPackages(); 2043 ServiceManager.addService("package", m); 2044 return m; 2045 } 2046 2047 private void enableSystemUserPackages() { 2048 if (!UserManager.isSplitSystemUser()) { 2049 return; 2050 } 2051 // For system user, enable apps based on the following conditions: 2052 // - app is whitelisted or belong to one of these groups: 2053 // -- system app which has no launcher icons 2054 // -- system app which has INTERACT_ACROSS_USERS permission 2055 // -- system IME app 2056 // - app is not in the blacklist 2057 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2058 Set<String> enableApps = new ArraySet<>(); 2059 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2060 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2061 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2062 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2063 enableApps.addAll(wlApps); 2064 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2065 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2066 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2067 enableApps.removeAll(blApps); 2068 Log.i(TAG, "Applications installed for system user: " + enableApps); 2069 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2070 UserHandle.SYSTEM); 2071 final int allAppsSize = allAps.size(); 2072 synchronized (mPackages) { 2073 for (int i = 0; i < allAppsSize; i++) { 2074 String pName = allAps.get(i); 2075 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2076 // Should not happen, but we shouldn't be failing if it does 2077 if (pkgSetting == null) { 2078 continue; 2079 } 2080 boolean install = enableApps.contains(pName); 2081 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2082 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2083 + " for system user"); 2084 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2085 } 2086 } 2087 } 2088 } 2089 2090 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2091 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2092 Context.DISPLAY_SERVICE); 2093 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2094 } 2095 2096 /** 2097 * Requests that files preopted on a secondary system partition be copied to the data partition 2098 * if possible. Note that the actual copying of the files is accomplished by init for security 2099 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2100 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2101 */ 2102 private static void requestCopyPreoptedFiles() { 2103 final int WAIT_TIME_MS = 100; 2104 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2105 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2106 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2107 // We will wait for up to 100 seconds. 2108 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2109 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2110 try { 2111 Thread.sleep(WAIT_TIME_MS); 2112 } catch (InterruptedException e) { 2113 // Do nothing 2114 } 2115 if (SystemClock.uptimeMillis() > timeEnd) { 2116 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2117 Slog.wtf(TAG, "cppreopt did not finish!"); 2118 break; 2119 } 2120 } 2121 } 2122 } 2123 2124 public PackageManagerService(Context context, Installer installer, 2125 boolean factoryTest, boolean onlyCore) { 2126 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2127 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2128 SystemClock.uptimeMillis()); 2129 2130 if (mSdkVersion <= 0) { 2131 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2132 } 2133 2134 mContext = context; 2135 2136 mPermissionReviewRequired = context.getResources().getBoolean( 2137 R.bool.config_permissionReviewRequired); 2138 2139 mFactoryTest = factoryTest; 2140 mOnlyCore = onlyCore; 2141 mMetrics = new DisplayMetrics(); 2142 mSettings = new Settings(mPackages); 2143 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2144 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2145 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2146 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2147 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2148 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2149 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2150 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2151 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2152 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2153 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2154 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2155 2156 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2157 if (separateProcesses != null && separateProcesses.length() > 0) { 2158 if ("*".equals(separateProcesses)) { 2159 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2160 mSeparateProcesses = null; 2161 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2162 } else { 2163 mDefParseFlags = 0; 2164 mSeparateProcesses = separateProcesses.split(","); 2165 Slog.w(TAG, "Running with debug.separate_processes: " 2166 + separateProcesses); 2167 } 2168 } else { 2169 mDefParseFlags = 0; 2170 mSeparateProcesses = null; 2171 } 2172 2173 mInstaller = installer; 2174 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2175 "*dexopt*"); 2176 mDexManager = new DexManager(); 2177 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2178 2179 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2180 FgThread.get().getLooper()); 2181 2182 getDefaultDisplayMetrics(context, mMetrics); 2183 2184 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2185 SystemConfig systemConfig = SystemConfig.getInstance(); 2186 mGlobalGids = systemConfig.getGlobalGids(); 2187 mSystemPermissions = systemConfig.getSystemPermissions(); 2188 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2189 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2190 2191 mProtectedPackages = new ProtectedPackages(mContext); 2192 2193 synchronized (mInstallLock) { 2194 // writer 2195 synchronized (mPackages) { 2196 mHandlerThread = new ServiceThread(TAG, 2197 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2198 mHandlerThread.start(); 2199 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2200 mProcessLoggingHandler = new ProcessLoggingHandler(); 2201 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2202 2203 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2204 2205 File dataDir = Environment.getDataDirectory(); 2206 mAppInstallDir = new File(dataDir, "app"); 2207 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2208 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2209 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2210 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2211 2212 sUserManager = new UserManagerService(context, this, mPackages); 2213 2214 // Propagate permission configuration in to package manager. 2215 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2216 = systemConfig.getPermissions(); 2217 for (int i=0; i<permConfig.size(); i++) { 2218 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2219 BasePermission bp = mSettings.mPermissions.get(perm.name); 2220 if (bp == null) { 2221 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2222 mSettings.mPermissions.put(perm.name, bp); 2223 } 2224 if (perm.gids != null) { 2225 bp.setGids(perm.gids, perm.perUser); 2226 } 2227 } 2228 2229 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2230 for (int i=0; i<libConfig.size(); i++) { 2231 mSharedLibraries.put(libConfig.keyAt(i), 2232 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2233 } 2234 2235 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2236 2237 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2238 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2239 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2240 2241 // Clean up orphaned packages for which the code path doesn't exist 2242 // and they are an update to a system app - caused by bug/32321269 2243 final int packageSettingCount = mSettings.mPackages.size(); 2244 for (int i = packageSettingCount - 1; i >= 0; i--) { 2245 PackageSetting ps = mSettings.mPackages.valueAt(i); 2246 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2247 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2248 mSettings.mPackages.removeAt(i); 2249 mSettings.enableSystemPackageLPw(ps.name); 2250 } 2251 } 2252 2253 if (mFirstBoot) { 2254 requestCopyPreoptedFiles(); 2255 } 2256 2257 String customResolverActivity = Resources.getSystem().getString( 2258 R.string.config_customResolverActivity); 2259 if (TextUtils.isEmpty(customResolverActivity)) { 2260 customResolverActivity = null; 2261 } else { 2262 mCustomResolverComponentName = ComponentName.unflattenFromString( 2263 customResolverActivity); 2264 } 2265 2266 long startTime = SystemClock.uptimeMillis(); 2267 2268 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2269 startTime); 2270 2271 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2272 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2273 2274 if (bootClassPath == null) { 2275 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2276 } 2277 2278 if (systemServerClassPath == null) { 2279 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2280 } 2281 2282 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2283 final String[] dexCodeInstructionSets = 2284 getDexCodeInstructionSets( 2285 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2286 2287 /** 2288 * Ensure all external libraries have had dexopt run on them. 2289 */ 2290 if (mSharedLibraries.size() > 0) { 2291 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2292 // NOTE: For now, we're compiling these system "shared libraries" 2293 // (and framework jars) into all available architectures. It's possible 2294 // to compile them only when we come across an app that uses them (there's 2295 // already logic for that in scanPackageLI) but that adds some complexity. 2296 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2297 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2298 final String lib = libEntry.path; 2299 if (lib == null) { 2300 continue; 2301 } 2302 2303 try { 2304 // Shared libraries do not have profiles so we perform a full 2305 // AOT compilation (if needed). 2306 int dexoptNeeded = DexFile.getDexOptNeeded( 2307 lib, dexCodeInstructionSet, 2308 getCompilerFilterForReason(REASON_SHARED_APK), 2309 false /* newProfile */); 2310 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2311 mInstaller.dexopt(lib, Process.SYSTEM_UID, "*", 2312 dexCodeInstructionSet, dexoptNeeded, null, 2313 DEXOPT_PUBLIC, 2314 getCompilerFilterForReason(REASON_SHARED_APK), 2315 StorageManager.UUID_PRIVATE_INTERNAL, 2316 SKIP_SHARED_LIBRARY_CHECK); 2317 } 2318 } catch (FileNotFoundException e) { 2319 Slog.w(TAG, "Library not found: " + lib); 2320 } catch (IOException | InstallerException e) { 2321 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2322 + e.getMessage()); 2323 } 2324 } 2325 } 2326 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2327 } 2328 2329 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2330 2331 final VersionInfo ver = mSettings.getInternalVersion(); 2332 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2333 2334 // when upgrading from pre-M, promote system app permissions from install to runtime 2335 mPromoteSystemApps = 2336 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2337 2338 // When upgrading from pre-N, we need to handle package extraction like first boot, 2339 // as there is no profiling data available. 2340 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2341 2342 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2343 2344 // save off the names of pre-existing system packages prior to scanning; we don't 2345 // want to automatically grant runtime permissions for new system apps 2346 if (mPromoteSystemApps) { 2347 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2348 while (pkgSettingIter.hasNext()) { 2349 PackageSetting ps = pkgSettingIter.next(); 2350 if (isSystemApp(ps)) { 2351 mExistingSystemPackages.add(ps.name); 2352 } 2353 } 2354 } 2355 2356 // Set flag to monitor and not change apk file paths when 2357 // scanning install directories. 2358 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2359 2360 if (mIsUpgrade || mFirstBoot) { 2361 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2362 } 2363 2364 // Collect vendor overlay packages. (Do this before scanning any apps.) 2365 // For security and version matching reason, only consider 2366 // overlay packages if they reside in the right directory. 2367 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2368 if (overlayThemeDir.isEmpty()) { 2369 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2370 } 2371 if (!overlayThemeDir.isEmpty()) { 2372 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2373 | PackageParser.PARSE_IS_SYSTEM 2374 | PackageParser.PARSE_IS_SYSTEM_DIR 2375 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2376 } 2377 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2378 | PackageParser.PARSE_IS_SYSTEM 2379 | PackageParser.PARSE_IS_SYSTEM_DIR 2380 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2381 2382 // Find base frameworks (resource packages without code). 2383 scanDirTracedLI(frameworkDir, mDefParseFlags 2384 | PackageParser.PARSE_IS_SYSTEM 2385 | PackageParser.PARSE_IS_SYSTEM_DIR 2386 | PackageParser.PARSE_IS_PRIVILEGED, 2387 scanFlags | SCAN_NO_DEX, 0); 2388 2389 // Collected privileged system packages. 2390 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2391 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2392 | PackageParser.PARSE_IS_SYSTEM 2393 | PackageParser.PARSE_IS_SYSTEM_DIR 2394 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2395 2396 // Collect ordinary system packages. 2397 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2398 scanDirTracedLI(systemAppDir, mDefParseFlags 2399 | PackageParser.PARSE_IS_SYSTEM 2400 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2401 2402 // Collect all vendor packages. 2403 File vendorAppDir = new File("/vendor/app"); 2404 try { 2405 vendorAppDir = vendorAppDir.getCanonicalFile(); 2406 } catch (IOException e) { 2407 // failed to look up canonical path, continue with original one 2408 } 2409 scanDirTracedLI(vendorAppDir, mDefParseFlags 2410 | PackageParser.PARSE_IS_SYSTEM 2411 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2412 2413 // Collect all OEM packages. 2414 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2415 scanDirTracedLI(oemAppDir, mDefParseFlags 2416 | PackageParser.PARSE_IS_SYSTEM 2417 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2418 2419 // Prune any system packages that no longer exist. 2420 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2421 if (!mOnlyCore) { 2422 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2423 while (psit.hasNext()) { 2424 PackageSetting ps = psit.next(); 2425 2426 /* 2427 * If this is not a system app, it can't be a 2428 * disable system app. 2429 */ 2430 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2431 continue; 2432 } 2433 2434 /* 2435 * If the package is scanned, it's not erased. 2436 */ 2437 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2438 if (scannedPkg != null) { 2439 /* 2440 * If the system app is both scanned and in the 2441 * disabled packages list, then it must have been 2442 * added via OTA. Remove it from the currently 2443 * scanned package so the previously user-installed 2444 * application can be scanned. 2445 */ 2446 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2447 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2448 + ps.name + "; removing system app. Last known codePath=" 2449 + ps.codePathString + ", installStatus=" + ps.installStatus 2450 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2451 + scannedPkg.mVersionCode); 2452 removePackageLI(scannedPkg, true); 2453 mExpectingBetter.put(ps.name, ps.codePath); 2454 } 2455 2456 continue; 2457 } 2458 2459 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2460 psit.remove(); 2461 logCriticalInfo(Log.WARN, "System package " + ps.name 2462 + " no longer exists; it's data will be wiped"); 2463 // Actual deletion of code and data will be handled by later 2464 // reconciliation step 2465 } else { 2466 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2467 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2468 possiblyDeletedUpdatedSystemApps.add(ps.name); 2469 } 2470 } 2471 } 2472 } 2473 2474 //look for any incomplete package installations 2475 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2476 for (int i = 0; i < deletePkgsList.size(); i++) { 2477 // Actual deletion of code and data will be handled by later 2478 // reconciliation step 2479 final String packageName = deletePkgsList.get(i).name; 2480 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2481 synchronized (mPackages) { 2482 mSettings.removePackageLPw(packageName); 2483 } 2484 } 2485 2486 //delete tmp files 2487 deleteTempPackageFiles(); 2488 2489 // Remove any shared userIDs that have no associated packages 2490 mSettings.pruneSharedUsersLPw(); 2491 2492 if (!mOnlyCore) { 2493 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2494 SystemClock.uptimeMillis()); 2495 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2496 2497 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2498 | PackageParser.PARSE_FORWARD_LOCK, 2499 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2500 2501 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2502 | PackageParser.PARSE_IS_EPHEMERAL, 2503 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2504 2505 /** 2506 * Remove disable package settings for any updated system 2507 * apps that were removed via an OTA. If they're not a 2508 * previously-updated app, remove them completely. 2509 * Otherwise, just revoke their system-level permissions. 2510 */ 2511 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2512 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2513 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2514 2515 String msg; 2516 if (deletedPkg == null) { 2517 msg = "Updated system package " + deletedAppName 2518 + " no longer exists; it's data will be wiped"; 2519 // Actual deletion of code and data will be handled by later 2520 // reconciliation step 2521 } else { 2522 msg = "Updated system app + " + deletedAppName 2523 + " no longer present; removing system privileges for " 2524 + deletedAppName; 2525 2526 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2527 2528 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2529 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2530 } 2531 logCriticalInfo(Log.WARN, msg); 2532 } 2533 2534 /** 2535 * Make sure all system apps that we expected to appear on 2536 * the userdata partition actually showed up. If they never 2537 * appeared, crawl back and revive the system version. 2538 */ 2539 for (int i = 0; i < mExpectingBetter.size(); i++) { 2540 final String packageName = mExpectingBetter.keyAt(i); 2541 if (!mPackages.containsKey(packageName)) { 2542 final File scanFile = mExpectingBetter.valueAt(i); 2543 2544 logCriticalInfo(Log.WARN, "Expected better " + packageName 2545 + " but never showed up; reverting to system"); 2546 2547 int reparseFlags = mDefParseFlags; 2548 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2549 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2550 | PackageParser.PARSE_IS_SYSTEM_DIR 2551 | PackageParser.PARSE_IS_PRIVILEGED; 2552 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2553 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2554 | PackageParser.PARSE_IS_SYSTEM_DIR; 2555 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2556 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2557 | PackageParser.PARSE_IS_SYSTEM_DIR; 2558 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2559 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2560 | PackageParser.PARSE_IS_SYSTEM_DIR; 2561 } else { 2562 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2563 continue; 2564 } 2565 2566 mSettings.enableSystemPackageLPw(packageName); 2567 2568 try { 2569 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2570 } catch (PackageManagerException e) { 2571 Slog.e(TAG, "Failed to parse original system package: " 2572 + e.getMessage()); 2573 } 2574 } 2575 } 2576 } 2577 mExpectingBetter.clear(); 2578 2579 // Resolve the storage manager. 2580 mStorageManagerPackage = getStorageManagerPackageName(); 2581 2582 // Resolve protected action filters. Only the setup wizard is allowed to 2583 // have a high priority filter for these actions. 2584 mSetupWizardPackage = getSetupWizardPackageName(); 2585 if (mProtectedFilters.size() > 0) { 2586 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2587 Slog.i(TAG, "No setup wizard;" 2588 + " All protected intents capped to priority 0"); 2589 } 2590 for (ActivityIntentInfo filter : mProtectedFilters) { 2591 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2592 if (DEBUG_FILTERS) { 2593 Slog.i(TAG, "Found setup wizard;" 2594 + " allow priority " + filter.getPriority() + ";" 2595 + " package: " + filter.activity.info.packageName 2596 + " activity: " + filter.activity.className 2597 + " priority: " + filter.getPriority()); 2598 } 2599 // skip setup wizard; allow it to keep the high priority filter 2600 continue; 2601 } 2602 Slog.w(TAG, "Protected action; cap priority to 0;" 2603 + " package: " + filter.activity.info.packageName 2604 + " activity: " + filter.activity.className 2605 + " origPrio: " + filter.getPriority()); 2606 filter.setPriority(0); 2607 } 2608 } 2609 mDeferProtectedFilters = false; 2610 mProtectedFilters.clear(); 2611 2612 // Now that we know all of the shared libraries, update all clients to have 2613 // the correct library paths. 2614 updateAllSharedLibrariesLPw(); 2615 2616 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2617 // NOTE: We ignore potential failures here during a system scan (like 2618 // the rest of the commands above) because there's precious little we 2619 // can do about it. A settings error is reported, though. 2620 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2621 } 2622 2623 // Now that we know all the packages we are keeping, 2624 // read and update their last usage times. 2625 mPackageUsage.read(mPackages); 2626 mCompilerStats.read(); 2627 2628 // Read and update the usage of dex files. 2629 // At this point we know the code paths of the packages, so we can validate 2630 // the disk file and build the internal cache. 2631 // The usage file is expected to be small so loading and verifying it 2632 // should take a fairly small time compare to the other activities (e.g. package 2633 // scanning). 2634 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2635 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2636 for (int userId : currentUserIds) { 2637 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2638 } 2639 mDexManager.load(userPackages); 2640 2641 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2642 SystemClock.uptimeMillis()); 2643 Slog.i(TAG, "Time to scan packages: " 2644 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2645 + " seconds"); 2646 2647 // If the platform SDK has changed since the last time we booted, 2648 // we need to re-grant app permission to catch any new ones that 2649 // appear. This is really a hack, and means that apps can in some 2650 // cases get permissions that the user didn't initially explicitly 2651 // allow... it would be nice to have some better way to handle 2652 // this situation. 2653 int updateFlags = UPDATE_PERMISSIONS_ALL; 2654 if (ver.sdkVersion != mSdkVersion) { 2655 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2656 + mSdkVersion + "; regranting permissions for internal storage"); 2657 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2658 } 2659 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2660 ver.sdkVersion = mSdkVersion; 2661 2662 // If this is the first boot or an update from pre-M, and it is a normal 2663 // boot, then we need to initialize the default preferred apps across 2664 // all defined users. 2665 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2666 for (UserInfo user : sUserManager.getUsers(true)) { 2667 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2668 applyFactoryDefaultBrowserLPw(user.id); 2669 primeDomainVerificationsLPw(user.id); 2670 } 2671 } 2672 2673 // Prepare storage for system user really early during boot, 2674 // since core system apps like SettingsProvider and SystemUI 2675 // can't wait for user to start 2676 final int storageFlags; 2677 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2678 storageFlags = StorageManager.FLAG_STORAGE_DE; 2679 } else { 2680 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2681 } 2682 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2683 storageFlags, true /* migrateAppData */); 2684 2685 // If this is first boot after an OTA, and a normal boot, then 2686 // we need to clear code cache directories. 2687 // Note that we do *not* clear the application profiles. These remain valid 2688 // across OTAs and are used to drive profile verification (post OTA) and 2689 // profile compilation (without waiting to collect a fresh set of profiles). 2690 if (mIsUpgrade && !onlyCore) { 2691 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2692 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2693 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2694 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2695 // No apps are running this early, so no need to freeze 2696 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2697 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2698 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2699 } 2700 } 2701 ver.fingerprint = Build.FINGERPRINT; 2702 } 2703 2704 checkDefaultBrowser(); 2705 2706 // clear only after permissions and other defaults have been updated 2707 mExistingSystemPackages.clear(); 2708 mPromoteSystemApps = false; 2709 2710 // All the changes are done during package scanning. 2711 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2712 2713 // can downgrade to reader 2714 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2715 mSettings.writeLPr(); 2716 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2717 2718 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2719 // early on (before the package manager declares itself as early) because other 2720 // components in the system server might ask for package contexts for these apps. 2721 // 2722 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2723 // (i.e, that the data partition is unavailable). 2724 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2725 long start = System.nanoTime(); 2726 List<PackageParser.Package> coreApps = new ArrayList<>(); 2727 for (PackageParser.Package pkg : mPackages.values()) { 2728 if (pkg.coreApp) { 2729 coreApps.add(pkg); 2730 } 2731 } 2732 2733 int[] stats = performDexOptUpgrade(coreApps, false, 2734 getCompilerFilterForReason(REASON_CORE_APP)); 2735 2736 final int elapsedTimeSeconds = 2737 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2738 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2739 2740 if (DEBUG_DEXOPT) { 2741 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2742 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2743 } 2744 2745 2746 // TODO: Should we log these stats to tron too ? 2747 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2748 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2749 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2750 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2751 } 2752 2753 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2754 SystemClock.uptimeMillis()); 2755 2756 if (!mOnlyCore) { 2757 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2758 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2759 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2760 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2761 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2762 mIntentFilterVerifierComponent); 2763 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2764 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2765 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2766 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2767 } else { 2768 mRequiredVerifierPackage = null; 2769 mRequiredInstallerPackage = null; 2770 mRequiredUninstallerPackage = null; 2771 mIntentFilterVerifierComponent = null; 2772 mIntentFilterVerifier = null; 2773 mServicesSystemSharedLibraryPackageName = null; 2774 mSharedSystemSharedLibraryPackageName = null; 2775 } 2776 2777 mInstallerService = new PackageInstallerService(context, this); 2778 2779 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2780 if (ephemeralResolverComponent != null) { 2781 if (DEBUG_EPHEMERAL) { 2782 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2783 } 2784 mEphemeralResolverConnection = 2785 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2786 } else { 2787 mEphemeralResolverConnection = null; 2788 } 2789 mEphemeralInstallerComponent = getEphemeralInstallerLPr(); 2790 if (mEphemeralInstallerComponent != null) { 2791 if (DEBUG_EPHEMERAL) { 2792 Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent); 2793 } 2794 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2795 } 2796 2797 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2798 } // synchronized (mPackages) 2799 } // synchronized (mInstallLock) 2800 2801 // Now after opening every single application zip, make sure they 2802 // are all flushed. Not really needed, but keeps things nice and 2803 // tidy. 2804 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2805 Runtime.getRuntime().gc(); 2806 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2807 2808 // The initial scanning above does many calls into installd while 2809 // holding the mPackages lock, but we're mostly interested in yelling 2810 // once we have a booted system. 2811 mInstaller.setWarnIfHeld(mPackages); 2812 2813 // Expose private service for system components to use. 2814 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2815 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2816 } 2817 2818 @Override 2819 public boolean isFirstBoot() { 2820 return mFirstBoot; 2821 } 2822 2823 @Override 2824 public boolean isOnlyCoreApps() { 2825 return mOnlyCore; 2826 } 2827 2828 @Override 2829 public boolean isUpgrade() { 2830 return mIsUpgrade; 2831 } 2832 2833 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2834 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2835 2836 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2837 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2838 UserHandle.USER_SYSTEM); 2839 if (matches.size() == 1) { 2840 return matches.get(0).getComponentInfo().packageName; 2841 } else if (matches.size() == 0) { 2842 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2843 return null; 2844 } 2845 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2846 } 2847 2848 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2849 synchronized (mPackages) { 2850 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2851 if (libraryEntry == null) { 2852 throw new IllegalStateException("Missing required shared library:" + libraryName); 2853 } 2854 return libraryEntry.apk; 2855 } 2856 } 2857 2858 private @NonNull String getRequiredInstallerLPr() { 2859 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2860 intent.addCategory(Intent.CATEGORY_DEFAULT); 2861 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2862 2863 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2864 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2865 UserHandle.USER_SYSTEM); 2866 if (matches.size() == 1) { 2867 ResolveInfo resolveInfo = matches.get(0); 2868 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2869 throw new RuntimeException("The installer must be a privileged app"); 2870 } 2871 return matches.get(0).getComponentInfo().packageName; 2872 } else { 2873 throw new RuntimeException("There must be exactly one installer; found " + matches); 2874 } 2875 } 2876 2877 private @NonNull String getRequiredUninstallerLPr() { 2878 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2879 intent.addCategory(Intent.CATEGORY_DEFAULT); 2880 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2881 2882 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2883 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2884 UserHandle.USER_SYSTEM); 2885 if (resolveInfo == null || 2886 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2887 throw new RuntimeException("There must be exactly one uninstaller; found " 2888 + resolveInfo); 2889 } 2890 return resolveInfo.getComponentInfo().packageName; 2891 } 2892 2893 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2894 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2895 2896 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2897 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2898 UserHandle.USER_SYSTEM); 2899 ResolveInfo best = null; 2900 final int N = matches.size(); 2901 for (int i = 0; i < N; i++) { 2902 final ResolveInfo cur = matches.get(i); 2903 final String packageName = cur.getComponentInfo().packageName; 2904 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2905 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2906 continue; 2907 } 2908 2909 if (best == null || cur.priority > best.priority) { 2910 best = cur; 2911 } 2912 } 2913 2914 if (best != null) { 2915 return best.getComponentInfo().getComponentName(); 2916 } else { 2917 throw new RuntimeException("There must be at least one intent filter verifier"); 2918 } 2919 } 2920 2921 private @Nullable ComponentName getEphemeralResolverLPr() { 2922 final String[] packageArray = 2923 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2924 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2925 if (DEBUG_EPHEMERAL) { 2926 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2927 } 2928 return null; 2929 } 2930 2931 final int resolveFlags = 2932 MATCH_DIRECT_BOOT_AWARE 2933 | MATCH_DIRECT_BOOT_UNAWARE 2934 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2935 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2936 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2937 resolveFlags, UserHandle.USER_SYSTEM); 2938 2939 final int N = resolvers.size(); 2940 if (N == 0) { 2941 if (DEBUG_EPHEMERAL) { 2942 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2943 } 2944 return null; 2945 } 2946 2947 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2948 for (int i = 0; i < N; i++) { 2949 final ResolveInfo info = resolvers.get(i); 2950 2951 if (info.serviceInfo == null) { 2952 continue; 2953 } 2954 2955 final String packageName = info.serviceInfo.packageName; 2956 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2957 if (DEBUG_EPHEMERAL) { 2958 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2959 + " pkg: " + packageName + ", info:" + info); 2960 } 2961 continue; 2962 } 2963 2964 if (DEBUG_EPHEMERAL) { 2965 Slog.v(TAG, "Ephemeral resolver found;" 2966 + " pkg: " + packageName + ", info:" + info); 2967 } 2968 return new ComponentName(packageName, info.serviceInfo.name); 2969 } 2970 if (DEBUG_EPHEMERAL) { 2971 Slog.v(TAG, "Ephemeral resolver NOT found"); 2972 } 2973 return null; 2974 } 2975 2976 private @Nullable ComponentName getEphemeralInstallerLPr() { 2977 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2978 intent.addCategory(Intent.CATEGORY_DEFAULT); 2979 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2980 2981 final int resolveFlags = 2982 MATCH_DIRECT_BOOT_AWARE 2983 | MATCH_DIRECT_BOOT_UNAWARE 2984 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2985 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2986 resolveFlags, UserHandle.USER_SYSTEM); 2987 Iterator<ResolveInfo> iter = matches.iterator(); 2988 while (iter.hasNext()) { 2989 final ResolveInfo rInfo = iter.next(); 2990 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 2991 if (ps != null) { 2992 final PermissionsState permissionsState = ps.getPermissionsState(); 2993 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 2994 continue; 2995 } 2996 } 2997 iter.remove(); 2998 } 2999 if (matches.size() == 0) { 3000 return null; 3001 } else if (matches.size() == 1) { 3002 return matches.get(0).getComponentInfo().getComponentName(); 3003 } else { 3004 throw new RuntimeException( 3005 "There must be at most one ephemeral installer; found " + matches); 3006 } 3007 } 3008 3009 private void primeDomainVerificationsLPw(int userId) { 3010 if (DEBUG_DOMAIN_VERIFICATION) { 3011 Slog.d(TAG, "Priming domain verifications in user " + userId); 3012 } 3013 3014 SystemConfig systemConfig = SystemConfig.getInstance(); 3015 ArraySet<String> packages = systemConfig.getLinkedApps(); 3016 3017 for (String packageName : packages) { 3018 PackageParser.Package pkg = mPackages.get(packageName); 3019 if (pkg != null) { 3020 if (!pkg.isSystemApp()) { 3021 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3022 continue; 3023 } 3024 3025 ArraySet<String> domains = null; 3026 for (PackageParser.Activity a : pkg.activities) { 3027 for (ActivityIntentInfo filter : a.intents) { 3028 if (hasValidDomains(filter)) { 3029 if (domains == null) { 3030 domains = new ArraySet<String>(); 3031 } 3032 domains.addAll(filter.getHostsList()); 3033 } 3034 } 3035 } 3036 3037 if (domains != null && domains.size() > 0) { 3038 if (DEBUG_DOMAIN_VERIFICATION) { 3039 Slog.v(TAG, " + " + packageName); 3040 } 3041 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3042 // state w.r.t. the formal app-linkage "no verification attempted" state; 3043 // and then 'always' in the per-user state actually used for intent resolution. 3044 final IntentFilterVerificationInfo ivi; 3045 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3046 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3047 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3048 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3049 } else { 3050 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3051 + "' does not handle web links"); 3052 } 3053 } else { 3054 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3055 } 3056 } 3057 3058 scheduleWritePackageRestrictionsLocked(userId); 3059 scheduleWriteSettingsLocked(); 3060 } 3061 3062 private void applyFactoryDefaultBrowserLPw(int userId) { 3063 // The default browser app's package name is stored in a string resource, 3064 // with a product-specific overlay used for vendor customization. 3065 String browserPkg = mContext.getResources().getString( 3066 com.android.internal.R.string.default_browser); 3067 if (!TextUtils.isEmpty(browserPkg)) { 3068 // non-empty string => required to be a known package 3069 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3070 if (ps == null) { 3071 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3072 browserPkg = null; 3073 } else { 3074 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3075 } 3076 } 3077 3078 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3079 // default. If there's more than one, just leave everything alone. 3080 if (browserPkg == null) { 3081 calculateDefaultBrowserLPw(userId); 3082 } 3083 } 3084 3085 private void calculateDefaultBrowserLPw(int userId) { 3086 List<String> allBrowsers = resolveAllBrowserApps(userId); 3087 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3088 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3089 } 3090 3091 private List<String> resolveAllBrowserApps(int userId) { 3092 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3093 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3094 PackageManager.MATCH_ALL, userId); 3095 3096 final int count = list.size(); 3097 List<String> result = new ArrayList<String>(count); 3098 for (int i=0; i<count; i++) { 3099 ResolveInfo info = list.get(i); 3100 if (info.activityInfo == null 3101 || !info.handleAllWebDataURI 3102 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3103 || result.contains(info.activityInfo.packageName)) { 3104 continue; 3105 } 3106 result.add(info.activityInfo.packageName); 3107 } 3108 3109 return result; 3110 } 3111 3112 private boolean packageIsBrowser(String packageName, int userId) { 3113 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3114 PackageManager.MATCH_ALL, userId); 3115 final int N = list.size(); 3116 for (int i = 0; i < N; i++) { 3117 ResolveInfo info = list.get(i); 3118 if (packageName.equals(info.activityInfo.packageName)) { 3119 return true; 3120 } 3121 } 3122 return false; 3123 } 3124 3125 private void checkDefaultBrowser() { 3126 final int myUserId = UserHandle.myUserId(); 3127 final String packageName = getDefaultBrowserPackageName(myUserId); 3128 if (packageName != null) { 3129 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3130 if (info == null) { 3131 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3132 synchronized (mPackages) { 3133 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3134 } 3135 } 3136 } 3137 } 3138 3139 @Override 3140 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3141 throws RemoteException { 3142 try { 3143 return super.onTransact(code, data, reply, flags); 3144 } catch (RuntimeException e) { 3145 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3146 Slog.wtf(TAG, "Package Manager Crash", e); 3147 } 3148 throw e; 3149 } 3150 } 3151 3152 static int[] appendInts(int[] cur, int[] add) { 3153 if (add == null) return cur; 3154 if (cur == null) return add; 3155 final int N = add.length; 3156 for (int i=0; i<N; i++) { 3157 cur = appendInt(cur, add[i]); 3158 } 3159 return cur; 3160 } 3161 3162 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3163 if (!sUserManager.exists(userId)) return null; 3164 if (ps == null) { 3165 return null; 3166 } 3167 final PackageParser.Package p = ps.pkg; 3168 if (p == null) { 3169 return null; 3170 } 3171 3172 final PermissionsState permissionsState = ps.getPermissionsState(); 3173 3174 // Compute GIDs only if requested 3175 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3176 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3177 // Compute granted permissions only if package has requested permissions 3178 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3179 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3180 final PackageUserState state = ps.readUserState(userId); 3181 3182 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3183 && ps.isSystem()) { 3184 flags |= MATCH_ANY_USER; 3185 } 3186 3187 return PackageParser.generatePackageInfo(p, gids, flags, 3188 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3189 } 3190 3191 @Override 3192 public void checkPackageStartable(String packageName, int userId) { 3193 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3194 3195 synchronized (mPackages) { 3196 final PackageSetting ps = mSettings.mPackages.get(packageName); 3197 if (ps == null) { 3198 throw new SecurityException("Package " + packageName + " was not found!"); 3199 } 3200 3201 if (!ps.getInstalled(userId)) { 3202 throw new SecurityException( 3203 "Package " + packageName + " was not installed for user " + userId + "!"); 3204 } 3205 3206 if (mSafeMode && !ps.isSystem()) { 3207 throw new SecurityException("Package " + packageName + " not a system app!"); 3208 } 3209 3210 if (mFrozenPackages.contains(packageName)) { 3211 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3212 } 3213 3214 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3215 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3216 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3217 } 3218 } 3219 } 3220 3221 @Override 3222 public boolean isPackageAvailable(String packageName, int userId) { 3223 if (!sUserManager.exists(userId)) return false; 3224 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3225 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3226 synchronized (mPackages) { 3227 PackageParser.Package p = mPackages.get(packageName); 3228 if (p != null) { 3229 final PackageSetting ps = (PackageSetting) p.mExtras; 3230 if (ps != null) { 3231 final PackageUserState state = ps.readUserState(userId); 3232 if (state != null) { 3233 return PackageParser.isAvailable(state); 3234 } 3235 } 3236 } 3237 } 3238 return false; 3239 } 3240 3241 @Override 3242 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3243 if (!sUserManager.exists(userId)) return null; 3244 flags = updateFlagsForPackage(flags, userId, packageName); 3245 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3246 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3247 3248 // reader 3249 synchronized (mPackages) { 3250 // Normalize package name to hanlde renamed packages 3251 packageName = normalizePackageNameLPr(packageName); 3252 3253 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3254 PackageParser.Package p = null; 3255 if (matchFactoryOnly) { 3256 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3257 if (ps != null) { 3258 return generatePackageInfo(ps, flags, userId); 3259 } 3260 } 3261 if (p == null) { 3262 p = mPackages.get(packageName); 3263 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3264 return null; 3265 } 3266 } 3267 if (DEBUG_PACKAGE_INFO) 3268 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3269 if (p != null) { 3270 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3271 } 3272 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3273 final PackageSetting ps = mSettings.mPackages.get(packageName); 3274 return generatePackageInfo(ps, flags, userId); 3275 } 3276 } 3277 return null; 3278 } 3279 3280 @Override 3281 public String[] currentToCanonicalPackageNames(String[] names) { 3282 String[] out = new String[names.length]; 3283 // reader 3284 synchronized (mPackages) { 3285 for (int i=names.length-1; i>=0; i--) { 3286 PackageSetting ps = mSettings.mPackages.get(names[i]); 3287 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3288 } 3289 } 3290 return out; 3291 } 3292 3293 @Override 3294 public String[] canonicalToCurrentPackageNames(String[] names) { 3295 String[] out = new String[names.length]; 3296 // reader 3297 synchronized (mPackages) { 3298 for (int i=names.length-1; i>=0; i--) { 3299 String cur = mSettings.getRenamedPackageLPr(names[i]); 3300 out[i] = cur != null ? cur : names[i]; 3301 } 3302 } 3303 return out; 3304 } 3305 3306 @Override 3307 public int getPackageUid(String packageName, int flags, int userId) { 3308 if (!sUserManager.exists(userId)) return -1; 3309 flags = updateFlagsForPackage(flags, userId, packageName); 3310 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3311 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3312 3313 // reader 3314 synchronized (mPackages) { 3315 final PackageParser.Package p = mPackages.get(packageName); 3316 if (p != null && p.isMatch(flags)) { 3317 return UserHandle.getUid(userId, p.applicationInfo.uid); 3318 } 3319 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3320 final PackageSetting ps = mSettings.mPackages.get(packageName); 3321 if (ps != null && ps.isMatch(flags)) { 3322 return UserHandle.getUid(userId, ps.appId); 3323 } 3324 } 3325 } 3326 3327 return -1; 3328 } 3329 3330 @Override 3331 public int[] getPackageGids(String packageName, int flags, int userId) { 3332 if (!sUserManager.exists(userId)) return null; 3333 flags = updateFlagsForPackage(flags, userId, packageName); 3334 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3335 false /* requireFullPermission */, false /* checkShell */, 3336 "getPackageGids"); 3337 3338 // reader 3339 synchronized (mPackages) { 3340 final PackageParser.Package p = mPackages.get(packageName); 3341 if (p != null && p.isMatch(flags)) { 3342 PackageSetting ps = (PackageSetting) p.mExtras; 3343 // TODO: Shouldn't this be checking for package installed state for userId and 3344 // return null? 3345 return ps.getPermissionsState().computeGids(userId); 3346 } 3347 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3348 final PackageSetting ps = mSettings.mPackages.get(packageName); 3349 if (ps != null && ps.isMatch(flags)) { 3350 return ps.getPermissionsState().computeGids(userId); 3351 } 3352 } 3353 } 3354 3355 return null; 3356 } 3357 3358 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3359 if (bp.perm != null) { 3360 return PackageParser.generatePermissionInfo(bp.perm, flags); 3361 } 3362 PermissionInfo pi = new PermissionInfo(); 3363 pi.name = bp.name; 3364 pi.packageName = bp.sourcePackage; 3365 pi.nonLocalizedLabel = bp.name; 3366 pi.protectionLevel = bp.protectionLevel; 3367 return pi; 3368 } 3369 3370 @Override 3371 public PermissionInfo getPermissionInfo(String name, int flags) { 3372 // reader 3373 synchronized (mPackages) { 3374 final BasePermission p = mSettings.mPermissions.get(name); 3375 if (p != null) { 3376 return generatePermissionInfo(p, flags); 3377 } 3378 return null; 3379 } 3380 } 3381 3382 @Override 3383 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3384 int flags) { 3385 // reader 3386 synchronized (mPackages) { 3387 if (group != null && !mPermissionGroups.containsKey(group)) { 3388 // This is thrown as NameNotFoundException 3389 return null; 3390 } 3391 3392 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3393 for (BasePermission p : mSettings.mPermissions.values()) { 3394 if (group == null) { 3395 if (p.perm == null || p.perm.info.group == null) { 3396 out.add(generatePermissionInfo(p, flags)); 3397 } 3398 } else { 3399 if (p.perm != null && group.equals(p.perm.info.group)) { 3400 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3401 } 3402 } 3403 } 3404 return new ParceledListSlice<>(out); 3405 } 3406 } 3407 3408 @Override 3409 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3410 // reader 3411 synchronized (mPackages) { 3412 return PackageParser.generatePermissionGroupInfo( 3413 mPermissionGroups.get(name), flags); 3414 } 3415 } 3416 3417 @Override 3418 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3419 // reader 3420 synchronized (mPackages) { 3421 final int N = mPermissionGroups.size(); 3422 ArrayList<PermissionGroupInfo> out 3423 = new ArrayList<PermissionGroupInfo>(N); 3424 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3425 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3426 } 3427 return new ParceledListSlice<>(out); 3428 } 3429 } 3430 3431 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3432 int userId) { 3433 if (!sUserManager.exists(userId)) return null; 3434 PackageSetting ps = mSettings.mPackages.get(packageName); 3435 if (ps != null) { 3436 if (ps.pkg == null) { 3437 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3438 if (pInfo != null) { 3439 return pInfo.applicationInfo; 3440 } 3441 return null; 3442 } 3443 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3444 ps.readUserState(userId), userId); 3445 } 3446 return null; 3447 } 3448 3449 @Override 3450 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3451 if (!sUserManager.exists(userId)) return null; 3452 flags = updateFlagsForApplication(flags, userId, packageName); 3453 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3454 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3455 3456 // writer 3457 synchronized (mPackages) { 3458 // Normalize package name to hanlde renamed packages 3459 packageName = normalizePackageNameLPr(packageName); 3460 3461 PackageParser.Package p = mPackages.get(packageName); 3462 if (DEBUG_PACKAGE_INFO) Log.v( 3463 TAG, "getApplicationInfo " + packageName 3464 + ": " + p); 3465 if (p != null) { 3466 PackageSetting ps = mSettings.mPackages.get(packageName); 3467 if (ps == null) return null; 3468 // Note: isEnabledLP() does not apply here - always return info 3469 return PackageParser.generateApplicationInfo( 3470 p, flags, ps.readUserState(userId), userId); 3471 } 3472 if ("android".equals(packageName)||"system".equals(packageName)) { 3473 return mAndroidApplication; 3474 } 3475 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3476 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3477 } 3478 } 3479 return null; 3480 } 3481 3482 private String normalizePackageNameLPr(String packageName) { 3483 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3484 return normalizedPackageName != null ? normalizedPackageName : packageName; 3485 } 3486 3487 @Override 3488 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3489 final IPackageDataObserver observer) { 3490 mContext.enforceCallingOrSelfPermission( 3491 android.Manifest.permission.CLEAR_APP_CACHE, null); 3492 // Queue up an async operation since clearing cache may take a little while. 3493 mHandler.post(new Runnable() { 3494 public void run() { 3495 mHandler.removeCallbacks(this); 3496 boolean success = true; 3497 synchronized (mInstallLock) { 3498 try { 3499 mInstaller.freeCache(volumeUuid, freeStorageSize); 3500 } catch (InstallerException e) { 3501 Slog.w(TAG, "Couldn't clear application caches: " + e); 3502 success = false; 3503 } 3504 } 3505 if (observer != null) { 3506 try { 3507 observer.onRemoveCompleted(null, success); 3508 } catch (RemoteException e) { 3509 Slog.w(TAG, "RemoveException when invoking call back"); 3510 } 3511 } 3512 } 3513 }); 3514 } 3515 3516 @Override 3517 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3518 final IntentSender pi) { 3519 mContext.enforceCallingOrSelfPermission( 3520 android.Manifest.permission.CLEAR_APP_CACHE, null); 3521 // Queue up an async operation since clearing cache may take a little while. 3522 mHandler.post(new Runnable() { 3523 public void run() { 3524 mHandler.removeCallbacks(this); 3525 boolean success = true; 3526 synchronized (mInstallLock) { 3527 try { 3528 mInstaller.freeCache(volumeUuid, freeStorageSize); 3529 } catch (InstallerException e) { 3530 Slog.w(TAG, "Couldn't clear application caches: " + e); 3531 success = false; 3532 } 3533 } 3534 if(pi != null) { 3535 try { 3536 // Callback via pending intent 3537 int code = success ? 1 : 0; 3538 pi.sendIntent(null, code, null, 3539 null, null); 3540 } catch (SendIntentException e1) { 3541 Slog.i(TAG, "Failed to send pending intent"); 3542 } 3543 } 3544 } 3545 }); 3546 } 3547 3548 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3549 synchronized (mInstallLock) { 3550 try { 3551 mInstaller.freeCache(volumeUuid, freeStorageSize); 3552 } catch (InstallerException e) { 3553 throw new IOException("Failed to free enough space", e); 3554 } 3555 } 3556 } 3557 3558 /** 3559 * Update given flags based on encryption status of current user. 3560 */ 3561 private int updateFlags(int flags, int userId) { 3562 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3563 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3564 // Caller expressed an explicit opinion about what encryption 3565 // aware/unaware components they want to see, so fall through and 3566 // give them what they want 3567 } else { 3568 // Caller expressed no opinion, so match based on user state 3569 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3570 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3571 } else { 3572 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3573 } 3574 } 3575 return flags; 3576 } 3577 3578 private UserManagerInternal getUserManagerInternal() { 3579 if (mUserManagerInternal == null) { 3580 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3581 } 3582 return mUserManagerInternal; 3583 } 3584 3585 /** 3586 * Update given flags when being used to request {@link PackageInfo}. 3587 */ 3588 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3589 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3590 boolean triaged = true; 3591 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3592 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3593 // Caller is asking for component details, so they'd better be 3594 // asking for specific encryption matching behavior, or be triaged 3595 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3596 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3597 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3598 triaged = false; 3599 } 3600 } 3601 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3602 | PackageManager.MATCH_SYSTEM_ONLY 3603 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3604 triaged = false; 3605 } 3606 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3607 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3608 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3609 + Debug.getCallers(5)); 3610 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3611 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3612 // If the caller wants all packages and has a restricted profile associated with it, 3613 // then match all users. This is to make sure that launchers that need to access work 3614 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3615 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3616 flags |= PackageManager.MATCH_ANY_USER; 3617 } 3618 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3619 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3620 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3621 } 3622 return updateFlags(flags, userId); 3623 } 3624 3625 /** 3626 * Update given flags when being used to request {@link ApplicationInfo}. 3627 */ 3628 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3629 return updateFlagsForPackage(flags, userId, cookie); 3630 } 3631 3632 /** 3633 * Update given flags when being used to request {@link ComponentInfo}. 3634 */ 3635 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3636 if (cookie instanceof Intent) { 3637 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3638 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3639 } 3640 } 3641 3642 boolean triaged = true; 3643 // Caller is asking for component details, so they'd better be 3644 // asking for specific encryption matching behavior, or be triaged 3645 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3646 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3647 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3648 triaged = false; 3649 } 3650 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3651 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3652 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3653 } 3654 3655 return updateFlags(flags, userId); 3656 } 3657 3658 /** 3659 * Update given flags when being used to request {@link ResolveInfo}. 3660 */ 3661 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3662 // Safe mode means we shouldn't match any third-party components 3663 if (mSafeMode) { 3664 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3665 } 3666 final int callingUid = Binder.getCallingUid(); 3667 if (callingUid == Process.SYSTEM_UID || callingUid == 0) { 3668 // The system sees all components 3669 flags |= PackageManager.MATCH_EPHEMERAL; 3670 } else if (getEphemeralPackageName(callingUid) != null) { 3671 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 3672 flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY; 3673 flags |= PackageManager.MATCH_EPHEMERAL; 3674 } else { 3675 // Otherwise, prevent leaking ephemeral components 3676 flags &= ~PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY; 3677 flags &= ~PackageManager.MATCH_EPHEMERAL; 3678 } 3679 return updateFlagsForComponent(flags, userId, cookie); 3680 } 3681 3682 @Override 3683 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3684 if (!sUserManager.exists(userId)) return null; 3685 flags = updateFlagsForComponent(flags, userId, component); 3686 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3687 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3688 synchronized (mPackages) { 3689 PackageParser.Activity a = mActivities.mActivities.get(component); 3690 3691 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3692 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3693 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3694 if (ps == null) return null; 3695 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3696 userId); 3697 } 3698 if (mResolveComponentName.equals(component)) { 3699 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3700 new PackageUserState(), userId); 3701 } 3702 } 3703 return null; 3704 } 3705 3706 @Override 3707 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3708 String resolvedType) { 3709 synchronized (mPackages) { 3710 if (component.equals(mResolveComponentName)) { 3711 // The resolver supports EVERYTHING! 3712 return true; 3713 } 3714 PackageParser.Activity a = mActivities.mActivities.get(component); 3715 if (a == null) { 3716 return false; 3717 } 3718 for (int i=0; i<a.intents.size(); i++) { 3719 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3720 intent.getData(), intent.getCategories(), TAG) >= 0) { 3721 return true; 3722 } 3723 } 3724 return false; 3725 } 3726 } 3727 3728 @Override 3729 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3730 if (!sUserManager.exists(userId)) return null; 3731 flags = updateFlagsForComponent(flags, userId, component); 3732 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3733 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3734 synchronized (mPackages) { 3735 PackageParser.Activity a = mReceivers.mActivities.get(component); 3736 if (DEBUG_PACKAGE_INFO) Log.v( 3737 TAG, "getReceiverInfo " + component + ": " + a); 3738 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3739 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3740 if (ps == null) return null; 3741 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3742 userId); 3743 } 3744 } 3745 return null; 3746 } 3747 3748 @Override 3749 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3750 if (!sUserManager.exists(userId)) return null; 3751 flags = updateFlagsForComponent(flags, userId, component); 3752 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3753 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3754 synchronized (mPackages) { 3755 PackageParser.Service s = mServices.mServices.get(component); 3756 if (DEBUG_PACKAGE_INFO) Log.v( 3757 TAG, "getServiceInfo " + component + ": " + s); 3758 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3759 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3760 if (ps == null) return null; 3761 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3762 userId); 3763 } 3764 } 3765 return null; 3766 } 3767 3768 @Override 3769 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3770 if (!sUserManager.exists(userId)) return null; 3771 flags = updateFlagsForComponent(flags, userId, component); 3772 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3773 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3774 synchronized (mPackages) { 3775 PackageParser.Provider p = mProviders.mProviders.get(component); 3776 if (DEBUG_PACKAGE_INFO) Log.v( 3777 TAG, "getProviderInfo " + component + ": " + p); 3778 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3779 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3780 if (ps == null) return null; 3781 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3782 userId); 3783 } 3784 } 3785 return null; 3786 } 3787 3788 @Override 3789 public String[] getSystemSharedLibraryNames() { 3790 Set<String> libSet; 3791 synchronized (mPackages) { 3792 libSet = mSharedLibraries.keySet(); 3793 int size = libSet.size(); 3794 if (size > 0) { 3795 String[] libs = new String[size]; 3796 libSet.toArray(libs); 3797 return libs; 3798 } 3799 } 3800 return null; 3801 } 3802 3803 @Override 3804 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3805 synchronized (mPackages) { 3806 return mServicesSystemSharedLibraryPackageName; 3807 } 3808 } 3809 3810 @Override 3811 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3812 synchronized (mPackages) { 3813 return mSharedSystemSharedLibraryPackageName; 3814 } 3815 } 3816 3817 @Override 3818 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3819 synchronized (mPackages) { 3820 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3821 3822 final FeatureInfo fi = new FeatureInfo(); 3823 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3824 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3825 res.add(fi); 3826 3827 return new ParceledListSlice<>(res); 3828 } 3829 } 3830 3831 @Override 3832 public boolean hasSystemFeature(String name, int version) { 3833 synchronized (mPackages) { 3834 final FeatureInfo feat = mAvailableFeatures.get(name); 3835 if (feat == null) { 3836 return false; 3837 } else { 3838 return feat.version >= version; 3839 } 3840 } 3841 } 3842 3843 @Override 3844 public int checkPermission(String permName, String pkgName, int userId) { 3845 if (!sUserManager.exists(userId)) { 3846 return PackageManager.PERMISSION_DENIED; 3847 } 3848 3849 synchronized (mPackages) { 3850 final PackageParser.Package p = mPackages.get(pkgName); 3851 if (p != null && p.mExtras != null) { 3852 final PackageSetting ps = (PackageSetting) p.mExtras; 3853 final PermissionsState permissionsState = ps.getPermissionsState(); 3854 if (permissionsState.hasPermission(permName, userId)) { 3855 return PackageManager.PERMISSION_GRANTED; 3856 } 3857 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3858 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3859 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3860 return PackageManager.PERMISSION_GRANTED; 3861 } 3862 } 3863 } 3864 3865 return PackageManager.PERMISSION_DENIED; 3866 } 3867 3868 @Override 3869 public int checkUidPermission(String permName, int uid) { 3870 final int userId = UserHandle.getUserId(uid); 3871 3872 if (!sUserManager.exists(userId)) { 3873 return PackageManager.PERMISSION_DENIED; 3874 } 3875 3876 synchronized (mPackages) { 3877 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3878 if (obj != null) { 3879 final SettingBase ps = (SettingBase) obj; 3880 final PermissionsState permissionsState = ps.getPermissionsState(); 3881 if (permissionsState.hasPermission(permName, userId)) { 3882 return PackageManager.PERMISSION_GRANTED; 3883 } 3884 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3885 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3886 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3887 return PackageManager.PERMISSION_GRANTED; 3888 } 3889 } else { 3890 ArraySet<String> perms = mSystemPermissions.get(uid); 3891 if (perms != null) { 3892 if (perms.contains(permName)) { 3893 return PackageManager.PERMISSION_GRANTED; 3894 } 3895 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3896 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3897 return PackageManager.PERMISSION_GRANTED; 3898 } 3899 } 3900 } 3901 } 3902 3903 return PackageManager.PERMISSION_DENIED; 3904 } 3905 3906 @Override 3907 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3908 if (UserHandle.getCallingUserId() != userId) { 3909 mContext.enforceCallingPermission( 3910 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3911 "isPermissionRevokedByPolicy for user " + userId); 3912 } 3913 3914 if (checkPermission(permission, packageName, userId) 3915 == PackageManager.PERMISSION_GRANTED) { 3916 return false; 3917 } 3918 3919 final long identity = Binder.clearCallingIdentity(); 3920 try { 3921 final int flags = getPermissionFlags(permission, packageName, userId); 3922 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3923 } finally { 3924 Binder.restoreCallingIdentity(identity); 3925 } 3926 } 3927 3928 @Override 3929 public String getPermissionControllerPackageName() { 3930 synchronized (mPackages) { 3931 return mRequiredInstallerPackage; 3932 } 3933 } 3934 3935 /** 3936 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3937 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3938 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3939 * @param message the message to log on security exception 3940 */ 3941 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3942 boolean checkShell, String message) { 3943 if (userId < 0) { 3944 throw new IllegalArgumentException("Invalid userId " + userId); 3945 } 3946 if (checkShell) { 3947 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3948 } 3949 if (userId == UserHandle.getUserId(callingUid)) return; 3950 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3951 if (requireFullPermission) { 3952 mContext.enforceCallingOrSelfPermission( 3953 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3954 } else { 3955 try { 3956 mContext.enforceCallingOrSelfPermission( 3957 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3958 } catch (SecurityException se) { 3959 mContext.enforceCallingOrSelfPermission( 3960 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3961 } 3962 } 3963 } 3964 } 3965 3966 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3967 if (callingUid == Process.SHELL_UID) { 3968 if (userHandle >= 0 3969 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3970 throw new SecurityException("Shell does not have permission to access user " 3971 + userHandle); 3972 } else if (userHandle < 0) { 3973 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3974 + Debug.getCallers(3)); 3975 } 3976 } 3977 } 3978 3979 private BasePermission findPermissionTreeLP(String permName) { 3980 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3981 if (permName.startsWith(bp.name) && 3982 permName.length() > bp.name.length() && 3983 permName.charAt(bp.name.length()) == '.') { 3984 return bp; 3985 } 3986 } 3987 return null; 3988 } 3989 3990 private BasePermission checkPermissionTreeLP(String permName) { 3991 if (permName != null) { 3992 BasePermission bp = findPermissionTreeLP(permName); 3993 if (bp != null) { 3994 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3995 return bp; 3996 } 3997 throw new SecurityException("Calling uid " 3998 + Binder.getCallingUid() 3999 + " is not allowed to add to permission tree " 4000 + bp.name + " owned by uid " + bp.uid); 4001 } 4002 } 4003 throw new SecurityException("No permission tree found for " + permName); 4004 } 4005 4006 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4007 if (s1 == null) { 4008 return s2 == null; 4009 } 4010 if (s2 == null) { 4011 return false; 4012 } 4013 if (s1.getClass() != s2.getClass()) { 4014 return false; 4015 } 4016 return s1.equals(s2); 4017 } 4018 4019 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4020 if (pi1.icon != pi2.icon) return false; 4021 if (pi1.logo != pi2.logo) return false; 4022 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4023 if (!compareStrings(pi1.name, pi2.name)) return false; 4024 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4025 // We'll take care of setting this one. 4026 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4027 // These are not currently stored in settings. 4028 //if (!compareStrings(pi1.group, pi2.group)) return false; 4029 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4030 //if (pi1.labelRes != pi2.labelRes) return false; 4031 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4032 return true; 4033 } 4034 4035 int permissionInfoFootprint(PermissionInfo info) { 4036 int size = info.name.length(); 4037 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4038 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4039 return size; 4040 } 4041 4042 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4043 int size = 0; 4044 for (BasePermission perm : mSettings.mPermissions.values()) { 4045 if (perm.uid == tree.uid) { 4046 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4047 } 4048 } 4049 return size; 4050 } 4051 4052 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4053 // We calculate the max size of permissions defined by this uid and throw 4054 // if that plus the size of 'info' would exceed our stated maximum. 4055 if (tree.uid != Process.SYSTEM_UID) { 4056 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4057 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4058 throw new SecurityException("Permission tree size cap exceeded"); 4059 } 4060 } 4061 } 4062 4063 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4064 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4065 throw new SecurityException("Label must be specified in permission"); 4066 } 4067 BasePermission tree = checkPermissionTreeLP(info.name); 4068 BasePermission bp = mSettings.mPermissions.get(info.name); 4069 boolean added = bp == null; 4070 boolean changed = true; 4071 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4072 if (added) { 4073 enforcePermissionCapLocked(info, tree); 4074 bp = new BasePermission(info.name, tree.sourcePackage, 4075 BasePermission.TYPE_DYNAMIC); 4076 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4077 throw new SecurityException( 4078 "Not allowed to modify non-dynamic permission " 4079 + info.name); 4080 } else { 4081 if (bp.protectionLevel == fixedLevel 4082 && bp.perm.owner.equals(tree.perm.owner) 4083 && bp.uid == tree.uid 4084 && comparePermissionInfos(bp.perm.info, info)) { 4085 changed = false; 4086 } 4087 } 4088 bp.protectionLevel = fixedLevel; 4089 info = new PermissionInfo(info); 4090 info.protectionLevel = fixedLevel; 4091 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4092 bp.perm.info.packageName = tree.perm.info.packageName; 4093 bp.uid = tree.uid; 4094 if (added) { 4095 mSettings.mPermissions.put(info.name, bp); 4096 } 4097 if (changed) { 4098 if (!async) { 4099 mSettings.writeLPr(); 4100 } else { 4101 scheduleWriteSettingsLocked(); 4102 } 4103 } 4104 return added; 4105 } 4106 4107 @Override 4108 public boolean addPermission(PermissionInfo info) { 4109 synchronized (mPackages) { 4110 return addPermissionLocked(info, false); 4111 } 4112 } 4113 4114 @Override 4115 public boolean addPermissionAsync(PermissionInfo info) { 4116 synchronized (mPackages) { 4117 return addPermissionLocked(info, true); 4118 } 4119 } 4120 4121 @Override 4122 public void removePermission(String name) { 4123 synchronized (mPackages) { 4124 checkPermissionTreeLP(name); 4125 BasePermission bp = mSettings.mPermissions.get(name); 4126 if (bp != null) { 4127 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4128 throw new SecurityException( 4129 "Not allowed to modify non-dynamic permission " 4130 + name); 4131 } 4132 mSettings.mPermissions.remove(name); 4133 mSettings.writeLPr(); 4134 } 4135 } 4136 } 4137 4138 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4139 BasePermission bp) { 4140 int index = pkg.requestedPermissions.indexOf(bp.name); 4141 if (index == -1) { 4142 throw new SecurityException("Package " + pkg.packageName 4143 + " has not requested permission " + bp.name); 4144 } 4145 if (!bp.isRuntime() && !bp.isDevelopment()) { 4146 throw new SecurityException("Permission " + bp.name 4147 + " is not a changeable permission type"); 4148 } 4149 } 4150 4151 @Override 4152 public void grantRuntimePermission(String packageName, String name, final int userId) { 4153 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4154 } 4155 4156 private void grantRuntimePermission(String packageName, String name, final int userId, 4157 boolean overridePolicy) { 4158 if (!sUserManager.exists(userId)) { 4159 Log.e(TAG, "No such user:" + userId); 4160 return; 4161 } 4162 4163 mContext.enforceCallingOrSelfPermission( 4164 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4165 "grantRuntimePermission"); 4166 4167 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4168 true /* requireFullPermission */, true /* checkShell */, 4169 "grantRuntimePermission"); 4170 4171 final int uid; 4172 final SettingBase sb; 4173 4174 synchronized (mPackages) { 4175 final PackageParser.Package pkg = mPackages.get(packageName); 4176 if (pkg == null) { 4177 throw new IllegalArgumentException("Unknown package: " + packageName); 4178 } 4179 4180 final BasePermission bp = mSettings.mPermissions.get(name); 4181 if (bp == null) { 4182 throw new IllegalArgumentException("Unknown permission: " + name); 4183 } 4184 4185 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4186 4187 // If a permission review is required for legacy apps we represent 4188 // their permissions as always granted runtime ones since we need 4189 // to keep the review required permission flag per user while an 4190 // install permission's state is shared across all users. 4191 if (mPermissionReviewRequired 4192 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4193 && bp.isRuntime()) { 4194 return; 4195 } 4196 4197 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4198 sb = (SettingBase) pkg.mExtras; 4199 if (sb == null) { 4200 throw new IllegalArgumentException("Unknown package: " + packageName); 4201 } 4202 4203 final PermissionsState permissionsState = sb.getPermissionsState(); 4204 4205 final int flags = permissionsState.getPermissionFlags(name, userId); 4206 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4207 throw new SecurityException("Cannot grant system fixed permission " 4208 + name + " for package " + packageName); 4209 } 4210 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4211 throw new SecurityException("Cannot grant policy fixed permission " 4212 + name + " for package " + packageName); 4213 } 4214 4215 if (bp.isDevelopment()) { 4216 // Development permissions must be handled specially, since they are not 4217 // normal runtime permissions. For now they apply to all users. 4218 if (permissionsState.grantInstallPermission(bp) != 4219 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4220 scheduleWriteSettingsLocked(); 4221 } 4222 return; 4223 } 4224 4225 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 4226 throw new SecurityException("Cannot grant non-ephemeral permission" 4227 + name + " for package " + packageName); 4228 } 4229 4230 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4231 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4232 return; 4233 } 4234 4235 final int result = permissionsState.grantRuntimePermission(bp, userId); 4236 switch (result) { 4237 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4238 return; 4239 } 4240 4241 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4242 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4243 mHandler.post(new Runnable() { 4244 @Override 4245 public void run() { 4246 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4247 } 4248 }); 4249 } 4250 break; 4251 } 4252 4253 if (bp.isRuntime()) { 4254 logPermissionGranted(mContext, name, packageName); 4255 } 4256 4257 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4258 4259 // Not critical if that is lost - app has to request again. 4260 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4261 } 4262 4263 // Only need to do this if user is initialized. Otherwise it's a new user 4264 // and there are no processes running as the user yet and there's no need 4265 // to make an expensive call to remount processes for the changed permissions. 4266 if (READ_EXTERNAL_STORAGE.equals(name) 4267 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4268 final long token = Binder.clearCallingIdentity(); 4269 try { 4270 if (sUserManager.isInitialized(userId)) { 4271 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4272 StorageManagerInternal.class); 4273 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4274 } 4275 } finally { 4276 Binder.restoreCallingIdentity(token); 4277 } 4278 } 4279 } 4280 4281 @Override 4282 public void revokeRuntimePermission(String packageName, String name, int userId) { 4283 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4284 } 4285 4286 private void revokeRuntimePermission(String packageName, String name, int userId, 4287 boolean overridePolicy) { 4288 if (!sUserManager.exists(userId)) { 4289 Log.e(TAG, "No such user:" + userId); 4290 return; 4291 } 4292 4293 mContext.enforceCallingOrSelfPermission( 4294 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4295 "revokeRuntimePermission"); 4296 4297 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4298 true /* requireFullPermission */, true /* checkShell */, 4299 "revokeRuntimePermission"); 4300 4301 final int appId; 4302 4303 synchronized (mPackages) { 4304 final PackageParser.Package pkg = mPackages.get(packageName); 4305 if (pkg == null) { 4306 throw new IllegalArgumentException("Unknown package: " + packageName); 4307 } 4308 4309 final BasePermission bp = mSettings.mPermissions.get(name); 4310 if (bp == null) { 4311 throw new IllegalArgumentException("Unknown permission: " + name); 4312 } 4313 4314 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4315 4316 // If a permission review is required for legacy apps we represent 4317 // their permissions as always granted runtime ones since we need 4318 // to keep the review required permission flag per user while an 4319 // install permission's state is shared across all users. 4320 if (mPermissionReviewRequired 4321 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4322 && bp.isRuntime()) { 4323 return; 4324 } 4325 4326 SettingBase sb = (SettingBase) pkg.mExtras; 4327 if (sb == null) { 4328 throw new IllegalArgumentException("Unknown package: " + packageName); 4329 } 4330 4331 final PermissionsState permissionsState = sb.getPermissionsState(); 4332 4333 final int flags = permissionsState.getPermissionFlags(name, userId); 4334 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4335 throw new SecurityException("Cannot revoke system fixed permission " 4336 + name + " for package " + packageName); 4337 } 4338 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4339 throw new SecurityException("Cannot revoke policy fixed permission " 4340 + name + " for package " + packageName); 4341 } 4342 4343 if (bp.isDevelopment()) { 4344 // Development permissions must be handled specially, since they are not 4345 // normal runtime permissions. For now they apply to all users. 4346 if (permissionsState.revokeInstallPermission(bp) != 4347 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4348 scheduleWriteSettingsLocked(); 4349 } 4350 return; 4351 } 4352 4353 if (permissionsState.revokeRuntimePermission(bp, userId) == 4354 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4355 return; 4356 } 4357 4358 if (bp.isRuntime()) { 4359 logPermissionRevoked(mContext, name, packageName); 4360 } 4361 4362 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4363 4364 // Critical, after this call app should never have the permission. 4365 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4366 4367 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4368 } 4369 4370 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4371 } 4372 4373 /** 4374 * Get the first event id for the permission. 4375 * 4376 * <p>There are four events for each permission: <ul> 4377 * <li>Request permission: first id + 0</li> 4378 * <li>Grant permission: first id + 1</li> 4379 * <li>Request for permission denied: first id + 2</li> 4380 * <li>Revoke permission: first id + 3</li> 4381 * </ul></p> 4382 * 4383 * @param name name of the permission 4384 * 4385 * @return The first event id for the permission 4386 */ 4387 private static int getBaseEventId(@NonNull String name) { 4388 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4389 4390 if (eventIdIndex == -1) { 4391 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4392 || "user".equals(Build.TYPE)) { 4393 Log.i(TAG, "Unknown permission " + name); 4394 4395 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4396 } else { 4397 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4398 // 4399 // Also update 4400 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4401 // - metrics_constants.proto 4402 throw new IllegalStateException("Unknown permission " + name); 4403 } 4404 } 4405 4406 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4407 } 4408 4409 /** 4410 * Log that a permission was revoked. 4411 * 4412 * @param context Context of the caller 4413 * @param name name of the permission 4414 * @param packageName package permission if for 4415 */ 4416 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4417 @NonNull String packageName) { 4418 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4419 } 4420 4421 /** 4422 * Log that a permission request was granted. 4423 * 4424 * @param context Context of the caller 4425 * @param name name of the permission 4426 * @param packageName package permission if for 4427 */ 4428 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4429 @NonNull String packageName) { 4430 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4431 } 4432 4433 @Override 4434 public void resetRuntimePermissions() { 4435 mContext.enforceCallingOrSelfPermission( 4436 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4437 "revokeRuntimePermission"); 4438 4439 int callingUid = Binder.getCallingUid(); 4440 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4441 mContext.enforceCallingOrSelfPermission( 4442 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4443 "resetRuntimePermissions"); 4444 } 4445 4446 synchronized (mPackages) { 4447 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4448 for (int userId : UserManagerService.getInstance().getUserIds()) { 4449 final int packageCount = mPackages.size(); 4450 for (int i = 0; i < packageCount; i++) { 4451 PackageParser.Package pkg = mPackages.valueAt(i); 4452 if (!(pkg.mExtras instanceof PackageSetting)) { 4453 continue; 4454 } 4455 PackageSetting ps = (PackageSetting) pkg.mExtras; 4456 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4457 } 4458 } 4459 } 4460 } 4461 4462 @Override 4463 public int getPermissionFlags(String name, String packageName, int userId) { 4464 if (!sUserManager.exists(userId)) { 4465 return 0; 4466 } 4467 4468 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4469 4470 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4471 true /* requireFullPermission */, false /* checkShell */, 4472 "getPermissionFlags"); 4473 4474 synchronized (mPackages) { 4475 final PackageParser.Package pkg = mPackages.get(packageName); 4476 if (pkg == null) { 4477 return 0; 4478 } 4479 4480 final BasePermission bp = mSettings.mPermissions.get(name); 4481 if (bp == null) { 4482 return 0; 4483 } 4484 4485 SettingBase sb = (SettingBase) pkg.mExtras; 4486 if (sb == null) { 4487 return 0; 4488 } 4489 4490 PermissionsState permissionsState = sb.getPermissionsState(); 4491 return permissionsState.getPermissionFlags(name, userId); 4492 } 4493 } 4494 4495 @Override 4496 public void updatePermissionFlags(String name, String packageName, int flagMask, 4497 int flagValues, int userId) { 4498 if (!sUserManager.exists(userId)) { 4499 return; 4500 } 4501 4502 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4503 4504 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4505 true /* requireFullPermission */, true /* checkShell */, 4506 "updatePermissionFlags"); 4507 4508 // Only the system can change these flags and nothing else. 4509 if (getCallingUid() != Process.SYSTEM_UID) { 4510 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4511 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4512 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4513 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4514 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4515 } 4516 4517 synchronized (mPackages) { 4518 final PackageParser.Package pkg = mPackages.get(packageName); 4519 if (pkg == null) { 4520 throw new IllegalArgumentException("Unknown package: " + packageName); 4521 } 4522 4523 final BasePermission bp = mSettings.mPermissions.get(name); 4524 if (bp == null) { 4525 throw new IllegalArgumentException("Unknown permission: " + name); 4526 } 4527 4528 SettingBase sb = (SettingBase) pkg.mExtras; 4529 if (sb == null) { 4530 throw new IllegalArgumentException("Unknown package: " + packageName); 4531 } 4532 4533 PermissionsState permissionsState = sb.getPermissionsState(); 4534 4535 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4536 4537 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4538 // Install and runtime permissions are stored in different places, 4539 // so figure out what permission changed and persist the change. 4540 if (permissionsState.getInstallPermissionState(name) != null) { 4541 scheduleWriteSettingsLocked(); 4542 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4543 || hadState) { 4544 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4545 } 4546 } 4547 } 4548 } 4549 4550 /** 4551 * Update the permission flags for all packages and runtime permissions of a user in order 4552 * to allow device or profile owner to remove POLICY_FIXED. 4553 */ 4554 @Override 4555 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4556 if (!sUserManager.exists(userId)) { 4557 return; 4558 } 4559 4560 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4561 4562 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4563 true /* requireFullPermission */, true /* checkShell */, 4564 "updatePermissionFlagsForAllApps"); 4565 4566 // Only the system can change system fixed flags. 4567 if (getCallingUid() != Process.SYSTEM_UID) { 4568 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4569 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4570 } 4571 4572 synchronized (mPackages) { 4573 boolean changed = false; 4574 final int packageCount = mPackages.size(); 4575 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4576 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4577 SettingBase sb = (SettingBase) pkg.mExtras; 4578 if (sb == null) { 4579 continue; 4580 } 4581 PermissionsState permissionsState = sb.getPermissionsState(); 4582 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4583 userId, flagMask, flagValues); 4584 } 4585 if (changed) { 4586 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4587 } 4588 } 4589 } 4590 4591 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4592 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4593 != PackageManager.PERMISSION_GRANTED 4594 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4595 != PackageManager.PERMISSION_GRANTED) { 4596 throw new SecurityException(message + " requires " 4597 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4598 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4599 } 4600 } 4601 4602 @Override 4603 public boolean shouldShowRequestPermissionRationale(String permissionName, 4604 String packageName, int userId) { 4605 if (UserHandle.getCallingUserId() != userId) { 4606 mContext.enforceCallingPermission( 4607 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4608 "canShowRequestPermissionRationale for user " + userId); 4609 } 4610 4611 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4612 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4613 return false; 4614 } 4615 4616 if (checkPermission(permissionName, packageName, userId) 4617 == PackageManager.PERMISSION_GRANTED) { 4618 return false; 4619 } 4620 4621 final int flags; 4622 4623 final long identity = Binder.clearCallingIdentity(); 4624 try { 4625 flags = getPermissionFlags(permissionName, 4626 packageName, userId); 4627 } finally { 4628 Binder.restoreCallingIdentity(identity); 4629 } 4630 4631 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4632 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4633 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4634 4635 if ((flags & fixedFlags) != 0) { 4636 return false; 4637 } 4638 4639 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4640 } 4641 4642 @Override 4643 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4644 mContext.enforceCallingOrSelfPermission( 4645 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4646 "addOnPermissionsChangeListener"); 4647 4648 synchronized (mPackages) { 4649 mOnPermissionChangeListeners.addListenerLocked(listener); 4650 } 4651 } 4652 4653 @Override 4654 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4655 synchronized (mPackages) { 4656 mOnPermissionChangeListeners.removeListenerLocked(listener); 4657 } 4658 } 4659 4660 @Override 4661 public boolean isProtectedBroadcast(String actionName) { 4662 synchronized (mPackages) { 4663 if (mProtectedBroadcasts.contains(actionName)) { 4664 return true; 4665 } else if (actionName != null) { 4666 // TODO: remove these terrible hacks 4667 if (actionName.startsWith("android.net.netmon.lingerExpired") 4668 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4669 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4670 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4671 return true; 4672 } 4673 } 4674 } 4675 return false; 4676 } 4677 4678 @Override 4679 public int checkSignatures(String pkg1, String pkg2) { 4680 synchronized (mPackages) { 4681 final PackageParser.Package p1 = mPackages.get(pkg1); 4682 final PackageParser.Package p2 = mPackages.get(pkg2); 4683 if (p1 == null || p1.mExtras == null 4684 || p2 == null || p2.mExtras == null) { 4685 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4686 } 4687 return compareSignatures(p1.mSignatures, p2.mSignatures); 4688 } 4689 } 4690 4691 @Override 4692 public int checkUidSignatures(int uid1, int uid2) { 4693 // Map to base uids. 4694 uid1 = UserHandle.getAppId(uid1); 4695 uid2 = UserHandle.getAppId(uid2); 4696 // reader 4697 synchronized (mPackages) { 4698 Signature[] s1; 4699 Signature[] s2; 4700 Object obj = mSettings.getUserIdLPr(uid1); 4701 if (obj != null) { 4702 if (obj instanceof SharedUserSetting) { 4703 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4704 } else if (obj instanceof PackageSetting) { 4705 s1 = ((PackageSetting)obj).signatures.mSignatures; 4706 } else { 4707 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4708 } 4709 } else { 4710 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4711 } 4712 obj = mSettings.getUserIdLPr(uid2); 4713 if (obj != null) { 4714 if (obj instanceof SharedUserSetting) { 4715 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4716 } else if (obj instanceof PackageSetting) { 4717 s2 = ((PackageSetting)obj).signatures.mSignatures; 4718 } else { 4719 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4720 } 4721 } else { 4722 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4723 } 4724 return compareSignatures(s1, s2); 4725 } 4726 } 4727 4728 /** 4729 * This method should typically only be used when granting or revoking 4730 * permissions, since the app may immediately restart after this call. 4731 * <p> 4732 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4733 * guard your work against the app being relaunched. 4734 */ 4735 private void killUid(int appId, int userId, String reason) { 4736 final long identity = Binder.clearCallingIdentity(); 4737 try { 4738 IActivityManager am = ActivityManager.getService(); 4739 if (am != null) { 4740 try { 4741 am.killUid(appId, userId, reason); 4742 } catch (RemoteException e) { 4743 /* ignore - same process */ 4744 } 4745 } 4746 } finally { 4747 Binder.restoreCallingIdentity(identity); 4748 } 4749 } 4750 4751 /** 4752 * Compares two sets of signatures. Returns: 4753 * <br /> 4754 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4755 * <br /> 4756 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4757 * <br /> 4758 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4759 * <br /> 4760 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4761 * <br /> 4762 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4763 */ 4764 static int compareSignatures(Signature[] s1, Signature[] s2) { 4765 if (s1 == null) { 4766 return s2 == null 4767 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4768 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4769 } 4770 4771 if (s2 == null) { 4772 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4773 } 4774 4775 if (s1.length != s2.length) { 4776 return PackageManager.SIGNATURE_NO_MATCH; 4777 } 4778 4779 // Since both signature sets are of size 1, we can compare without HashSets. 4780 if (s1.length == 1) { 4781 return s1[0].equals(s2[0]) ? 4782 PackageManager.SIGNATURE_MATCH : 4783 PackageManager.SIGNATURE_NO_MATCH; 4784 } 4785 4786 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4787 for (Signature sig : s1) { 4788 set1.add(sig); 4789 } 4790 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4791 for (Signature sig : s2) { 4792 set2.add(sig); 4793 } 4794 // Make sure s2 contains all signatures in s1. 4795 if (set1.equals(set2)) { 4796 return PackageManager.SIGNATURE_MATCH; 4797 } 4798 return PackageManager.SIGNATURE_NO_MATCH; 4799 } 4800 4801 /** 4802 * If the database version for this type of package (internal storage or 4803 * external storage) is less than the version where package signatures 4804 * were updated, return true. 4805 */ 4806 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4807 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4808 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4809 } 4810 4811 /** 4812 * Used for backward compatibility to make sure any packages with 4813 * certificate chains get upgraded to the new style. {@code existingSigs} 4814 * will be in the old format (since they were stored on disk from before the 4815 * system upgrade) and {@code scannedSigs} will be in the newer format. 4816 */ 4817 private int compareSignaturesCompat(PackageSignatures existingSigs, 4818 PackageParser.Package scannedPkg) { 4819 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4820 return PackageManager.SIGNATURE_NO_MATCH; 4821 } 4822 4823 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4824 for (Signature sig : existingSigs.mSignatures) { 4825 existingSet.add(sig); 4826 } 4827 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4828 for (Signature sig : scannedPkg.mSignatures) { 4829 try { 4830 Signature[] chainSignatures = sig.getChainSignatures(); 4831 for (Signature chainSig : chainSignatures) { 4832 scannedCompatSet.add(chainSig); 4833 } 4834 } catch (CertificateEncodingException e) { 4835 scannedCompatSet.add(sig); 4836 } 4837 } 4838 /* 4839 * Make sure the expanded scanned set contains all signatures in the 4840 * existing one. 4841 */ 4842 if (scannedCompatSet.equals(existingSet)) { 4843 // Migrate the old signatures to the new scheme. 4844 existingSigs.assignSignatures(scannedPkg.mSignatures); 4845 // The new KeySets will be re-added later in the scanning process. 4846 synchronized (mPackages) { 4847 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4848 } 4849 return PackageManager.SIGNATURE_MATCH; 4850 } 4851 return PackageManager.SIGNATURE_NO_MATCH; 4852 } 4853 4854 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4855 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4856 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4857 } 4858 4859 private int compareSignaturesRecover(PackageSignatures existingSigs, 4860 PackageParser.Package scannedPkg) { 4861 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4862 return PackageManager.SIGNATURE_NO_MATCH; 4863 } 4864 4865 String msg = null; 4866 try { 4867 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4868 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4869 + scannedPkg.packageName); 4870 return PackageManager.SIGNATURE_MATCH; 4871 } 4872 } catch (CertificateException e) { 4873 msg = e.getMessage(); 4874 } 4875 4876 logCriticalInfo(Log.INFO, 4877 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4878 return PackageManager.SIGNATURE_NO_MATCH; 4879 } 4880 4881 @Override 4882 public List<String> getAllPackages() { 4883 synchronized (mPackages) { 4884 return new ArrayList<String>(mPackages.keySet()); 4885 } 4886 } 4887 4888 @Override 4889 public String[] getPackagesForUid(int uid) { 4890 final int userId = UserHandle.getUserId(uid); 4891 uid = UserHandle.getAppId(uid); 4892 // reader 4893 synchronized (mPackages) { 4894 Object obj = mSettings.getUserIdLPr(uid); 4895 if (obj instanceof SharedUserSetting) { 4896 final SharedUserSetting sus = (SharedUserSetting) obj; 4897 final int N = sus.packages.size(); 4898 String[] res = new String[N]; 4899 final Iterator<PackageSetting> it = sus.packages.iterator(); 4900 int i = 0; 4901 while (it.hasNext()) { 4902 PackageSetting ps = it.next(); 4903 if (ps.getInstalled(userId)) { 4904 res[i++] = ps.name; 4905 } else { 4906 res = ArrayUtils.removeElement(String.class, res, res[i]); 4907 } 4908 } 4909 return res; 4910 } else if (obj instanceof PackageSetting) { 4911 final PackageSetting ps = (PackageSetting) obj; 4912 return new String[] { ps.name }; 4913 } 4914 } 4915 return null; 4916 } 4917 4918 @Override 4919 public String getNameForUid(int uid) { 4920 // reader 4921 synchronized (mPackages) { 4922 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4923 if (obj instanceof SharedUserSetting) { 4924 final SharedUserSetting sus = (SharedUserSetting) obj; 4925 return sus.name + ":" + sus.userId; 4926 } else if (obj instanceof PackageSetting) { 4927 final PackageSetting ps = (PackageSetting) obj; 4928 return ps.name; 4929 } 4930 } 4931 return null; 4932 } 4933 4934 @Override 4935 public int getUidForSharedUser(String sharedUserName) { 4936 if(sharedUserName == null) { 4937 return -1; 4938 } 4939 // reader 4940 synchronized (mPackages) { 4941 SharedUserSetting suid; 4942 try { 4943 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4944 if (suid != null) { 4945 return suid.userId; 4946 } 4947 } catch (PackageManagerException ignore) { 4948 // can't happen, but, still need to catch it 4949 } 4950 return -1; 4951 } 4952 } 4953 4954 @Override 4955 public int getFlagsForUid(int uid) { 4956 synchronized (mPackages) { 4957 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4958 if (obj instanceof SharedUserSetting) { 4959 final SharedUserSetting sus = (SharedUserSetting) obj; 4960 return sus.pkgFlags; 4961 } else if (obj instanceof PackageSetting) { 4962 final PackageSetting ps = (PackageSetting) obj; 4963 return ps.pkgFlags; 4964 } 4965 } 4966 return 0; 4967 } 4968 4969 @Override 4970 public int getPrivateFlagsForUid(int uid) { 4971 synchronized (mPackages) { 4972 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4973 if (obj instanceof SharedUserSetting) { 4974 final SharedUserSetting sus = (SharedUserSetting) obj; 4975 return sus.pkgPrivateFlags; 4976 } else if (obj instanceof PackageSetting) { 4977 final PackageSetting ps = (PackageSetting) obj; 4978 return ps.pkgPrivateFlags; 4979 } 4980 } 4981 return 0; 4982 } 4983 4984 @Override 4985 public boolean isUidPrivileged(int uid) { 4986 uid = UserHandle.getAppId(uid); 4987 // reader 4988 synchronized (mPackages) { 4989 Object obj = mSettings.getUserIdLPr(uid); 4990 if (obj instanceof SharedUserSetting) { 4991 final SharedUserSetting sus = (SharedUserSetting) obj; 4992 final Iterator<PackageSetting> it = sus.packages.iterator(); 4993 while (it.hasNext()) { 4994 if (it.next().isPrivileged()) { 4995 return true; 4996 } 4997 } 4998 } else if (obj instanceof PackageSetting) { 4999 final PackageSetting ps = (PackageSetting) obj; 5000 return ps.isPrivileged(); 5001 } 5002 } 5003 return false; 5004 } 5005 5006 @Override 5007 public String[] getAppOpPermissionPackages(String permissionName) { 5008 synchronized (mPackages) { 5009 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5010 if (pkgs == null) { 5011 return null; 5012 } 5013 return pkgs.toArray(new String[pkgs.size()]); 5014 } 5015 } 5016 5017 @Override 5018 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5019 int flags, int userId) { 5020 try { 5021 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5022 5023 if (!sUserManager.exists(userId)) return null; 5024 flags = updateFlagsForResolve(flags, userId, intent); 5025 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5026 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5027 5028 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5029 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5030 flags, userId); 5031 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5032 5033 final ResolveInfo bestChoice = 5034 chooseBestActivity(intent, resolvedType, flags, query, userId); 5035 return bestChoice; 5036 } finally { 5037 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5038 } 5039 } 5040 5041 @Override 5042 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5043 IntentFilter filter, int match, ComponentName activity) { 5044 final int userId = UserHandle.getCallingUserId(); 5045 if (DEBUG_PREFERRED) { 5046 Log.v(TAG, "setLastChosenActivity intent=" + intent 5047 + " resolvedType=" + resolvedType 5048 + " flags=" + flags 5049 + " filter=" + filter 5050 + " match=" + match 5051 + " activity=" + activity); 5052 filter.dump(new PrintStreamPrinter(System.out), " "); 5053 } 5054 intent.setComponent(null); 5055 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5056 userId); 5057 // Find any earlier preferred or last chosen entries and nuke them 5058 findPreferredActivity(intent, resolvedType, 5059 flags, query, 0, false, true, false, userId); 5060 // Add the new activity as the last chosen for this filter 5061 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5062 "Setting last chosen"); 5063 } 5064 5065 @Override 5066 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5067 final int userId = UserHandle.getCallingUserId(); 5068 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5069 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5070 userId); 5071 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5072 false, false, false, userId); 5073 } 5074 5075 private boolean isEphemeralDisabled() { 5076 // ephemeral apps have been disabled across the board 5077 if (DISABLE_EPHEMERAL_APPS) { 5078 return true; 5079 } 5080 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5081 if (!mSystemReady) { 5082 return true; 5083 } 5084 // we can't get a content resolver until the system is ready; these checks must happen last 5085 final ContentResolver resolver = mContext.getContentResolver(); 5086 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5087 return true; 5088 } 5089 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5090 } 5091 5092 private boolean isEphemeralAllowed( 5093 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5094 boolean skipPackageCheck) { 5095 // Short circuit and return early if possible. 5096 if (isEphemeralDisabled()) { 5097 return false; 5098 } 5099 final int callingUser = UserHandle.getCallingUserId(); 5100 if (callingUser != UserHandle.USER_SYSTEM) { 5101 return false; 5102 } 5103 if (mEphemeralResolverConnection == null) { 5104 return false; 5105 } 5106 if (mEphemeralInstallerComponent == null) { 5107 return false; 5108 } 5109 if (intent.getComponent() != null) { 5110 return false; 5111 } 5112 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5113 return false; 5114 } 5115 if (!skipPackageCheck && intent.getPackage() != null) { 5116 return false; 5117 } 5118 final boolean isWebUri = hasWebURI(intent); 5119 if (!isWebUri || intent.getData().getHost() == null) { 5120 return false; 5121 } 5122 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5123 synchronized (mPackages) { 5124 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5125 for (int n = 0; n < count; n++) { 5126 ResolveInfo info = resolvedActivities.get(n); 5127 String packageName = info.activityInfo.packageName; 5128 PackageSetting ps = mSettings.mPackages.get(packageName); 5129 if (ps != null) { 5130 // Try to get the status from User settings first 5131 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5132 int status = (int) (packedStatus >> 32); 5133 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5134 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5135 if (DEBUG_EPHEMERAL) { 5136 Slog.v(TAG, "DENY ephemeral apps;" 5137 + " pkg: " + packageName + ", status: " + status); 5138 } 5139 return false; 5140 } 5141 } 5142 } 5143 } 5144 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5145 return true; 5146 } 5147 5148 private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 5149 Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage, 5150 int userId) { 5151 final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO, 5152 new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent, 5153 callingPackage, userId)); 5154 mHandler.sendMessage(msg); 5155 } 5156 5157 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5158 int flags, List<ResolveInfo> query, int userId) { 5159 if (query != null) { 5160 final int N = query.size(); 5161 if (N == 1) { 5162 return query.get(0); 5163 } else if (N > 1) { 5164 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5165 // If there is more than one activity with the same priority, 5166 // then let the user decide between them. 5167 ResolveInfo r0 = query.get(0); 5168 ResolveInfo r1 = query.get(1); 5169 if (DEBUG_INTENT_MATCHING || debug) { 5170 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5171 + r1.activityInfo.name + "=" + r1.priority); 5172 } 5173 // If the first activity has a higher priority, or a different 5174 // default, then it is always desirable to pick it. 5175 if (r0.priority != r1.priority 5176 || r0.preferredOrder != r1.preferredOrder 5177 || r0.isDefault != r1.isDefault) { 5178 return query.get(0); 5179 } 5180 // If we have saved a preference for a preferred activity for 5181 // this Intent, use that. 5182 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5183 flags, query, r0.priority, true, false, debug, userId); 5184 if (ri != null) { 5185 return ri; 5186 } 5187 ri = new ResolveInfo(mResolveInfo); 5188 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5189 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5190 // If all of the options come from the same package, show the application's 5191 // label and icon instead of the generic resolver's. 5192 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5193 // and then throw away the ResolveInfo itself, meaning that the caller loses 5194 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5195 // a fallback for this case; we only set the target package's resources on 5196 // the ResolveInfo, not the ActivityInfo. 5197 final String intentPackage = intent.getPackage(); 5198 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5199 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5200 ri.resolvePackageName = intentPackage; 5201 if (userNeedsBadging(userId)) { 5202 ri.noResourceId = true; 5203 } else { 5204 ri.icon = appi.icon; 5205 } 5206 ri.iconResourceId = appi.icon; 5207 ri.labelRes = appi.labelRes; 5208 } 5209 ri.activityInfo.applicationInfo = new ApplicationInfo( 5210 ri.activityInfo.applicationInfo); 5211 if (userId != 0) { 5212 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5213 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5214 } 5215 // Make sure that the resolver is displayable in car mode 5216 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5217 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5218 return ri; 5219 } 5220 } 5221 return null; 5222 } 5223 5224 /** 5225 * Return true if the given list is not empty and all of its contents have 5226 * an activityInfo with the given package name. 5227 */ 5228 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5229 if (ArrayUtils.isEmpty(list)) { 5230 return false; 5231 } 5232 for (int i = 0, N = list.size(); i < N; i++) { 5233 final ResolveInfo ri = list.get(i); 5234 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5235 if (ai == null || !packageName.equals(ai.packageName)) { 5236 return false; 5237 } 5238 } 5239 return true; 5240 } 5241 5242 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5243 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5244 final int N = query.size(); 5245 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5246 .get(userId); 5247 // Get the list of persistent preferred activities that handle the intent 5248 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5249 List<PersistentPreferredActivity> pprefs = ppir != null 5250 ? ppir.queryIntent(intent, resolvedType, 5251 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5252 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5253 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5254 : null; 5255 if (pprefs != null && pprefs.size() > 0) { 5256 final int M = pprefs.size(); 5257 for (int i=0; i<M; i++) { 5258 final PersistentPreferredActivity ppa = pprefs.get(i); 5259 if (DEBUG_PREFERRED || debug) { 5260 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5261 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5262 + "\n component=" + ppa.mComponent); 5263 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5264 } 5265 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5266 flags | MATCH_DISABLED_COMPONENTS, userId); 5267 if (DEBUG_PREFERRED || debug) { 5268 Slog.v(TAG, "Found persistent preferred activity:"); 5269 if (ai != null) { 5270 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5271 } else { 5272 Slog.v(TAG, " null"); 5273 } 5274 } 5275 if (ai == null) { 5276 // This previously registered persistent preferred activity 5277 // component is no longer known. Ignore it and do NOT remove it. 5278 continue; 5279 } 5280 for (int j=0; j<N; j++) { 5281 final ResolveInfo ri = query.get(j); 5282 if (!ri.activityInfo.applicationInfo.packageName 5283 .equals(ai.applicationInfo.packageName)) { 5284 continue; 5285 } 5286 if (!ri.activityInfo.name.equals(ai.name)) { 5287 continue; 5288 } 5289 // Found a persistent preference that can handle the intent. 5290 if (DEBUG_PREFERRED || debug) { 5291 Slog.v(TAG, "Returning persistent preferred activity: " + 5292 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5293 } 5294 return ri; 5295 } 5296 } 5297 } 5298 return null; 5299 } 5300 5301 // TODO: handle preferred activities missing while user has amnesia 5302 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5303 List<ResolveInfo> query, int priority, boolean always, 5304 boolean removeMatches, boolean debug, int userId) { 5305 if (!sUserManager.exists(userId)) return null; 5306 flags = updateFlagsForResolve(flags, userId, intent); 5307 // writer 5308 synchronized (mPackages) { 5309 if (intent.getSelector() != null) { 5310 intent = intent.getSelector(); 5311 } 5312 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5313 5314 // Try to find a matching persistent preferred activity. 5315 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5316 debug, userId); 5317 5318 // If a persistent preferred activity matched, use it. 5319 if (pri != null) { 5320 return pri; 5321 } 5322 5323 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5324 // Get the list of preferred activities that handle the intent 5325 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5326 List<PreferredActivity> prefs = pir != null 5327 ? pir.queryIntent(intent, resolvedType, 5328 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5329 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5330 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5331 : null; 5332 if (prefs != null && prefs.size() > 0) { 5333 boolean changed = false; 5334 try { 5335 // First figure out how good the original match set is. 5336 // We will only allow preferred activities that came 5337 // from the same match quality. 5338 int match = 0; 5339 5340 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5341 5342 final int N = query.size(); 5343 for (int j=0; j<N; j++) { 5344 final ResolveInfo ri = query.get(j); 5345 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5346 + ": 0x" + Integer.toHexString(match)); 5347 if (ri.match > match) { 5348 match = ri.match; 5349 } 5350 } 5351 5352 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5353 + Integer.toHexString(match)); 5354 5355 match &= IntentFilter.MATCH_CATEGORY_MASK; 5356 final int M = prefs.size(); 5357 for (int i=0; i<M; i++) { 5358 final PreferredActivity pa = prefs.get(i); 5359 if (DEBUG_PREFERRED || debug) { 5360 Slog.v(TAG, "Checking PreferredActivity ds=" 5361 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5362 + "\n component=" + pa.mPref.mComponent); 5363 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5364 } 5365 if (pa.mPref.mMatch != match) { 5366 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5367 + Integer.toHexString(pa.mPref.mMatch)); 5368 continue; 5369 } 5370 // If it's not an "always" type preferred activity and that's what we're 5371 // looking for, skip it. 5372 if (always && !pa.mPref.mAlways) { 5373 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5374 continue; 5375 } 5376 final ActivityInfo ai = getActivityInfo( 5377 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5378 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5379 userId); 5380 if (DEBUG_PREFERRED || debug) { 5381 Slog.v(TAG, "Found preferred activity:"); 5382 if (ai != null) { 5383 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5384 } else { 5385 Slog.v(TAG, " null"); 5386 } 5387 } 5388 if (ai == null) { 5389 // This previously registered preferred activity 5390 // component is no longer known. Most likely an update 5391 // to the app was installed and in the new version this 5392 // component no longer exists. Clean it up by removing 5393 // it from the preferred activities list, and skip it. 5394 Slog.w(TAG, "Removing dangling preferred activity: " 5395 + pa.mPref.mComponent); 5396 pir.removeFilter(pa); 5397 changed = true; 5398 continue; 5399 } 5400 for (int j=0; j<N; j++) { 5401 final ResolveInfo ri = query.get(j); 5402 if (!ri.activityInfo.applicationInfo.packageName 5403 .equals(ai.applicationInfo.packageName)) { 5404 continue; 5405 } 5406 if (!ri.activityInfo.name.equals(ai.name)) { 5407 continue; 5408 } 5409 5410 if (removeMatches) { 5411 pir.removeFilter(pa); 5412 changed = true; 5413 if (DEBUG_PREFERRED) { 5414 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5415 } 5416 break; 5417 } 5418 5419 // Okay we found a previously set preferred or last chosen app. 5420 // If the result set is different from when this 5421 // was created, we need to clear it and re-ask the 5422 // user their preference, if we're looking for an "always" type entry. 5423 if (always && !pa.mPref.sameSet(query)) { 5424 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5425 + intent + " type " + resolvedType); 5426 if (DEBUG_PREFERRED) { 5427 Slog.v(TAG, "Removing preferred activity since set changed " 5428 + pa.mPref.mComponent); 5429 } 5430 pir.removeFilter(pa); 5431 // Re-add the filter as a "last chosen" entry (!always) 5432 PreferredActivity lastChosen = new PreferredActivity( 5433 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5434 pir.addFilter(lastChosen); 5435 changed = true; 5436 return null; 5437 } 5438 5439 // Yay! Either the set matched or we're looking for the last chosen 5440 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5441 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5442 return ri; 5443 } 5444 } 5445 } finally { 5446 if (changed) { 5447 if (DEBUG_PREFERRED) { 5448 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5449 } 5450 scheduleWritePackageRestrictionsLocked(userId); 5451 } 5452 } 5453 } 5454 } 5455 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5456 return null; 5457 } 5458 5459 /* 5460 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5461 */ 5462 @Override 5463 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5464 int targetUserId) { 5465 mContext.enforceCallingOrSelfPermission( 5466 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5467 List<CrossProfileIntentFilter> matches = 5468 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5469 if (matches != null) { 5470 int size = matches.size(); 5471 for (int i = 0; i < size; i++) { 5472 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5473 } 5474 } 5475 if (hasWebURI(intent)) { 5476 // cross-profile app linking works only towards the parent. 5477 final UserInfo parent = getProfileParent(sourceUserId); 5478 synchronized(mPackages) { 5479 int flags = updateFlagsForResolve(0, parent.id, intent); 5480 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5481 intent, resolvedType, flags, sourceUserId, parent.id); 5482 return xpDomainInfo != null; 5483 } 5484 } 5485 return false; 5486 } 5487 5488 private UserInfo getProfileParent(int userId) { 5489 final long identity = Binder.clearCallingIdentity(); 5490 try { 5491 return sUserManager.getProfileParent(userId); 5492 } finally { 5493 Binder.restoreCallingIdentity(identity); 5494 } 5495 } 5496 5497 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5498 String resolvedType, int userId) { 5499 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5500 if (resolver != null) { 5501 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, 5502 false /*visibleToEphemeral*/, false /*isEphemeral*/, userId); 5503 } 5504 return null; 5505 } 5506 5507 @Override 5508 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5509 String resolvedType, int flags, int userId) { 5510 try { 5511 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5512 5513 return new ParceledListSlice<>( 5514 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5515 } finally { 5516 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5517 } 5518 } 5519 5520 /** 5521 * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't 5522 * ephemeral, returns {@code null}. 5523 */ 5524 private String getEphemeralPackageName(int callingUid) { 5525 final int appId = UserHandle.getAppId(callingUid); 5526 synchronized (mPackages) { 5527 final Object obj = mSettings.getUserIdLPr(appId); 5528 if (obj instanceof PackageSetting) { 5529 final PackageSetting ps = (PackageSetting) obj; 5530 return ps.pkg.applicationInfo.isEphemeralApp() ? ps.pkg.packageName : null; 5531 } 5532 } 5533 return null; 5534 } 5535 5536 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5537 String resolvedType, int flags, int userId) { 5538 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5539 final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid()); 5540 flags = updateFlagsForResolve(flags, userId, intent); 5541 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5542 false /* requireFullPermission */, false /* checkShell */, 5543 "query intent activities"); 5544 ComponentName comp = intent.getComponent(); 5545 if (comp == null) { 5546 if (intent.getSelector() != null) { 5547 intent = intent.getSelector(); 5548 comp = intent.getComponent(); 5549 } 5550 } 5551 5552 if (comp != null) { 5553 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5554 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5555 if (ai != null) { 5556 // When specifying an explicit component, we prevent the activity from being 5557 // used when either 1) the calling package is normal and the activity is within 5558 // an ephemeral application or 2) the calling package is ephemeral and the 5559 // activity is not visible to ephemeral applications. 5560 boolean matchEphemeral = 5561 (flags & PackageManager.MATCH_EPHEMERAL) != 0; 5562 boolean ephemeralVisibleOnly = 5563 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 5564 boolean blockResolution = 5565 (!matchEphemeral && ephemeralPkgName == null 5566 && (ai.applicationInfo.privateFlags 5567 & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0) 5568 || (ephemeralVisibleOnly && ephemeralPkgName != null 5569 && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0); 5570 if (!blockResolution) { 5571 final ResolveInfo ri = new ResolveInfo(); 5572 ri.activityInfo = ai; 5573 list.add(ri); 5574 } 5575 } 5576 return list; 5577 } 5578 5579 // reader 5580 boolean sortResult = false; 5581 boolean addEphemeral = false; 5582 List<ResolveInfo> result; 5583 final String pkgName = intent.getPackage(); 5584 synchronized (mPackages) { 5585 if (pkgName == null) { 5586 List<CrossProfileIntentFilter> matchingFilters = 5587 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5588 // Check for results that need to skip the current profile. 5589 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5590 resolvedType, flags, userId); 5591 if (xpResolveInfo != null) { 5592 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5593 xpResult.add(xpResolveInfo); 5594 return filterForEphemeral( 5595 filterIfNotSystemUser(xpResult, userId), ephemeralPkgName); 5596 } 5597 5598 // Check for results in the current profile. 5599 result = filterIfNotSystemUser(mActivities.queryIntent( 5600 intent, resolvedType, flags, userId), userId); 5601 addEphemeral = 5602 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5603 5604 // Check for cross profile results. 5605 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5606 xpResolveInfo = queryCrossProfileIntents( 5607 matchingFilters, intent, resolvedType, flags, userId, 5608 hasNonNegativePriorityResult); 5609 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5610 boolean isVisibleToUser = filterIfNotSystemUser( 5611 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5612 if (isVisibleToUser) { 5613 result.add(xpResolveInfo); 5614 sortResult = true; 5615 } 5616 } 5617 if (hasWebURI(intent)) { 5618 CrossProfileDomainInfo xpDomainInfo = null; 5619 final UserInfo parent = getProfileParent(userId); 5620 if (parent != null) { 5621 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5622 flags, userId, parent.id); 5623 } 5624 if (xpDomainInfo != null) { 5625 if (xpResolveInfo != null) { 5626 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5627 // in the result. 5628 result.remove(xpResolveInfo); 5629 } 5630 if (result.size() == 0 && !addEphemeral) { 5631 // No result in current profile, but found candidate in parent user. 5632 // And we are not going to add emphemeral app, so we can return the 5633 // result straight away. 5634 result.add(xpDomainInfo.resolveInfo); 5635 return filterForEphemeral(result, ephemeralPkgName); 5636 } 5637 } else if (result.size() <= 1 && !addEphemeral) { 5638 // No result in parent user and <= 1 result in current profile, and we 5639 // are not going to add emphemeral app, so we can return the result without 5640 // further processing. 5641 return filterForEphemeral(result, ephemeralPkgName); 5642 } 5643 // We have more than one candidate (combining results from current and parent 5644 // profile), so we need filtering and sorting. 5645 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5646 intent, flags, result, xpDomainInfo, userId); 5647 sortResult = true; 5648 } 5649 } else { 5650 final PackageParser.Package pkg = mPackages.get(pkgName); 5651 if (pkg != null) { 5652 result = filterForEphemeral(filterIfNotSystemUser( 5653 mActivities.queryIntentForPackage( 5654 intent, resolvedType, flags, pkg.activities, userId), 5655 userId), ephemeralPkgName); 5656 } else { 5657 // the caller wants to resolve for a particular package; however, there 5658 // were no installed results, so, try to find an ephemeral result 5659 addEphemeral = isEphemeralAllowed( 5660 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5661 result = new ArrayList<ResolveInfo>(); 5662 } 5663 } 5664 } 5665 if (addEphemeral) { 5666 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5667 final EphemeralRequest requestObject = new EphemeralRequest( 5668 null /*responseObj*/, intent /*origIntent*/, resolvedType, 5669 null /*launchIntent*/, null /*callingPackage*/, userId); 5670 final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne( 5671 mContext, mEphemeralResolverConnection, requestObject); 5672 if (intentInfo != null) { 5673 if (DEBUG_EPHEMERAL) { 5674 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5675 } 5676 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5677 ephemeralInstaller.ephemeralResponse = intentInfo; 5678 // make sure this resolver is the default 5679 ephemeralInstaller.isDefault = true; 5680 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5681 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5682 // add a non-generic filter 5683 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5684 ephemeralInstaller.filter.addDataPath( 5685 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5686 result.add(ephemeralInstaller); 5687 } 5688 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5689 } 5690 if (sortResult) { 5691 Collections.sort(result, mResolvePrioritySorter); 5692 } 5693 return filterForEphemeral(result, ephemeralPkgName); 5694 } 5695 5696 private static class CrossProfileDomainInfo { 5697 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5698 ResolveInfo resolveInfo; 5699 /* Best domain verification status of the activities found in the other profile */ 5700 int bestDomainVerificationStatus; 5701 } 5702 5703 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5704 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5705 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5706 sourceUserId)) { 5707 return null; 5708 } 5709 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5710 resolvedType, flags, parentUserId); 5711 5712 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5713 return null; 5714 } 5715 CrossProfileDomainInfo result = null; 5716 int size = resultTargetUser.size(); 5717 for (int i = 0; i < size; i++) { 5718 ResolveInfo riTargetUser = resultTargetUser.get(i); 5719 // Intent filter verification is only for filters that specify a host. So don't return 5720 // those that handle all web uris. 5721 if (riTargetUser.handleAllWebDataURI) { 5722 continue; 5723 } 5724 String packageName = riTargetUser.activityInfo.packageName; 5725 PackageSetting ps = mSettings.mPackages.get(packageName); 5726 if (ps == null) { 5727 continue; 5728 } 5729 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5730 int status = (int)(verificationState >> 32); 5731 if (result == null) { 5732 result = new CrossProfileDomainInfo(); 5733 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5734 sourceUserId, parentUserId); 5735 result.bestDomainVerificationStatus = status; 5736 } else { 5737 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5738 result.bestDomainVerificationStatus); 5739 } 5740 } 5741 // Don't consider matches with status NEVER across profiles. 5742 if (result != null && result.bestDomainVerificationStatus 5743 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5744 return null; 5745 } 5746 return result; 5747 } 5748 5749 /** 5750 * Verification statuses are ordered from the worse to the best, except for 5751 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5752 */ 5753 private int bestDomainVerificationStatus(int status1, int status2) { 5754 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5755 return status2; 5756 } 5757 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5758 return status1; 5759 } 5760 return (int) MathUtils.max(status1, status2); 5761 } 5762 5763 private boolean isUserEnabled(int userId) { 5764 long callingId = Binder.clearCallingIdentity(); 5765 try { 5766 UserInfo userInfo = sUserManager.getUserInfo(userId); 5767 return userInfo != null && userInfo.isEnabled(); 5768 } finally { 5769 Binder.restoreCallingIdentity(callingId); 5770 } 5771 } 5772 5773 /** 5774 * Filter out activities with systemUserOnly flag set, when current user is not System. 5775 * 5776 * @return filtered list 5777 */ 5778 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5779 if (userId == UserHandle.USER_SYSTEM) { 5780 return resolveInfos; 5781 } 5782 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5783 ResolveInfo info = resolveInfos.get(i); 5784 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5785 resolveInfos.remove(i); 5786 } 5787 } 5788 return resolveInfos; 5789 } 5790 5791 /** 5792 * Filters out ephemeral activities. 5793 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 5794 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 5795 * 5796 * @param resolveInfos The pre-filtered list of resolved activities 5797 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 5798 * is performed. 5799 * @return A filtered list of resolved activities. 5800 */ 5801 private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos, 5802 String ephemeralPkgName) { 5803 if (ephemeralPkgName == null) { 5804 return resolveInfos; 5805 } 5806 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5807 ResolveInfo info = resolveInfos.get(i); 5808 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp(); 5809 // allow activities that are defined in the provided package 5810 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 5811 continue; 5812 } 5813 // allow activities that have been explicitly exposed to ephemeral apps 5814 if (!isEphemeralApp 5815 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 5816 continue; 5817 } 5818 resolveInfos.remove(i); 5819 } 5820 return resolveInfos; 5821 } 5822 5823 /** 5824 * @param resolveInfos list of resolve infos in descending priority order 5825 * @return if the list contains a resolve info with non-negative priority 5826 */ 5827 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5828 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5829 } 5830 5831 private static boolean hasWebURI(Intent intent) { 5832 if (intent.getData() == null) { 5833 return false; 5834 } 5835 final String scheme = intent.getScheme(); 5836 if (TextUtils.isEmpty(scheme)) { 5837 return false; 5838 } 5839 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5840 } 5841 5842 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5843 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5844 int userId) { 5845 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5846 5847 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5848 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5849 candidates.size()); 5850 } 5851 5852 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5853 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5854 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5855 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5856 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5857 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5858 5859 synchronized (mPackages) { 5860 final int count = candidates.size(); 5861 // First, try to use linked apps. Partition the candidates into four lists: 5862 // one for the final results, one for the "do not use ever", one for "undefined status" 5863 // and finally one for "browser app type". 5864 for (int n=0; n<count; n++) { 5865 ResolveInfo info = candidates.get(n); 5866 String packageName = info.activityInfo.packageName; 5867 PackageSetting ps = mSettings.mPackages.get(packageName); 5868 if (ps != null) { 5869 // Add to the special match all list (Browser use case) 5870 if (info.handleAllWebDataURI) { 5871 matchAllList.add(info); 5872 continue; 5873 } 5874 // Try to get the status from User settings first 5875 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5876 int status = (int)(packedStatus >> 32); 5877 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5878 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5879 if (DEBUG_DOMAIN_VERIFICATION) { 5880 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5881 + " : linkgen=" + linkGeneration); 5882 } 5883 // Use link-enabled generation as preferredOrder, i.e. 5884 // prefer newly-enabled over earlier-enabled. 5885 info.preferredOrder = linkGeneration; 5886 alwaysList.add(info); 5887 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5888 if (DEBUG_DOMAIN_VERIFICATION) { 5889 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5890 } 5891 neverList.add(info); 5892 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5893 if (DEBUG_DOMAIN_VERIFICATION) { 5894 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5895 } 5896 alwaysAskList.add(info); 5897 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5898 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5899 if (DEBUG_DOMAIN_VERIFICATION) { 5900 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5901 } 5902 undefinedList.add(info); 5903 } 5904 } 5905 } 5906 5907 // We'll want to include browser possibilities in a few cases 5908 boolean includeBrowser = false; 5909 5910 // First try to add the "always" resolution(s) for the current user, if any 5911 if (alwaysList.size() > 0) { 5912 result.addAll(alwaysList); 5913 } else { 5914 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5915 result.addAll(undefinedList); 5916 // Maybe add one for the other profile. 5917 if (xpDomainInfo != null && ( 5918 xpDomainInfo.bestDomainVerificationStatus 5919 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5920 result.add(xpDomainInfo.resolveInfo); 5921 } 5922 includeBrowser = true; 5923 } 5924 5925 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5926 // If there were 'always' entries their preferred order has been set, so we also 5927 // back that off to make the alternatives equivalent 5928 if (alwaysAskList.size() > 0) { 5929 for (ResolveInfo i : result) { 5930 i.preferredOrder = 0; 5931 } 5932 result.addAll(alwaysAskList); 5933 includeBrowser = true; 5934 } 5935 5936 if (includeBrowser) { 5937 // Also add browsers (all of them or only the default one) 5938 if (DEBUG_DOMAIN_VERIFICATION) { 5939 Slog.v(TAG, " ...including browsers in candidate set"); 5940 } 5941 if ((matchFlags & MATCH_ALL) != 0) { 5942 result.addAll(matchAllList); 5943 } else { 5944 // Browser/generic handling case. If there's a default browser, go straight 5945 // to that (but only if there is no other higher-priority match). 5946 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5947 int maxMatchPrio = 0; 5948 ResolveInfo defaultBrowserMatch = null; 5949 final int numCandidates = matchAllList.size(); 5950 for (int n = 0; n < numCandidates; n++) { 5951 ResolveInfo info = matchAllList.get(n); 5952 // track the highest overall match priority... 5953 if (info.priority > maxMatchPrio) { 5954 maxMatchPrio = info.priority; 5955 } 5956 // ...and the highest-priority default browser match 5957 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5958 if (defaultBrowserMatch == null 5959 || (defaultBrowserMatch.priority < info.priority)) { 5960 if (debug) { 5961 Slog.v(TAG, "Considering default browser match " + info); 5962 } 5963 defaultBrowserMatch = info; 5964 } 5965 } 5966 } 5967 if (defaultBrowserMatch != null 5968 && defaultBrowserMatch.priority >= maxMatchPrio 5969 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5970 { 5971 if (debug) { 5972 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5973 } 5974 result.add(defaultBrowserMatch); 5975 } else { 5976 result.addAll(matchAllList); 5977 } 5978 } 5979 5980 // If there is nothing selected, add all candidates and remove the ones that the user 5981 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5982 if (result.size() == 0) { 5983 result.addAll(candidates); 5984 result.removeAll(neverList); 5985 } 5986 } 5987 } 5988 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5989 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5990 result.size()); 5991 for (ResolveInfo info : result) { 5992 Slog.v(TAG, " + " + info.activityInfo); 5993 } 5994 } 5995 return result; 5996 } 5997 5998 // Returns a packed value as a long: 5999 // 6000 // high 'int'-sized word: link status: undefined/ask/never/always. 6001 // low 'int'-sized word: relative priority among 'always' results. 6002 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6003 long result = ps.getDomainVerificationStatusForUser(userId); 6004 // if none available, get the master status 6005 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6006 if (ps.getIntentFilterVerificationInfo() != null) { 6007 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6008 } 6009 } 6010 return result; 6011 } 6012 6013 private ResolveInfo querySkipCurrentProfileIntents( 6014 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6015 int flags, int sourceUserId) { 6016 if (matchingFilters != null) { 6017 int size = matchingFilters.size(); 6018 for (int i = 0; i < size; i ++) { 6019 CrossProfileIntentFilter filter = matchingFilters.get(i); 6020 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6021 // Checking if there are activities in the target user that can handle the 6022 // intent. 6023 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6024 resolvedType, flags, sourceUserId); 6025 if (resolveInfo != null) { 6026 return resolveInfo; 6027 } 6028 } 6029 } 6030 } 6031 return null; 6032 } 6033 6034 // Return matching ResolveInfo in target user if any. 6035 private ResolveInfo queryCrossProfileIntents( 6036 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6037 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6038 if (matchingFilters != null) { 6039 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6040 // match the same intent. For performance reasons, it is better not to 6041 // run queryIntent twice for the same userId 6042 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6043 int size = matchingFilters.size(); 6044 for (int i = 0; i < size; i++) { 6045 CrossProfileIntentFilter filter = matchingFilters.get(i); 6046 int targetUserId = filter.getTargetUserId(); 6047 boolean skipCurrentProfile = 6048 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6049 boolean skipCurrentProfileIfNoMatchFound = 6050 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6051 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6052 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6053 // Checking if there are activities in the target user that can handle the 6054 // intent. 6055 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6056 resolvedType, flags, sourceUserId); 6057 if (resolveInfo != null) return resolveInfo; 6058 alreadyTriedUserIds.put(targetUserId, true); 6059 } 6060 } 6061 } 6062 return null; 6063 } 6064 6065 /** 6066 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6067 * will forward the intent to the filter's target user. 6068 * Otherwise, returns null. 6069 */ 6070 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6071 String resolvedType, int flags, int sourceUserId) { 6072 int targetUserId = filter.getTargetUserId(); 6073 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6074 resolvedType, flags, targetUserId); 6075 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6076 // If all the matches in the target profile are suspended, return null. 6077 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6078 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6079 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6080 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6081 targetUserId); 6082 } 6083 } 6084 } 6085 return null; 6086 } 6087 6088 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6089 int sourceUserId, int targetUserId) { 6090 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6091 long ident = Binder.clearCallingIdentity(); 6092 boolean targetIsProfile; 6093 try { 6094 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6095 } finally { 6096 Binder.restoreCallingIdentity(ident); 6097 } 6098 String className; 6099 if (targetIsProfile) { 6100 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6101 } else { 6102 className = FORWARD_INTENT_TO_PARENT; 6103 } 6104 ComponentName forwardingActivityComponentName = new ComponentName( 6105 mAndroidApplication.packageName, className); 6106 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6107 sourceUserId); 6108 if (!targetIsProfile) { 6109 forwardingActivityInfo.showUserIcon = targetUserId; 6110 forwardingResolveInfo.noResourceId = true; 6111 } 6112 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6113 forwardingResolveInfo.priority = 0; 6114 forwardingResolveInfo.preferredOrder = 0; 6115 forwardingResolveInfo.match = 0; 6116 forwardingResolveInfo.isDefault = true; 6117 forwardingResolveInfo.filter = filter; 6118 forwardingResolveInfo.targetUserId = targetUserId; 6119 return forwardingResolveInfo; 6120 } 6121 6122 @Override 6123 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6124 Intent[] specifics, String[] specificTypes, Intent intent, 6125 String resolvedType, int flags, int userId) { 6126 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6127 specificTypes, intent, resolvedType, flags, userId)); 6128 } 6129 6130 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6131 Intent[] specifics, String[] specificTypes, Intent intent, 6132 String resolvedType, int flags, int userId) { 6133 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6134 flags = updateFlagsForResolve(flags, userId, intent); 6135 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6136 false /* requireFullPermission */, false /* checkShell */, 6137 "query intent activity options"); 6138 final String resultsAction = intent.getAction(); 6139 6140 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6141 | PackageManager.GET_RESOLVED_FILTER, userId); 6142 6143 if (DEBUG_INTENT_MATCHING) { 6144 Log.v(TAG, "Query " + intent + ": " + results); 6145 } 6146 6147 int specificsPos = 0; 6148 int N; 6149 6150 // todo: note that the algorithm used here is O(N^2). This 6151 // isn't a problem in our current environment, but if we start running 6152 // into situations where we have more than 5 or 10 matches then this 6153 // should probably be changed to something smarter... 6154 6155 // First we go through and resolve each of the specific items 6156 // that were supplied, taking care of removing any corresponding 6157 // duplicate items in the generic resolve list. 6158 if (specifics != null) { 6159 for (int i=0; i<specifics.length; i++) { 6160 final Intent sintent = specifics[i]; 6161 if (sintent == null) { 6162 continue; 6163 } 6164 6165 if (DEBUG_INTENT_MATCHING) { 6166 Log.v(TAG, "Specific #" + i + ": " + sintent); 6167 } 6168 6169 String action = sintent.getAction(); 6170 if (resultsAction != null && resultsAction.equals(action)) { 6171 // If this action was explicitly requested, then don't 6172 // remove things that have it. 6173 action = null; 6174 } 6175 6176 ResolveInfo ri = null; 6177 ActivityInfo ai = null; 6178 6179 ComponentName comp = sintent.getComponent(); 6180 if (comp == null) { 6181 ri = resolveIntent( 6182 sintent, 6183 specificTypes != null ? specificTypes[i] : null, 6184 flags, userId); 6185 if (ri == null) { 6186 continue; 6187 } 6188 if (ri == mResolveInfo) { 6189 // ACK! Must do something better with this. 6190 } 6191 ai = ri.activityInfo; 6192 comp = new ComponentName(ai.applicationInfo.packageName, 6193 ai.name); 6194 } else { 6195 ai = getActivityInfo(comp, flags, userId); 6196 if (ai == null) { 6197 continue; 6198 } 6199 } 6200 6201 // Look for any generic query activities that are duplicates 6202 // of this specific one, and remove them from the results. 6203 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6204 N = results.size(); 6205 int j; 6206 for (j=specificsPos; j<N; j++) { 6207 ResolveInfo sri = results.get(j); 6208 if ((sri.activityInfo.name.equals(comp.getClassName()) 6209 && sri.activityInfo.applicationInfo.packageName.equals( 6210 comp.getPackageName())) 6211 || (action != null && sri.filter.matchAction(action))) { 6212 results.remove(j); 6213 if (DEBUG_INTENT_MATCHING) Log.v( 6214 TAG, "Removing duplicate item from " + j 6215 + " due to specific " + specificsPos); 6216 if (ri == null) { 6217 ri = sri; 6218 } 6219 j--; 6220 N--; 6221 } 6222 } 6223 6224 // Add this specific item to its proper place. 6225 if (ri == null) { 6226 ri = new ResolveInfo(); 6227 ri.activityInfo = ai; 6228 } 6229 results.add(specificsPos, ri); 6230 ri.specificIndex = i; 6231 specificsPos++; 6232 } 6233 } 6234 6235 // Now we go through the remaining generic results and remove any 6236 // duplicate actions that are found here. 6237 N = results.size(); 6238 for (int i=specificsPos; i<N-1; i++) { 6239 final ResolveInfo rii = results.get(i); 6240 if (rii.filter == null) { 6241 continue; 6242 } 6243 6244 // Iterate over all of the actions of this result's intent 6245 // filter... typically this should be just one. 6246 final Iterator<String> it = rii.filter.actionsIterator(); 6247 if (it == null) { 6248 continue; 6249 } 6250 while (it.hasNext()) { 6251 final String action = it.next(); 6252 if (resultsAction != null && resultsAction.equals(action)) { 6253 // If this action was explicitly requested, then don't 6254 // remove things that have it. 6255 continue; 6256 } 6257 for (int j=i+1; j<N; j++) { 6258 final ResolveInfo rij = results.get(j); 6259 if (rij.filter != null && rij.filter.hasAction(action)) { 6260 results.remove(j); 6261 if (DEBUG_INTENT_MATCHING) Log.v( 6262 TAG, "Removing duplicate item from " + j 6263 + " due to action " + action + " at " + i); 6264 j--; 6265 N--; 6266 } 6267 } 6268 } 6269 6270 // If the caller didn't request filter information, drop it now 6271 // so we don't have to marshall/unmarshall it. 6272 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6273 rii.filter = null; 6274 } 6275 } 6276 6277 // Filter out the caller activity if so requested. 6278 if (caller != null) { 6279 N = results.size(); 6280 for (int i=0; i<N; i++) { 6281 ActivityInfo ainfo = results.get(i).activityInfo; 6282 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6283 && caller.getClassName().equals(ainfo.name)) { 6284 results.remove(i); 6285 break; 6286 } 6287 } 6288 } 6289 6290 // If the caller didn't request filter information, 6291 // drop them now so we don't have to 6292 // marshall/unmarshall it. 6293 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6294 N = results.size(); 6295 for (int i=0; i<N; i++) { 6296 results.get(i).filter = null; 6297 } 6298 } 6299 6300 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6301 return results; 6302 } 6303 6304 @Override 6305 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6306 String resolvedType, int flags, int userId) { 6307 return new ParceledListSlice<>( 6308 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6309 } 6310 6311 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6312 String resolvedType, int flags, int userId) { 6313 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6314 flags = updateFlagsForResolve(flags, userId, intent); 6315 ComponentName comp = intent.getComponent(); 6316 if (comp == null) { 6317 if (intent.getSelector() != null) { 6318 intent = intent.getSelector(); 6319 comp = intent.getComponent(); 6320 } 6321 } 6322 if (comp != null) { 6323 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6324 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6325 if (ai != null) { 6326 ResolveInfo ri = new ResolveInfo(); 6327 ri.activityInfo = ai; 6328 list.add(ri); 6329 } 6330 return list; 6331 } 6332 6333 // reader 6334 synchronized (mPackages) { 6335 String pkgName = intent.getPackage(); 6336 if (pkgName == null) { 6337 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6338 } 6339 final PackageParser.Package pkg = mPackages.get(pkgName); 6340 if (pkg != null) { 6341 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6342 userId); 6343 } 6344 return Collections.emptyList(); 6345 } 6346 } 6347 6348 @Override 6349 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6350 if (!sUserManager.exists(userId)) return null; 6351 flags = updateFlagsForResolve(flags, userId, intent); 6352 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6353 if (query != null) { 6354 if (query.size() >= 1) { 6355 // If there is more than one service with the same priority, 6356 // just arbitrarily pick the first one. 6357 return query.get(0); 6358 } 6359 } 6360 return null; 6361 } 6362 6363 @Override 6364 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6365 String resolvedType, int flags, int userId) { 6366 return new ParceledListSlice<>( 6367 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6368 } 6369 6370 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6371 String resolvedType, int flags, int userId) { 6372 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6373 flags = updateFlagsForResolve(flags, userId, intent); 6374 ComponentName comp = intent.getComponent(); 6375 if (comp == null) { 6376 if (intent.getSelector() != null) { 6377 intent = intent.getSelector(); 6378 comp = intent.getComponent(); 6379 } 6380 } 6381 if (comp != null) { 6382 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6383 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6384 if (si != null) { 6385 final ResolveInfo ri = new ResolveInfo(); 6386 ri.serviceInfo = si; 6387 list.add(ri); 6388 } 6389 return list; 6390 } 6391 6392 // reader 6393 synchronized (mPackages) { 6394 String pkgName = intent.getPackage(); 6395 if (pkgName == null) { 6396 return mServices.queryIntent(intent, resolvedType, flags, userId); 6397 } 6398 final PackageParser.Package pkg = mPackages.get(pkgName); 6399 if (pkg != null) { 6400 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6401 userId); 6402 } 6403 return Collections.emptyList(); 6404 } 6405 } 6406 6407 @Override 6408 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6409 String resolvedType, int flags, int userId) { 6410 return new ParceledListSlice<>( 6411 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6412 } 6413 6414 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6415 Intent intent, String resolvedType, int flags, int userId) { 6416 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6417 flags = updateFlagsForResolve(flags, userId, intent); 6418 ComponentName comp = intent.getComponent(); 6419 if (comp == null) { 6420 if (intent.getSelector() != null) { 6421 intent = intent.getSelector(); 6422 comp = intent.getComponent(); 6423 } 6424 } 6425 if (comp != null) { 6426 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6427 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6428 if (pi != null) { 6429 final ResolveInfo ri = new ResolveInfo(); 6430 ri.providerInfo = pi; 6431 list.add(ri); 6432 } 6433 return list; 6434 } 6435 6436 // reader 6437 synchronized (mPackages) { 6438 String pkgName = intent.getPackage(); 6439 if (pkgName == null) { 6440 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6441 } 6442 final PackageParser.Package pkg = mPackages.get(pkgName); 6443 if (pkg != null) { 6444 return mProviders.queryIntentForPackage( 6445 intent, resolvedType, flags, pkg.providers, userId); 6446 } 6447 return Collections.emptyList(); 6448 } 6449 } 6450 6451 @Override 6452 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6453 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6454 flags = updateFlagsForPackage(flags, userId, null); 6455 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6456 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6457 true /* requireFullPermission */, false /* checkShell */, 6458 "get installed packages"); 6459 6460 // writer 6461 synchronized (mPackages) { 6462 ArrayList<PackageInfo> list; 6463 if (listUninstalled) { 6464 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6465 for (PackageSetting ps : mSettings.mPackages.values()) { 6466 final PackageInfo pi; 6467 if (ps.pkg != null) { 6468 pi = generatePackageInfo(ps, flags, userId); 6469 } else { 6470 pi = generatePackageInfo(ps, flags, userId); 6471 } 6472 if (pi != null) { 6473 list.add(pi); 6474 } 6475 } 6476 } else { 6477 list = new ArrayList<PackageInfo>(mPackages.size()); 6478 for (PackageParser.Package p : mPackages.values()) { 6479 final PackageInfo pi = 6480 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6481 if (pi != null) { 6482 list.add(pi); 6483 } 6484 } 6485 } 6486 6487 return new ParceledListSlice<PackageInfo>(list); 6488 } 6489 } 6490 6491 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6492 String[] permissions, boolean[] tmp, int flags, int userId) { 6493 int numMatch = 0; 6494 final PermissionsState permissionsState = ps.getPermissionsState(); 6495 for (int i=0; i<permissions.length; i++) { 6496 final String permission = permissions[i]; 6497 if (permissionsState.hasPermission(permission, userId)) { 6498 tmp[i] = true; 6499 numMatch++; 6500 } else { 6501 tmp[i] = false; 6502 } 6503 } 6504 if (numMatch == 0) { 6505 return; 6506 } 6507 final PackageInfo pi; 6508 if (ps.pkg != null) { 6509 pi = generatePackageInfo(ps, flags, userId); 6510 } else { 6511 pi = generatePackageInfo(ps, flags, userId); 6512 } 6513 // The above might return null in cases of uninstalled apps or install-state 6514 // skew across users/profiles. 6515 if (pi != null) { 6516 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6517 if (numMatch == permissions.length) { 6518 pi.requestedPermissions = permissions; 6519 } else { 6520 pi.requestedPermissions = new String[numMatch]; 6521 numMatch = 0; 6522 for (int i=0; i<permissions.length; i++) { 6523 if (tmp[i]) { 6524 pi.requestedPermissions[numMatch] = permissions[i]; 6525 numMatch++; 6526 } 6527 } 6528 } 6529 } 6530 list.add(pi); 6531 } 6532 } 6533 6534 @Override 6535 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6536 String[] permissions, int flags, int userId) { 6537 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6538 flags = updateFlagsForPackage(flags, userId, permissions); 6539 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6540 true /* requireFullPermission */, false /* checkShell */, 6541 "get packages holding permissions"); 6542 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6543 6544 // writer 6545 synchronized (mPackages) { 6546 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6547 boolean[] tmpBools = new boolean[permissions.length]; 6548 if (listUninstalled) { 6549 for (PackageSetting ps : mSettings.mPackages.values()) { 6550 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6551 userId); 6552 } 6553 } else { 6554 for (PackageParser.Package pkg : mPackages.values()) { 6555 PackageSetting ps = (PackageSetting)pkg.mExtras; 6556 if (ps != null) { 6557 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6558 userId); 6559 } 6560 } 6561 } 6562 6563 return new ParceledListSlice<PackageInfo>(list); 6564 } 6565 } 6566 6567 @Override 6568 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6569 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6570 flags = updateFlagsForApplication(flags, userId, null); 6571 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6572 6573 // writer 6574 synchronized (mPackages) { 6575 ArrayList<ApplicationInfo> list; 6576 if (listUninstalled) { 6577 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6578 for (PackageSetting ps : mSettings.mPackages.values()) { 6579 ApplicationInfo ai; 6580 int effectiveFlags = flags; 6581 if (ps.isSystem()) { 6582 effectiveFlags |= PackageManager.MATCH_ANY_USER; 6583 } 6584 if (ps.pkg != null) { 6585 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 6586 ps.readUserState(userId), userId); 6587 } else { 6588 ai = generateApplicationInfoFromSettingsLPw(ps.name, effectiveFlags, 6589 userId); 6590 } 6591 if (ai != null) { 6592 list.add(ai); 6593 } 6594 } 6595 } else { 6596 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6597 for (PackageParser.Package p : mPackages.values()) { 6598 if (p.mExtras != null) { 6599 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6600 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6601 if (ai != null) { 6602 list.add(ai); 6603 } 6604 } 6605 } 6606 } 6607 6608 return new ParceledListSlice<ApplicationInfo>(list); 6609 } 6610 } 6611 6612 @Override 6613 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6614 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6615 return null; 6616 } 6617 6618 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6619 "getEphemeralApplications"); 6620 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6621 true /* requireFullPermission */, false /* checkShell */, 6622 "getEphemeralApplications"); 6623 synchronized (mPackages) { 6624 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6625 .getEphemeralApplicationsLPw(userId); 6626 if (ephemeralApps != null) { 6627 return new ParceledListSlice<>(ephemeralApps); 6628 } 6629 } 6630 return null; 6631 } 6632 6633 @Override 6634 public boolean isEphemeralApplication(String packageName, int userId) { 6635 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6636 true /* requireFullPermission */, false /* checkShell */, 6637 "isEphemeral"); 6638 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6639 return false; 6640 } 6641 6642 if (!isCallerSameApp(packageName)) { 6643 return false; 6644 } 6645 synchronized (mPackages) { 6646 PackageParser.Package pkg = mPackages.get(packageName); 6647 if (pkg != null) { 6648 return pkg.applicationInfo.isEphemeralApp(); 6649 } 6650 } 6651 return false; 6652 } 6653 6654 @Override 6655 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6656 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6657 return null; 6658 } 6659 6660 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6661 true /* requireFullPermission */, false /* checkShell */, 6662 "getCookie"); 6663 if (!isCallerSameApp(packageName)) { 6664 return null; 6665 } 6666 synchronized (mPackages) { 6667 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6668 packageName, userId); 6669 } 6670 } 6671 6672 @Override 6673 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6674 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6675 return true; 6676 } 6677 6678 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6679 true /* requireFullPermission */, true /* checkShell */, 6680 "setCookie"); 6681 if (!isCallerSameApp(packageName)) { 6682 return false; 6683 } 6684 synchronized (mPackages) { 6685 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6686 packageName, cookie, userId); 6687 } 6688 } 6689 6690 @Override 6691 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6692 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6693 return null; 6694 } 6695 6696 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6697 "getEphemeralApplicationIcon"); 6698 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6699 true /* requireFullPermission */, false /* checkShell */, 6700 "getEphemeralApplicationIcon"); 6701 synchronized (mPackages) { 6702 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6703 packageName, userId); 6704 } 6705 } 6706 6707 private boolean isCallerSameApp(String packageName) { 6708 PackageParser.Package pkg = mPackages.get(packageName); 6709 return pkg != null 6710 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6711 } 6712 6713 @Override 6714 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6715 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6716 } 6717 6718 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6719 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6720 6721 // reader 6722 synchronized (mPackages) { 6723 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6724 final int userId = UserHandle.getCallingUserId(); 6725 while (i.hasNext()) { 6726 final PackageParser.Package p = i.next(); 6727 if (p.applicationInfo == null) continue; 6728 6729 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6730 && !p.applicationInfo.isDirectBootAware(); 6731 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6732 && p.applicationInfo.isDirectBootAware(); 6733 6734 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6735 && (!mSafeMode || isSystemApp(p)) 6736 && (matchesUnaware || matchesAware)) { 6737 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6738 if (ps != null) { 6739 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6740 ps.readUserState(userId), userId); 6741 if (ai != null) { 6742 finalList.add(ai); 6743 } 6744 } 6745 } 6746 } 6747 } 6748 6749 return finalList; 6750 } 6751 6752 @Override 6753 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6754 if (!sUserManager.exists(userId)) return null; 6755 flags = updateFlagsForComponent(flags, userId, name); 6756 // reader 6757 synchronized (mPackages) { 6758 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6759 PackageSetting ps = provider != null 6760 ? mSettings.mPackages.get(provider.owner.packageName) 6761 : null; 6762 return ps != null 6763 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6764 ? PackageParser.generateProviderInfo(provider, flags, 6765 ps.readUserState(userId), userId) 6766 : null; 6767 } 6768 } 6769 6770 /** 6771 * @deprecated 6772 */ 6773 @Deprecated 6774 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6775 // reader 6776 synchronized (mPackages) { 6777 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6778 .entrySet().iterator(); 6779 final int userId = UserHandle.getCallingUserId(); 6780 while (i.hasNext()) { 6781 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6782 PackageParser.Provider p = entry.getValue(); 6783 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6784 6785 if (ps != null && p.syncable 6786 && (!mSafeMode || (p.info.applicationInfo.flags 6787 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6788 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6789 ps.readUserState(userId), userId); 6790 if (info != null) { 6791 outNames.add(entry.getKey()); 6792 outInfo.add(info); 6793 } 6794 } 6795 } 6796 } 6797 } 6798 6799 @Override 6800 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6801 int uid, int flags) { 6802 final int userId = processName != null ? UserHandle.getUserId(uid) 6803 : UserHandle.getCallingUserId(); 6804 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6805 flags = updateFlagsForComponent(flags, userId, processName); 6806 6807 ArrayList<ProviderInfo> finalList = null; 6808 // reader 6809 synchronized (mPackages) { 6810 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6811 while (i.hasNext()) { 6812 final PackageParser.Provider p = i.next(); 6813 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6814 if (ps != null && p.info.authority != null 6815 && (processName == null 6816 || (p.info.processName.equals(processName) 6817 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6818 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6819 if (finalList == null) { 6820 finalList = new ArrayList<ProviderInfo>(3); 6821 } 6822 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6823 ps.readUserState(userId), userId); 6824 if (info != null) { 6825 finalList.add(info); 6826 } 6827 } 6828 } 6829 } 6830 6831 if (finalList != null) { 6832 Collections.sort(finalList, mProviderInitOrderSorter); 6833 return new ParceledListSlice<ProviderInfo>(finalList); 6834 } 6835 6836 return ParceledListSlice.emptyList(); 6837 } 6838 6839 @Override 6840 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6841 // reader 6842 synchronized (mPackages) { 6843 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6844 return PackageParser.generateInstrumentationInfo(i, flags); 6845 } 6846 } 6847 6848 @Override 6849 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6850 String targetPackage, int flags) { 6851 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6852 } 6853 6854 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6855 int flags) { 6856 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6857 6858 // reader 6859 synchronized (mPackages) { 6860 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6861 while (i.hasNext()) { 6862 final PackageParser.Instrumentation p = i.next(); 6863 if (targetPackage == null 6864 || targetPackage.equals(p.info.targetPackage)) { 6865 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6866 flags); 6867 if (ii != null) { 6868 finalList.add(ii); 6869 } 6870 } 6871 } 6872 } 6873 6874 return finalList; 6875 } 6876 6877 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6878 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6879 if (overlays == null) { 6880 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6881 return; 6882 } 6883 for (PackageParser.Package opkg : overlays.values()) { 6884 // Not much to do if idmap fails: we already logged the error 6885 // and we certainly don't want to abort installation of pkg simply 6886 // because an overlay didn't fit properly. For these reasons, 6887 // ignore the return value of createIdmapForPackagePairLI. 6888 createIdmapForPackagePairLI(pkg, opkg); 6889 } 6890 } 6891 6892 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6893 PackageParser.Package opkg) { 6894 if (!opkg.mTrustedOverlay) { 6895 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6896 opkg.baseCodePath + ": overlay not trusted"); 6897 return false; 6898 } 6899 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6900 if (overlaySet == null) { 6901 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6902 opkg.baseCodePath + " but target package has no known overlays"); 6903 return false; 6904 } 6905 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6906 // TODO: generate idmap for split APKs 6907 try { 6908 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6909 } catch (InstallerException e) { 6910 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6911 + opkg.baseCodePath); 6912 return false; 6913 } 6914 PackageParser.Package[] overlayArray = 6915 overlaySet.values().toArray(new PackageParser.Package[0]); 6916 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6917 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6918 return p1.mOverlayPriority - p2.mOverlayPriority; 6919 } 6920 }; 6921 Arrays.sort(overlayArray, cmp); 6922 6923 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6924 int i = 0; 6925 for (PackageParser.Package p : overlayArray) { 6926 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6927 } 6928 return true; 6929 } 6930 6931 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6932 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 6933 try { 6934 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6935 } finally { 6936 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6937 } 6938 } 6939 6940 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6941 final File[] files = dir.listFiles(); 6942 if (ArrayUtils.isEmpty(files)) { 6943 Log.d(TAG, "No files in app dir " + dir); 6944 return; 6945 } 6946 6947 if (DEBUG_PACKAGE_SCANNING) { 6948 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6949 + " flags=0x" + Integer.toHexString(parseFlags)); 6950 } 6951 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 6952 mSeparateProcesses, mOnlyCore, mMetrics); 6953 6954 // Submit files for parsing in parallel 6955 int fileCount = 0; 6956 for (File file : files) { 6957 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6958 && !PackageInstallerService.isStageName(file.getName()); 6959 if (!isPackage) { 6960 // Ignore entries which are not packages 6961 continue; 6962 } 6963 parallelPackageParser.submit(file, parseFlags); 6964 fileCount++; 6965 } 6966 6967 // Process results one by one 6968 for (; fileCount > 0; fileCount--) { 6969 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 6970 Throwable throwable = parseResult.throwable; 6971 int errorCode = PackageManager.INSTALL_SUCCEEDED; 6972 6973 if (throwable == null) { 6974 try { 6975 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 6976 currentTime, null); 6977 } catch (PackageManagerException e) { 6978 errorCode = e.error; 6979 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 6980 } 6981 } else if (throwable instanceof PackageParser.PackageParserException) { 6982 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 6983 throwable; 6984 errorCode = e.error; 6985 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 6986 } else { 6987 throw new IllegalStateException("Unexpected exception occurred while parsing " 6988 + parseResult.scanFile, throwable); 6989 } 6990 6991 // Delete invalid userdata apps 6992 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6993 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 6994 logCriticalInfo(Log.WARN, 6995 "Deleting invalid package at " + parseResult.scanFile); 6996 removeCodePathLI(parseResult.scanFile); 6997 } 6998 } 6999 parallelPackageParser.close(); 7000 } 7001 7002 private static File getSettingsProblemFile() { 7003 File dataDir = Environment.getDataDirectory(); 7004 File systemDir = new File(dataDir, "system"); 7005 File fname = new File(systemDir, "uiderrors.txt"); 7006 return fname; 7007 } 7008 7009 static void reportSettingsProblem(int priority, String msg) { 7010 logCriticalInfo(priority, msg); 7011 } 7012 7013 static void logCriticalInfo(int priority, String msg) { 7014 Slog.println(priority, TAG, msg); 7015 EventLogTags.writePmCriticalInfo(msg); 7016 try { 7017 File fname = getSettingsProblemFile(); 7018 FileOutputStream out = new FileOutputStream(fname, true); 7019 PrintWriter pw = new FastPrintWriter(out); 7020 SimpleDateFormat formatter = new SimpleDateFormat(); 7021 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7022 pw.println(dateString + ": " + msg); 7023 pw.close(); 7024 FileUtils.setPermissions( 7025 fname.toString(), 7026 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7027 -1, -1); 7028 } catch (java.io.IOException e) { 7029 } 7030 } 7031 7032 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7033 if (srcFile.isDirectory()) { 7034 final File baseFile = new File(pkg.baseCodePath); 7035 long maxModifiedTime = baseFile.lastModified(); 7036 if (pkg.splitCodePaths != null) { 7037 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7038 final File splitFile = new File(pkg.splitCodePaths[i]); 7039 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7040 } 7041 } 7042 return maxModifiedTime; 7043 } 7044 return srcFile.lastModified(); 7045 } 7046 7047 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7048 final int policyFlags) throws PackageManagerException { 7049 // When upgrading from pre-N MR1, verify the package time stamp using the package 7050 // directory and not the APK file. 7051 final long lastModifiedTime = mIsPreNMR1Upgrade 7052 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7053 if (ps != null 7054 && ps.codePath.equals(srcFile) 7055 && ps.timeStamp == lastModifiedTime 7056 && !isCompatSignatureUpdateNeeded(pkg) 7057 && !isRecoverSignatureUpdateNeeded(pkg)) { 7058 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7059 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7060 ArraySet<PublicKey> signingKs; 7061 synchronized (mPackages) { 7062 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7063 } 7064 if (ps.signatures.mSignatures != null 7065 && ps.signatures.mSignatures.length != 0 7066 && signingKs != null) { 7067 // Optimization: reuse the existing cached certificates 7068 // if the package appears to be unchanged. 7069 pkg.mSignatures = ps.signatures.mSignatures; 7070 pkg.mSigningKeys = signingKs; 7071 return; 7072 } 7073 7074 Slog.w(TAG, "PackageSetting for " + ps.name 7075 + " is missing signatures. Collecting certs again to recover them."); 7076 } else { 7077 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7078 } 7079 7080 try { 7081 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7082 PackageParser.collectCertificates(pkg, policyFlags); 7083 } catch (PackageParserException e) { 7084 throw PackageManagerException.from(e); 7085 } finally { 7086 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7087 } 7088 } 7089 7090 /** 7091 * Traces a package scan. 7092 * @see #scanPackageLI(File, int, int, long, UserHandle) 7093 */ 7094 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7095 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7096 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7097 try { 7098 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7099 } finally { 7100 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7101 } 7102 } 7103 7104 /** 7105 * Scans a package and returns the newly parsed package. 7106 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7107 */ 7108 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7109 long currentTime, UserHandle user) throws PackageManagerException { 7110 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7111 PackageParser pp = new PackageParser(); 7112 pp.setSeparateProcesses(mSeparateProcesses); 7113 pp.setOnlyCoreApps(mOnlyCore); 7114 pp.setDisplayMetrics(mMetrics); 7115 7116 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7117 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7118 } 7119 7120 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7121 final PackageParser.Package pkg; 7122 try { 7123 pkg = pp.parsePackage(scanFile, parseFlags); 7124 } catch (PackageParserException e) { 7125 throw PackageManagerException.from(e); 7126 } finally { 7127 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7128 } 7129 7130 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7131 } 7132 7133 /** 7134 * Scans a package and returns the newly parsed package. 7135 * @throws PackageManagerException on a parse error. 7136 */ 7137 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7138 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7139 throws PackageManagerException { 7140 // If the package has children and this is the first dive in the function 7141 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7142 // packages (parent and children) would be successfully scanned before the 7143 // actual scan since scanning mutates internal state and we want to atomically 7144 // install the package and its children. 7145 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7146 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7147 scanFlags |= SCAN_CHECK_ONLY; 7148 } 7149 } else { 7150 scanFlags &= ~SCAN_CHECK_ONLY; 7151 } 7152 7153 // Scan the parent 7154 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7155 scanFlags, currentTime, user); 7156 7157 // Scan the children 7158 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7159 for (int i = 0; i < childCount; i++) { 7160 PackageParser.Package childPackage = pkg.childPackages.get(i); 7161 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7162 currentTime, user); 7163 } 7164 7165 7166 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7167 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7168 } 7169 7170 return scannedPkg; 7171 } 7172 7173 /** 7174 * Scans a package and returns the newly parsed package. 7175 * @throws PackageManagerException on a parse error. 7176 */ 7177 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7178 int policyFlags, int scanFlags, long currentTime, UserHandle user) 7179 throws PackageManagerException { 7180 PackageSetting ps = null; 7181 PackageSetting updatedPkg; 7182 // reader 7183 synchronized (mPackages) { 7184 // Look to see if we already know about this package. 7185 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7186 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7187 // This package has been renamed to its original name. Let's 7188 // use that. 7189 ps = mSettings.getPackageLPr(oldName); 7190 } 7191 // If there was no original package, see one for the real package name. 7192 if (ps == null) { 7193 ps = mSettings.getPackageLPr(pkg.packageName); 7194 } 7195 // Check to see if this package could be hiding/updating a system 7196 // package. Must look for it either under the original or real 7197 // package name depending on our state. 7198 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7199 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7200 7201 // If this is a package we don't know about on the system partition, we 7202 // may need to remove disabled child packages on the system partition 7203 // or may need to not add child packages if the parent apk is updated 7204 // on the data partition and no longer defines this child package. 7205 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7206 // If this is a parent package for an updated system app and this system 7207 // app got an OTA update which no longer defines some of the child packages 7208 // we have to prune them from the disabled system packages. 7209 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7210 if (disabledPs != null) { 7211 final int scannedChildCount = (pkg.childPackages != null) 7212 ? pkg.childPackages.size() : 0; 7213 final int disabledChildCount = disabledPs.childPackageNames != null 7214 ? disabledPs.childPackageNames.size() : 0; 7215 for (int i = 0; i < disabledChildCount; i++) { 7216 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7217 boolean disabledPackageAvailable = false; 7218 for (int j = 0; j < scannedChildCount; j++) { 7219 PackageParser.Package childPkg = pkg.childPackages.get(j); 7220 if (childPkg.packageName.equals(disabledChildPackageName)) { 7221 disabledPackageAvailable = true; 7222 break; 7223 } 7224 } 7225 if (!disabledPackageAvailable) { 7226 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7227 } 7228 } 7229 } 7230 } 7231 } 7232 7233 boolean updatedPkgBetter = false; 7234 // First check if this is a system package that may involve an update 7235 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7236 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7237 // it needs to drop FLAG_PRIVILEGED. 7238 if (locationIsPrivileged(scanFile)) { 7239 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7240 } else { 7241 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7242 } 7243 7244 if (ps != null && !ps.codePath.equals(scanFile)) { 7245 // The path has changed from what was last scanned... check the 7246 // version of the new path against what we have stored to determine 7247 // what to do. 7248 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7249 if (pkg.mVersionCode <= ps.versionCode) { 7250 // The system package has been updated and the code path does not match 7251 // Ignore entry. Skip it. 7252 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7253 + " ignored: updated version " + ps.versionCode 7254 + " better than this " + pkg.mVersionCode); 7255 if (!updatedPkg.codePath.equals(scanFile)) { 7256 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7257 + ps.name + " changing from " + updatedPkg.codePathString 7258 + " to " + scanFile); 7259 updatedPkg.codePath = scanFile; 7260 updatedPkg.codePathString = scanFile.toString(); 7261 updatedPkg.resourcePath = scanFile; 7262 updatedPkg.resourcePathString = scanFile.toString(); 7263 } 7264 updatedPkg.pkg = pkg; 7265 updatedPkg.versionCode = pkg.mVersionCode; 7266 7267 // Update the disabled system child packages to point to the package too. 7268 final int childCount = updatedPkg.childPackageNames != null 7269 ? updatedPkg.childPackageNames.size() : 0; 7270 for (int i = 0; i < childCount; i++) { 7271 String childPackageName = updatedPkg.childPackageNames.get(i); 7272 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7273 childPackageName); 7274 if (updatedChildPkg != null) { 7275 updatedChildPkg.pkg = pkg; 7276 updatedChildPkg.versionCode = pkg.mVersionCode; 7277 } 7278 } 7279 7280 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7281 + scanFile + " ignored: updated version " + ps.versionCode 7282 + " better than this " + pkg.mVersionCode); 7283 } else { 7284 // The current app on the system partition is better than 7285 // what we have updated to on the data partition; switch 7286 // back to the system partition version. 7287 // At this point, its safely assumed that package installation for 7288 // apps in system partition will go through. If not there won't be a working 7289 // version of the app 7290 // writer 7291 synchronized (mPackages) { 7292 // Just remove the loaded entries from package lists. 7293 mPackages.remove(ps.name); 7294 } 7295 7296 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7297 + " reverting from " + ps.codePathString 7298 + ": new version " + pkg.mVersionCode 7299 + " better than installed " + ps.versionCode); 7300 7301 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7302 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7303 synchronized (mInstallLock) { 7304 args.cleanUpResourcesLI(); 7305 } 7306 synchronized (mPackages) { 7307 mSettings.enableSystemPackageLPw(ps.name); 7308 } 7309 updatedPkgBetter = true; 7310 } 7311 } 7312 } 7313 7314 if (updatedPkg != null) { 7315 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7316 // initially 7317 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7318 7319 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7320 // flag set initially 7321 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7322 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7323 } 7324 } 7325 7326 // Verify certificates against what was last scanned 7327 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7328 7329 /* 7330 * A new system app appeared, but we already had a non-system one of the 7331 * same name installed earlier. 7332 */ 7333 boolean shouldHideSystemApp = false; 7334 if (updatedPkg == null && ps != null 7335 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7336 /* 7337 * Check to make sure the signatures match first. If they don't, 7338 * wipe the installed application and its data. 7339 */ 7340 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7341 != PackageManager.SIGNATURE_MATCH) { 7342 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7343 + " signatures don't match existing userdata copy; removing"); 7344 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7345 "scanPackageInternalLI")) { 7346 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7347 } 7348 ps = null; 7349 } else { 7350 /* 7351 * If the newly-added system app is an older version than the 7352 * already installed version, hide it. It will be scanned later 7353 * and re-added like an update. 7354 */ 7355 if (pkg.mVersionCode <= ps.versionCode) { 7356 shouldHideSystemApp = true; 7357 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7358 + " but new version " + pkg.mVersionCode + " better than installed " 7359 + ps.versionCode + "; hiding system"); 7360 } else { 7361 /* 7362 * The newly found system app is a newer version that the 7363 * one previously installed. Simply remove the 7364 * already-installed application and replace it with our own 7365 * while keeping the application data. 7366 */ 7367 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7368 + " reverting from " + ps.codePathString + ": new version " 7369 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7370 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7371 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7372 synchronized (mInstallLock) { 7373 args.cleanUpResourcesLI(); 7374 } 7375 } 7376 } 7377 } 7378 7379 // The apk is forward locked (not public) if its code and resources 7380 // are kept in different files. (except for app in either system or 7381 // vendor path). 7382 // TODO grab this value from PackageSettings 7383 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7384 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7385 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7386 } 7387 } 7388 7389 // TODO: extend to support forward-locked splits 7390 String resourcePath = null; 7391 String baseResourcePath = null; 7392 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7393 if (ps != null && ps.resourcePathString != null) { 7394 resourcePath = ps.resourcePathString; 7395 baseResourcePath = ps.resourcePathString; 7396 } else { 7397 // Should not happen at all. Just log an error. 7398 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7399 } 7400 } else { 7401 resourcePath = pkg.codePath; 7402 baseResourcePath = pkg.baseCodePath; 7403 } 7404 7405 // Set application objects path explicitly. 7406 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7407 pkg.setApplicationInfoCodePath(pkg.codePath); 7408 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7409 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7410 pkg.setApplicationInfoResourcePath(resourcePath); 7411 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7412 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7413 7414 // Note that we invoke the following method only if we are about to unpack an application 7415 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7416 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7417 7418 /* 7419 * If the system app should be overridden by a previously installed 7420 * data, hide the system app now and let the /data/app scan pick it up 7421 * again. 7422 */ 7423 if (shouldHideSystemApp) { 7424 synchronized (mPackages) { 7425 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7426 } 7427 } 7428 7429 return scannedPkg; 7430 } 7431 7432 private static String fixProcessName(String defProcessName, 7433 String processName) { 7434 if (processName == null) { 7435 return defProcessName; 7436 } 7437 return processName; 7438 } 7439 7440 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7441 throws PackageManagerException { 7442 if (pkgSetting.signatures.mSignatures != null) { 7443 // Already existing package. Make sure signatures match 7444 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7445 == PackageManager.SIGNATURE_MATCH; 7446 if (!match) { 7447 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7448 == PackageManager.SIGNATURE_MATCH; 7449 } 7450 if (!match) { 7451 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7452 == PackageManager.SIGNATURE_MATCH; 7453 } 7454 if (!match) { 7455 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7456 + pkg.packageName + " signatures do not match the " 7457 + "previously installed version; ignoring!"); 7458 } 7459 } 7460 7461 // Check for shared user signatures 7462 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7463 // Already existing package. Make sure signatures match 7464 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7465 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7466 if (!match) { 7467 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7468 == PackageManager.SIGNATURE_MATCH; 7469 } 7470 if (!match) { 7471 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7472 == PackageManager.SIGNATURE_MATCH; 7473 } 7474 if (!match) { 7475 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7476 "Package " + pkg.packageName 7477 + " has no signatures that match those in shared user " 7478 + pkgSetting.sharedUser.name + "; ignoring!"); 7479 } 7480 } 7481 } 7482 7483 /** 7484 * Enforces that only the system UID or root's UID can call a method exposed 7485 * via Binder. 7486 * 7487 * @param message used as message if SecurityException is thrown 7488 * @throws SecurityException if the caller is not system or root 7489 */ 7490 private static final void enforceSystemOrRoot(String message) { 7491 final int uid = Binder.getCallingUid(); 7492 if (uid != Process.SYSTEM_UID && uid != 0) { 7493 throw new SecurityException(message); 7494 } 7495 } 7496 7497 @Override 7498 public void performFstrimIfNeeded() { 7499 enforceSystemOrRoot("Only the system can request fstrim"); 7500 7501 // Before everything else, see whether we need to fstrim. 7502 try { 7503 IStorageManager sm = PackageHelper.getStorageManager(); 7504 if (sm != null) { 7505 boolean doTrim = false; 7506 final long interval = android.provider.Settings.Global.getLong( 7507 mContext.getContentResolver(), 7508 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7509 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7510 if (interval > 0) { 7511 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 7512 if (timeSinceLast > interval) { 7513 doTrim = true; 7514 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7515 + "; running immediately"); 7516 } 7517 } 7518 if (doTrim) { 7519 final boolean dexOptDialogShown; 7520 synchronized (mPackages) { 7521 dexOptDialogShown = mDexOptDialogShown; 7522 } 7523 if (!isFirstBoot() && dexOptDialogShown) { 7524 try { 7525 ActivityManager.getService().showBootMessage( 7526 mContext.getResources().getString( 7527 R.string.android_upgrading_fstrim), true); 7528 } catch (RemoteException e) { 7529 } 7530 } 7531 sm.runMaintenance(); 7532 } 7533 } else { 7534 Slog.e(TAG, "storageManager service unavailable!"); 7535 } 7536 } catch (RemoteException e) { 7537 // Can't happen; StorageManagerService is local 7538 } 7539 } 7540 7541 @Override 7542 public void updatePackagesIfNeeded() { 7543 enforceSystemOrRoot("Only the system can request package update"); 7544 7545 // We need to re-extract after an OTA. 7546 boolean causeUpgrade = isUpgrade(); 7547 7548 // First boot or factory reset. 7549 // Note: we also handle devices that are upgrading to N right now as if it is their 7550 // first boot, as they do not have profile data. 7551 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7552 7553 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7554 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7555 7556 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7557 return; 7558 } 7559 7560 List<PackageParser.Package> pkgs; 7561 synchronized (mPackages) { 7562 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7563 } 7564 7565 final long startTime = System.nanoTime(); 7566 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7567 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7568 7569 final int elapsedTimeSeconds = 7570 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7571 7572 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7573 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7574 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7575 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7576 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7577 } 7578 7579 /** 7580 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7581 * containing statistics about the invocation. The array consists of three elements, 7582 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7583 * and {@code numberOfPackagesFailed}. 7584 */ 7585 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7586 String compilerFilter) { 7587 7588 int numberOfPackagesVisited = 0; 7589 int numberOfPackagesOptimized = 0; 7590 int numberOfPackagesSkipped = 0; 7591 int numberOfPackagesFailed = 0; 7592 final int numberOfPackagesToDexopt = pkgs.size(); 7593 7594 for (PackageParser.Package pkg : pkgs) { 7595 numberOfPackagesVisited++; 7596 7597 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7598 if (DEBUG_DEXOPT) { 7599 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7600 } 7601 numberOfPackagesSkipped++; 7602 continue; 7603 } 7604 7605 if (DEBUG_DEXOPT) { 7606 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7607 numberOfPackagesToDexopt + ": " + pkg.packageName); 7608 } 7609 7610 if (showDialog) { 7611 try { 7612 ActivityManager.getService().showBootMessage( 7613 mContext.getResources().getString(R.string.android_upgrading_apk, 7614 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7615 } catch (RemoteException e) { 7616 } 7617 synchronized (mPackages) { 7618 mDexOptDialogShown = true; 7619 } 7620 } 7621 7622 // If the OTA updates a system app which was previously preopted to a non-preopted state 7623 // the app might end up being verified at runtime. That's because by default the apps 7624 // are verify-profile but for preopted apps there's no profile. 7625 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7626 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7627 // filter (by default interpret-only). 7628 // Note that at this stage unused apps are already filtered. 7629 if (isSystemApp(pkg) && 7630 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7631 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7632 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7633 } 7634 7635 // checkProfiles is false to avoid merging profiles during boot which 7636 // might interfere with background compilation (b/28612421). 7637 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7638 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7639 // trade-off worth doing to save boot time work. 7640 int dexOptStatus = performDexOptTraced(pkg.packageName, 7641 false /* checkProfiles */, 7642 compilerFilter, 7643 false /* force */); 7644 switch (dexOptStatus) { 7645 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7646 numberOfPackagesOptimized++; 7647 break; 7648 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7649 numberOfPackagesSkipped++; 7650 break; 7651 case PackageDexOptimizer.DEX_OPT_FAILED: 7652 numberOfPackagesFailed++; 7653 break; 7654 default: 7655 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7656 break; 7657 } 7658 } 7659 7660 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7661 numberOfPackagesFailed }; 7662 } 7663 7664 @Override 7665 public void notifyPackageUse(String packageName, int reason) { 7666 synchronized (mPackages) { 7667 PackageParser.Package p = mPackages.get(packageName); 7668 if (p == null) { 7669 return; 7670 } 7671 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7672 } 7673 } 7674 7675 @Override 7676 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 7677 int userId = UserHandle.getCallingUserId(); 7678 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 7679 if (ai == null) { 7680 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 7681 + loadingPackageName + ", user=" + userId); 7682 return; 7683 } 7684 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 7685 } 7686 7687 // TODO: this is not used nor needed. Delete it. 7688 @Override 7689 public boolean performDexOptIfNeeded(String packageName) { 7690 int dexOptStatus = performDexOptTraced(packageName, 7691 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7692 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7693 } 7694 7695 @Override 7696 public boolean performDexOpt(String packageName, 7697 boolean checkProfiles, int compileReason, boolean force) { 7698 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7699 getCompilerFilterForReason(compileReason), force); 7700 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7701 } 7702 7703 @Override 7704 public boolean performDexOptMode(String packageName, 7705 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7706 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7707 targetCompilerFilter, force); 7708 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7709 } 7710 7711 private int performDexOptTraced(String packageName, 7712 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7713 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7714 try { 7715 return performDexOptInternal(packageName, checkProfiles, 7716 targetCompilerFilter, force); 7717 } finally { 7718 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7719 } 7720 } 7721 7722 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7723 // if the package can now be considered up to date for the given filter. 7724 private int performDexOptInternal(String packageName, 7725 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7726 PackageParser.Package p; 7727 synchronized (mPackages) { 7728 p = mPackages.get(packageName); 7729 if (p == null) { 7730 // Package could not be found. Report failure. 7731 return PackageDexOptimizer.DEX_OPT_FAILED; 7732 } 7733 mPackageUsage.maybeWriteAsync(mPackages); 7734 mCompilerStats.maybeWriteAsync(); 7735 } 7736 long callingId = Binder.clearCallingIdentity(); 7737 try { 7738 synchronized (mInstallLock) { 7739 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7740 targetCompilerFilter, force); 7741 } 7742 } finally { 7743 Binder.restoreCallingIdentity(callingId); 7744 } 7745 } 7746 7747 public ArraySet<String> getOptimizablePackages() { 7748 ArraySet<String> pkgs = new ArraySet<String>(); 7749 synchronized (mPackages) { 7750 for (PackageParser.Package p : mPackages.values()) { 7751 if (PackageDexOptimizer.canOptimizePackage(p)) { 7752 pkgs.add(p.packageName); 7753 } 7754 } 7755 } 7756 return pkgs; 7757 } 7758 7759 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7760 boolean checkProfiles, String targetCompilerFilter, 7761 boolean force) { 7762 // Select the dex optimizer based on the force parameter. 7763 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7764 // allocate an object here. 7765 PackageDexOptimizer pdo = force 7766 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7767 : mPackageDexOptimizer; 7768 7769 // Optimize all dependencies first. Note: we ignore the return value and march on 7770 // on errors. 7771 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7772 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7773 if (!deps.isEmpty()) { 7774 for (PackageParser.Package depPackage : deps) { 7775 // TODO: Analyze and investigate if we (should) profile libraries. 7776 // Currently this will do a full compilation of the library by default. 7777 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7778 false /* checkProfiles */, 7779 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7780 getOrCreateCompilerPackageStats(depPackage)); 7781 } 7782 } 7783 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7784 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7785 } 7786 7787 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7788 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7789 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7790 Set<String> collectedNames = new HashSet<>(); 7791 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7792 7793 retValue.remove(p); 7794 7795 return retValue; 7796 } else { 7797 return Collections.emptyList(); 7798 } 7799 } 7800 7801 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7802 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7803 if (!collectedNames.contains(p.packageName)) { 7804 collectedNames.add(p.packageName); 7805 collected.add(p); 7806 7807 if (p.usesLibraries != null) { 7808 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7809 } 7810 if (p.usesOptionalLibraries != null) { 7811 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7812 collectedNames); 7813 } 7814 } 7815 } 7816 7817 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7818 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7819 for (String libName : libs) { 7820 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7821 if (libPkg != null) { 7822 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7823 } 7824 } 7825 } 7826 7827 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7828 synchronized (mPackages) { 7829 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7830 if (lib != null && lib.apk != null) { 7831 return mPackages.get(lib.apk); 7832 } 7833 } 7834 return null; 7835 } 7836 7837 public void shutdown() { 7838 mPackageUsage.writeNow(mPackages); 7839 mCompilerStats.writeNow(); 7840 } 7841 7842 @Override 7843 public void dumpProfiles(String packageName) { 7844 PackageParser.Package pkg; 7845 synchronized (mPackages) { 7846 pkg = mPackages.get(packageName); 7847 if (pkg == null) { 7848 throw new IllegalArgumentException("Unknown package: " + packageName); 7849 } 7850 } 7851 /* Only the shell, root, or the app user should be able to dump profiles. */ 7852 int callingUid = Binder.getCallingUid(); 7853 if (callingUid != Process.SHELL_UID && 7854 callingUid != Process.ROOT_UID && 7855 callingUid != pkg.applicationInfo.uid) { 7856 throw new SecurityException("dumpProfiles"); 7857 } 7858 7859 synchronized (mInstallLock) { 7860 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7861 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7862 try { 7863 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7864 String codePaths = TextUtils.join(";", allCodePaths); 7865 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 7866 } catch (InstallerException e) { 7867 Slog.w(TAG, "Failed to dump profiles", e); 7868 } 7869 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7870 } 7871 } 7872 7873 @Override 7874 public void forceDexOpt(String packageName) { 7875 enforceSystemOrRoot("forceDexOpt"); 7876 7877 PackageParser.Package pkg; 7878 synchronized (mPackages) { 7879 pkg = mPackages.get(packageName); 7880 if (pkg == null) { 7881 throw new IllegalArgumentException("Unknown package: " + packageName); 7882 } 7883 } 7884 7885 synchronized (mInstallLock) { 7886 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7887 7888 // Whoever is calling forceDexOpt wants a fully compiled package. 7889 // Don't use profiles since that may cause compilation to be skipped. 7890 final int res = performDexOptInternalWithDependenciesLI(pkg, 7891 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7892 true /* force */); 7893 7894 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7895 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7896 throw new IllegalStateException("Failed to dexopt: " + res); 7897 } 7898 } 7899 } 7900 7901 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7902 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7903 Slog.w(TAG, "Unable to update from " + oldPkg.name 7904 + " to " + newPkg.packageName 7905 + ": old package not in system partition"); 7906 return false; 7907 } else if (mPackages.get(oldPkg.name) != null) { 7908 Slog.w(TAG, "Unable to update from " + oldPkg.name 7909 + " to " + newPkg.packageName 7910 + ": old package still exists"); 7911 return false; 7912 } 7913 return true; 7914 } 7915 7916 void removeCodePathLI(File codePath) { 7917 if (codePath.isDirectory()) { 7918 try { 7919 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7920 } catch (InstallerException e) { 7921 Slog.w(TAG, "Failed to remove code path", e); 7922 } 7923 } else { 7924 codePath.delete(); 7925 } 7926 } 7927 7928 private int[] resolveUserIds(int userId) { 7929 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7930 } 7931 7932 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7933 if (pkg == null) { 7934 Slog.wtf(TAG, "Package was null!", new Throwable()); 7935 return; 7936 } 7937 clearAppDataLeafLIF(pkg, userId, flags); 7938 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7939 for (int i = 0; i < childCount; i++) { 7940 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7941 } 7942 } 7943 7944 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7945 final PackageSetting ps; 7946 synchronized (mPackages) { 7947 ps = mSettings.mPackages.get(pkg.packageName); 7948 } 7949 for (int realUserId : resolveUserIds(userId)) { 7950 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7951 try { 7952 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7953 ceDataInode); 7954 } catch (InstallerException e) { 7955 Slog.w(TAG, String.valueOf(e)); 7956 } 7957 } 7958 } 7959 7960 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7961 if (pkg == null) { 7962 Slog.wtf(TAG, "Package was null!", new Throwable()); 7963 return; 7964 } 7965 destroyAppDataLeafLIF(pkg, userId, flags); 7966 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7967 for (int i = 0; i < childCount; i++) { 7968 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7969 } 7970 } 7971 7972 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7973 final PackageSetting ps; 7974 synchronized (mPackages) { 7975 ps = mSettings.mPackages.get(pkg.packageName); 7976 } 7977 for (int realUserId : resolveUserIds(userId)) { 7978 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7979 try { 7980 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7981 ceDataInode); 7982 } catch (InstallerException e) { 7983 Slog.w(TAG, String.valueOf(e)); 7984 } 7985 } 7986 } 7987 7988 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7989 if (pkg == null) { 7990 Slog.wtf(TAG, "Package was null!", new Throwable()); 7991 return; 7992 } 7993 destroyAppProfilesLeafLIF(pkg); 7994 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7995 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7996 for (int i = 0; i < childCount; i++) { 7997 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7998 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7999 true /* removeBaseMarker */); 8000 } 8001 } 8002 8003 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 8004 boolean removeBaseMarker) { 8005 if (pkg.isForwardLocked()) { 8006 return; 8007 } 8008 8009 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 8010 try { 8011 path = PackageManagerServiceUtils.realpath(new File(path)); 8012 } catch (IOException e) { 8013 // TODO: Should we return early here ? 8014 Slog.w(TAG, "Failed to get canonical path", e); 8015 continue; 8016 } 8017 8018 final String useMarker = path.replace('/', '@'); 8019 for (int realUserId : resolveUserIds(userId)) { 8020 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 8021 if (removeBaseMarker) { 8022 File foreignUseMark = new File(profileDir, useMarker); 8023 if (foreignUseMark.exists()) { 8024 if (!foreignUseMark.delete()) { 8025 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8026 + pkg.packageName); 8027 } 8028 } 8029 } 8030 8031 File[] markers = profileDir.listFiles(); 8032 if (markers != null) { 8033 final String searchString = "@" + pkg.packageName + "@"; 8034 // We also delete all markers that contain the package name we're 8035 // uninstalling. These are associated with secondary dex-files belonging 8036 // to the package. Reconstructing the path of these dex files is messy 8037 // in general. 8038 for (File marker : markers) { 8039 if (marker.getName().indexOf(searchString) > 0) { 8040 if (!marker.delete()) { 8041 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8042 + pkg.packageName); 8043 } 8044 } 8045 } 8046 } 8047 } 8048 } 8049 } 8050 8051 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8052 try { 8053 mInstaller.destroyAppProfiles(pkg.packageName); 8054 } catch (InstallerException e) { 8055 Slog.w(TAG, String.valueOf(e)); 8056 } 8057 } 8058 8059 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8060 if (pkg == null) { 8061 Slog.wtf(TAG, "Package was null!", new Throwable()); 8062 return; 8063 } 8064 clearAppProfilesLeafLIF(pkg); 8065 // We don't remove the base foreign use marker when clearing profiles because 8066 // we will rename it when the app is updated. Unlike the actual profile contents, 8067 // the foreign use marker is good across installs. 8068 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 8069 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8070 for (int i = 0; i < childCount; i++) { 8071 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8072 } 8073 } 8074 8075 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8076 try { 8077 mInstaller.clearAppProfiles(pkg.packageName); 8078 } catch (InstallerException e) { 8079 Slog.w(TAG, String.valueOf(e)); 8080 } 8081 } 8082 8083 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8084 long lastUpdateTime) { 8085 // Set parent install/update time 8086 PackageSetting ps = (PackageSetting) pkg.mExtras; 8087 if (ps != null) { 8088 ps.firstInstallTime = firstInstallTime; 8089 ps.lastUpdateTime = lastUpdateTime; 8090 } 8091 // Set children install/update time 8092 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8093 for (int i = 0; i < childCount; i++) { 8094 PackageParser.Package childPkg = pkg.childPackages.get(i); 8095 ps = (PackageSetting) childPkg.mExtras; 8096 if (ps != null) { 8097 ps.firstInstallTime = firstInstallTime; 8098 ps.lastUpdateTime = lastUpdateTime; 8099 } 8100 } 8101 } 8102 8103 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8104 PackageParser.Package changingLib) { 8105 if (file.path != null) { 8106 usesLibraryFiles.add(file.path); 8107 return; 8108 } 8109 PackageParser.Package p = mPackages.get(file.apk); 8110 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8111 // If we are doing this while in the middle of updating a library apk, 8112 // then we need to make sure to use that new apk for determining the 8113 // dependencies here. (We haven't yet finished committing the new apk 8114 // to the package manager state.) 8115 if (p == null || p.packageName.equals(changingLib.packageName)) { 8116 p = changingLib; 8117 } 8118 } 8119 if (p != null) { 8120 usesLibraryFiles.addAll(p.getAllCodePaths()); 8121 } 8122 } 8123 8124 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8125 PackageParser.Package changingLib) throws PackageManagerException { 8126 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 8127 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 8128 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 8129 for (int i=0; i<N; i++) { 8130 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 8131 if (file == null) { 8132 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8133 "Package " + pkg.packageName + " requires unavailable shared library " 8134 + pkg.usesLibraries.get(i) + "; failing!"); 8135 } 8136 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 8137 } 8138 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 8139 for (int i=0; i<N; i++) { 8140 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 8141 if (file == null) { 8142 Slog.w(TAG, "Package " + pkg.packageName 8143 + " desires unavailable shared library " 8144 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 8145 } else { 8146 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 8147 } 8148 } 8149 N = usesLibraryFiles.size(); 8150 if (N > 0) { 8151 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 8152 } else { 8153 pkg.usesLibraryFiles = null; 8154 } 8155 } 8156 } 8157 8158 private static boolean hasString(List<String> list, List<String> which) { 8159 if (list == null) { 8160 return false; 8161 } 8162 for (int i=list.size()-1; i>=0; i--) { 8163 for (int j=which.size()-1; j>=0; j--) { 8164 if (which.get(j).equals(list.get(i))) { 8165 return true; 8166 } 8167 } 8168 } 8169 return false; 8170 } 8171 8172 private void updateAllSharedLibrariesLPw() { 8173 for (PackageParser.Package pkg : mPackages.values()) { 8174 try { 8175 updateSharedLibrariesLPr(pkg, null); 8176 } catch (PackageManagerException e) { 8177 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8178 } 8179 } 8180 } 8181 8182 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8183 PackageParser.Package changingPkg) { 8184 ArrayList<PackageParser.Package> res = null; 8185 for (PackageParser.Package pkg : mPackages.values()) { 8186 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 8187 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 8188 if (res == null) { 8189 res = new ArrayList<PackageParser.Package>(); 8190 } 8191 res.add(pkg); 8192 try { 8193 updateSharedLibrariesLPr(pkg, changingPkg); 8194 } catch (PackageManagerException e) { 8195 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8196 } 8197 } 8198 } 8199 return res; 8200 } 8201 8202 /** 8203 * Derive the value of the {@code cpuAbiOverride} based on the provided 8204 * value and an optional stored value from the package settings. 8205 */ 8206 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8207 String cpuAbiOverride = null; 8208 8209 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8210 cpuAbiOverride = null; 8211 } else if (abiOverride != null) { 8212 cpuAbiOverride = abiOverride; 8213 } else if (settings != null) { 8214 cpuAbiOverride = settings.cpuAbiOverrideString; 8215 } 8216 8217 return cpuAbiOverride; 8218 } 8219 8220 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8221 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 8222 throws PackageManagerException { 8223 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8224 // If the package has children and this is the first dive in the function 8225 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8226 // whether all packages (parent and children) would be successfully scanned 8227 // before the actual scan since scanning mutates internal state and we want 8228 // to atomically install the package and its children. 8229 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8230 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8231 scanFlags |= SCAN_CHECK_ONLY; 8232 } 8233 } else { 8234 scanFlags &= ~SCAN_CHECK_ONLY; 8235 } 8236 8237 final PackageParser.Package scannedPkg; 8238 try { 8239 // Scan the parent 8240 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8241 // Scan the children 8242 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8243 for (int i = 0; i < childCount; i++) { 8244 PackageParser.Package childPkg = pkg.childPackages.get(i); 8245 scanPackageLI(childPkg, policyFlags, 8246 scanFlags, currentTime, user); 8247 } 8248 } finally { 8249 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8250 } 8251 8252 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8253 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8254 } 8255 8256 return scannedPkg; 8257 } 8258 8259 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8260 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8261 boolean success = false; 8262 try { 8263 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8264 currentTime, user); 8265 success = true; 8266 return res; 8267 } finally { 8268 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8269 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8270 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8271 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8272 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8273 } 8274 } 8275 } 8276 8277 /** 8278 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8279 */ 8280 private static boolean apkHasCode(String fileName) { 8281 StrictJarFile jarFile = null; 8282 try { 8283 jarFile = new StrictJarFile(fileName, 8284 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8285 return jarFile.findEntry("classes.dex") != null; 8286 } catch (IOException ignore) { 8287 } finally { 8288 try { 8289 if (jarFile != null) { 8290 jarFile.close(); 8291 } 8292 } catch (IOException ignore) {} 8293 } 8294 return false; 8295 } 8296 8297 /** 8298 * Enforces code policy for the package. This ensures that if an APK has 8299 * declared hasCode="true" in its manifest that the APK actually contains 8300 * code. 8301 * 8302 * @throws PackageManagerException If bytecode could not be found when it should exist 8303 */ 8304 private static void assertCodePolicy(PackageParser.Package pkg) 8305 throws PackageManagerException { 8306 final boolean shouldHaveCode = 8307 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8308 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8309 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8310 "Package " + pkg.baseCodePath + " code is missing"); 8311 } 8312 8313 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8314 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8315 final boolean splitShouldHaveCode = 8316 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8317 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8318 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8319 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8320 } 8321 } 8322 } 8323 } 8324 8325 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8326 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8327 throws PackageManagerException { 8328 if (DEBUG_PACKAGE_SCANNING) { 8329 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8330 Log.d(TAG, "Scanning package " + pkg.packageName); 8331 } 8332 8333 applyPolicy(pkg, policyFlags); 8334 8335 assertPackageIsValid(pkg, policyFlags, scanFlags); 8336 8337 // Initialize package source and resource directories 8338 final File scanFile = new File(pkg.codePath); 8339 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8340 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8341 8342 SharedUserSetting suid = null; 8343 PackageSetting pkgSetting = null; 8344 8345 // Getting the package setting may have a side-effect, so if we 8346 // are only checking if scan would succeed, stash a copy of the 8347 // old setting to restore at the end. 8348 PackageSetting nonMutatedPs = null; 8349 8350 // We keep references to the derived CPU Abis from settings in oder to reuse 8351 // them in the case where we're not upgrading or booting for the first time. 8352 String primaryCpuAbiFromSettings = null; 8353 String secondaryCpuAbiFromSettings = null; 8354 8355 // writer 8356 synchronized (mPackages) { 8357 if (pkg.mSharedUserId != null) { 8358 // SIDE EFFECTS; may potentially allocate a new shared user 8359 suid = mSettings.getSharedUserLPw( 8360 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 8361 if (DEBUG_PACKAGE_SCANNING) { 8362 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8363 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8364 + "): packages=" + suid.packages); 8365 } 8366 } 8367 8368 // Check if we are renaming from an original package name. 8369 PackageSetting origPackage = null; 8370 String realName = null; 8371 if (pkg.mOriginalPackages != null) { 8372 // This package may need to be renamed to a previously 8373 // installed name. Let's check on that... 8374 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8375 if (pkg.mOriginalPackages.contains(renamed)) { 8376 // This package had originally been installed as the 8377 // original name, and we have already taken care of 8378 // transitioning to the new one. Just update the new 8379 // one to continue using the old name. 8380 realName = pkg.mRealPackage; 8381 if (!pkg.packageName.equals(renamed)) { 8382 // Callers into this function may have already taken 8383 // care of renaming the package; only do it here if 8384 // it is not already done. 8385 pkg.setPackageName(renamed); 8386 } 8387 } else { 8388 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8389 if ((origPackage = mSettings.getPackageLPr( 8390 pkg.mOriginalPackages.get(i))) != null) { 8391 // We do have the package already installed under its 8392 // original name... should we use it? 8393 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8394 // New package is not compatible with original. 8395 origPackage = null; 8396 continue; 8397 } else if (origPackage.sharedUser != null) { 8398 // Make sure uid is compatible between packages. 8399 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8400 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8401 + " to " + pkg.packageName + ": old uid " 8402 + origPackage.sharedUser.name 8403 + " differs from " + pkg.mSharedUserId); 8404 origPackage = null; 8405 continue; 8406 } 8407 // TODO: Add case when shared user id is added [b/28144775] 8408 } else { 8409 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8410 + pkg.packageName + " to old name " + origPackage.name); 8411 } 8412 break; 8413 } 8414 } 8415 } 8416 } 8417 8418 if (mTransferedPackages.contains(pkg.packageName)) { 8419 Slog.w(TAG, "Package " + pkg.packageName 8420 + " was transferred to another, but its .apk remains"); 8421 } 8422 8423 // See comments in nonMutatedPs declaration 8424 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8425 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8426 if (foundPs != null) { 8427 nonMutatedPs = new PackageSetting(foundPs); 8428 } 8429 } 8430 8431 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 8432 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8433 if (foundPs != null) { 8434 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 8435 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 8436 } 8437 } 8438 8439 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8440 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 8441 PackageManagerService.reportSettingsProblem(Log.WARN, 8442 "Package " + pkg.packageName + " shared user changed from " 8443 + (pkgSetting.sharedUser != null 8444 ? pkgSetting.sharedUser.name : "<nothing>") 8445 + " to " 8446 + (suid != null ? suid.name : "<nothing>") 8447 + "; replacing with new"); 8448 pkgSetting = null; 8449 } 8450 final PackageSetting oldPkgSetting = 8451 pkgSetting == null ? null : new PackageSetting(pkgSetting); 8452 final PackageSetting disabledPkgSetting = 8453 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8454 if (pkgSetting == null) { 8455 final String parentPackageName = (pkg.parentPackage != null) 8456 ? pkg.parentPackage.packageName : null; 8457 // REMOVE SharedUserSetting from method; update in a separate call 8458 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 8459 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 8460 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 8461 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 8462 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 8463 true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(), 8464 UserManagerService.getInstance()); 8465 // SIDE EFFECTS; updates system state; move elsewhere 8466 if (origPackage != null) { 8467 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 8468 } 8469 mSettings.addUserToSettingLPw(pkgSetting); 8470 } else { 8471 // REMOVE SharedUserSetting from method; update in a separate call. 8472 // 8473 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 8474 // secondaryCpuAbi are not known at this point so we always update them 8475 // to null here, only to reset them at a later point. 8476 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 8477 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 8478 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 8479 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 8480 UserManagerService.getInstance()); 8481 } 8482 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 8483 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 8484 8485 // SIDE EFFECTS; modifies system state; move elsewhere 8486 if (pkgSetting.origPackage != null) { 8487 // If we are first transitioning from an original package, 8488 // fix up the new package's name now. We need to do this after 8489 // looking up the package under its new name, so getPackageLP 8490 // can take care of fiddling things correctly. 8491 pkg.setPackageName(origPackage.name); 8492 8493 // File a report about this. 8494 String msg = "New package " + pkgSetting.realName 8495 + " renamed to replace old package " + pkgSetting.name; 8496 reportSettingsProblem(Log.WARN, msg); 8497 8498 // Make a note of it. 8499 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8500 mTransferedPackages.add(origPackage.name); 8501 } 8502 8503 // No longer need to retain this. 8504 pkgSetting.origPackage = null; 8505 } 8506 8507 // SIDE EFFECTS; modifies system state; move elsewhere 8508 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8509 // Make a note of it. 8510 mTransferedPackages.add(pkg.packageName); 8511 } 8512 8513 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8514 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8515 } 8516 8517 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8518 // Check all shared libraries and map to their actual file path. 8519 // We only do this here for apps not on a system dir, because those 8520 // are the only ones that can fail an install due to this. We 8521 // will take care of the system apps by updating all of their 8522 // library paths after the scan is done. 8523 updateSharedLibrariesLPr(pkg, null); 8524 } 8525 8526 if (mFoundPolicyFile) { 8527 SELinuxMMAC.assignSeinfoValue(pkg); 8528 } 8529 8530 pkg.applicationInfo.uid = pkgSetting.appId; 8531 pkg.mExtras = pkgSetting; 8532 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8533 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8534 // We just determined the app is signed correctly, so bring 8535 // over the latest parsed certs. 8536 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8537 } else { 8538 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8539 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8540 "Package " + pkg.packageName + " upgrade keys do not match the " 8541 + "previously installed version"); 8542 } else { 8543 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8544 String msg = "System package " + pkg.packageName 8545 + " signature changed; retaining data."; 8546 reportSettingsProblem(Log.WARN, msg); 8547 } 8548 } 8549 } else { 8550 try { 8551 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 8552 verifySignaturesLP(pkgSetting, pkg); 8553 // We just determined the app is signed correctly, so bring 8554 // over the latest parsed certs. 8555 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8556 } catch (PackageManagerException e) { 8557 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8558 throw e; 8559 } 8560 // The signature has changed, but this package is in the system 8561 // image... let's recover! 8562 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8563 // However... if this package is part of a shared user, but it 8564 // doesn't match the signature of the shared user, let's fail. 8565 // What this means is that you can't change the signatures 8566 // associated with an overall shared user, which doesn't seem all 8567 // that unreasonable. 8568 if (pkgSetting.sharedUser != null) { 8569 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8570 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8571 throw new PackageManagerException( 8572 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8573 "Signature mismatch for shared user: " 8574 + pkgSetting.sharedUser); 8575 } 8576 } 8577 // File a report about this. 8578 String msg = "System package " + pkg.packageName 8579 + " signature changed; retaining data."; 8580 reportSettingsProblem(Log.WARN, msg); 8581 } 8582 } 8583 8584 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8585 // This package wants to adopt ownership of permissions from 8586 // another package. 8587 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8588 final String origName = pkg.mAdoptPermissions.get(i); 8589 final PackageSetting orig = mSettings.getPackageLPr(origName); 8590 if (orig != null) { 8591 if (verifyPackageUpdateLPr(orig, pkg)) { 8592 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8593 + pkg.packageName); 8594 // SIDE EFFECTS; updates permissions system state; move elsewhere 8595 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8596 } 8597 } 8598 } 8599 } 8600 } 8601 8602 pkg.applicationInfo.processName = fixProcessName( 8603 pkg.applicationInfo.packageName, 8604 pkg.applicationInfo.processName); 8605 8606 if (pkg != mPlatformPackage) { 8607 // Get all of our default paths setup 8608 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8609 } 8610 8611 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8612 8613 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8614 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 8615 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 8616 derivePackageAbi( 8617 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 8618 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8619 8620 // Some system apps still use directory structure for native libraries 8621 // in which case we might end up not detecting abi solely based on apk 8622 // structure. Try to detect abi based on directory structure. 8623 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8624 pkg.applicationInfo.primaryCpuAbi == null) { 8625 setBundledAppAbisAndRoots(pkg, pkgSetting); 8626 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8627 } 8628 } else { 8629 // This is not a first boot or an upgrade, don't bother deriving the 8630 // ABI during the scan. Instead, trust the value that was stored in the 8631 // package setting. 8632 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 8633 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 8634 8635 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8636 8637 if (DEBUG_ABI_SELECTION) { 8638 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 8639 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 8640 pkg.applicationInfo.secondaryCpuAbi); 8641 } 8642 } 8643 } else { 8644 if ((scanFlags & SCAN_MOVE) != 0) { 8645 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8646 // but we already have this packages package info in the PackageSetting. We just 8647 // use that and derive the native library path based on the new codepath. 8648 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8649 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8650 } 8651 8652 // Set native library paths again. For moves, the path will be updated based on the 8653 // ABIs we've determined above. For non-moves, the path will be updated based on the 8654 // ABIs we determined during compilation, but the path will depend on the final 8655 // package path (after the rename away from the stage path). 8656 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8657 } 8658 8659 // This is a special case for the "system" package, where the ABI is 8660 // dictated by the zygote configuration (and init.rc). We should keep track 8661 // of this ABI so that we can deal with "normal" applications that run under 8662 // the same UID correctly. 8663 if (mPlatformPackage == pkg) { 8664 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8665 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8666 } 8667 8668 // If there's a mismatch between the abi-override in the package setting 8669 // and the abiOverride specified for the install. Warn about this because we 8670 // would've already compiled the app without taking the package setting into 8671 // account. 8672 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8673 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8674 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8675 " for package " + pkg.packageName); 8676 } 8677 } 8678 8679 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8680 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8681 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8682 8683 // Copy the derived override back to the parsed package, so that we can 8684 // update the package settings accordingly. 8685 pkg.cpuAbiOverride = cpuAbiOverride; 8686 8687 if (DEBUG_ABI_SELECTION) { 8688 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8689 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8690 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8691 } 8692 8693 // Push the derived path down into PackageSettings so we know what to 8694 // clean up at uninstall time. 8695 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8696 8697 if (DEBUG_ABI_SELECTION) { 8698 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8699 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8700 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8701 } 8702 8703 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 8704 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8705 // We don't do this here during boot because we can do it all 8706 // at once after scanning all existing packages. 8707 // 8708 // We also do this *before* we perform dexopt on this package, so that 8709 // we can avoid redundant dexopts, and also to make sure we've got the 8710 // code and package path correct. 8711 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 8712 } 8713 8714 if (mFactoryTest && pkg.requestedPermissions.contains( 8715 android.Manifest.permission.FACTORY_TEST)) { 8716 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8717 } 8718 8719 if (isSystemApp(pkg)) { 8720 pkgSetting.isOrphaned = true; 8721 } 8722 8723 // Take care of first install / last update times. 8724 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8725 if (currentTime != 0) { 8726 if (pkgSetting.firstInstallTime == 0) { 8727 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8728 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 8729 pkgSetting.lastUpdateTime = currentTime; 8730 } 8731 } else if (pkgSetting.firstInstallTime == 0) { 8732 // We need *something*. Take time time stamp of the file. 8733 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8734 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8735 if (scanFileTime != pkgSetting.timeStamp) { 8736 // A package on the system image has changed; consider this 8737 // to be an update. 8738 pkgSetting.lastUpdateTime = scanFileTime; 8739 } 8740 } 8741 pkgSetting.setTimeStamp(scanFileTime); 8742 8743 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8744 if (nonMutatedPs != null) { 8745 synchronized (mPackages) { 8746 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8747 } 8748 } 8749 } else { 8750 // Modify state for the given package setting 8751 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 8752 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 8753 } 8754 return pkg; 8755 } 8756 8757 /** 8758 * Applies policy to the parsed package based upon the given policy flags. 8759 * Ensures the package is in a good state. 8760 * <p> 8761 * Implementation detail: This method must NOT have any side effect. It would 8762 * ideally be static, but, it requires locks to read system state. 8763 */ 8764 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 8765 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8766 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8767 if (pkg.applicationInfo.isDirectBootAware()) { 8768 // we're direct boot aware; set for all components 8769 for (PackageParser.Service s : pkg.services) { 8770 s.info.encryptionAware = s.info.directBootAware = true; 8771 } 8772 for (PackageParser.Provider p : pkg.providers) { 8773 p.info.encryptionAware = p.info.directBootAware = true; 8774 } 8775 for (PackageParser.Activity a : pkg.activities) { 8776 a.info.encryptionAware = a.info.directBootAware = true; 8777 } 8778 for (PackageParser.Activity r : pkg.receivers) { 8779 r.info.encryptionAware = r.info.directBootAware = true; 8780 } 8781 } 8782 } else { 8783 // Only allow system apps to be flagged as core apps. 8784 pkg.coreApp = false; 8785 // clear flags not applicable to regular apps 8786 pkg.applicationInfo.privateFlags &= 8787 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8788 pkg.applicationInfo.privateFlags &= 8789 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8790 } 8791 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8792 8793 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8794 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8795 } 8796 8797 if (!isSystemApp(pkg)) { 8798 // Only system apps can use these features. 8799 pkg.mOriginalPackages = null; 8800 pkg.mRealPackage = null; 8801 pkg.mAdoptPermissions = null; 8802 } 8803 } 8804 8805 /** 8806 * Asserts the parsed package is valid according to teh given policy. If the 8807 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 8808 * <p> 8809 * Implementation detail: This method must NOT have any side effects. It would 8810 * ideally be static, but, it requires locks to read system state. 8811 * 8812 * @throws PackageManagerException If the package fails any of the validation checks 8813 */ 8814 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 8815 throws PackageManagerException { 8816 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8817 assertCodePolicy(pkg); 8818 } 8819 8820 if (pkg.applicationInfo.getCodePath() == null || 8821 pkg.applicationInfo.getResourcePath() == null) { 8822 // Bail out. The resource and code paths haven't been set. 8823 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8824 "Code and resource paths haven't been set correctly"); 8825 } 8826 8827 // Make sure we're not adding any bogus keyset info 8828 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8829 ksms.assertScannedPackageValid(pkg); 8830 8831 synchronized (mPackages) { 8832 // The special "android" package can only be defined once 8833 if (pkg.packageName.equals("android")) { 8834 if (mAndroidApplication != null) { 8835 Slog.w(TAG, "*************************************************"); 8836 Slog.w(TAG, "Core android package being redefined. Skipping."); 8837 Slog.w(TAG, " codePath=" + pkg.codePath); 8838 Slog.w(TAG, "*************************************************"); 8839 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8840 "Core android package being redefined. Skipping."); 8841 } 8842 } 8843 8844 // A package name must be unique; don't allow duplicates 8845 if (mPackages.containsKey(pkg.packageName) 8846 || mSharedLibraries.containsKey(pkg.packageName)) { 8847 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8848 "Application package " + pkg.packageName 8849 + " already installed. Skipping duplicate."); 8850 } 8851 8852 // Only privileged apps and updated privileged apps can add child packages. 8853 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8854 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8855 throw new PackageManagerException("Only privileged apps can add child " 8856 + "packages. Ignoring package " + pkg.packageName); 8857 } 8858 final int childCount = pkg.childPackages.size(); 8859 for (int i = 0; i < childCount; i++) { 8860 PackageParser.Package childPkg = pkg.childPackages.get(i); 8861 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8862 childPkg.packageName)) { 8863 throw new PackageManagerException("Can't override child of " 8864 + "another disabled app. Ignoring package " + pkg.packageName); 8865 } 8866 } 8867 } 8868 8869 // If we're only installing presumed-existing packages, require that the 8870 // scanned APK is both already known and at the path previously established 8871 // for it. Previously unknown packages we pick up normally, but if we have an 8872 // a priori expectation about this package's install presence, enforce it. 8873 // With a singular exception for new system packages. When an OTA contains 8874 // a new system package, we allow the codepath to change from a system location 8875 // to the user-installed location. If we don't allow this change, any newer, 8876 // user-installed version of the application will be ignored. 8877 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8878 if (mExpectingBetter.containsKey(pkg.packageName)) { 8879 logCriticalInfo(Log.WARN, 8880 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8881 } else { 8882 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 8883 if (known != null) { 8884 if (DEBUG_PACKAGE_SCANNING) { 8885 Log.d(TAG, "Examining " + pkg.codePath 8886 + " and requiring known paths " + known.codePathString 8887 + " & " + known.resourcePathString); 8888 } 8889 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8890 || !pkg.applicationInfo.getResourcePath().equals( 8891 known.resourcePathString)) { 8892 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8893 "Application package " + pkg.packageName 8894 + " found at " + pkg.applicationInfo.getCodePath() 8895 + " but expected at " + known.codePathString 8896 + "; ignoring."); 8897 } 8898 } 8899 } 8900 } 8901 8902 // Verify that this new package doesn't have any content providers 8903 // that conflict with existing packages. Only do this if the 8904 // package isn't already installed, since we don't want to break 8905 // things that are installed. 8906 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8907 final int N = pkg.providers.size(); 8908 int i; 8909 for (i=0; i<N; i++) { 8910 PackageParser.Provider p = pkg.providers.get(i); 8911 if (p.info.authority != null) { 8912 String names[] = p.info.authority.split(";"); 8913 for (int j = 0; j < names.length; j++) { 8914 if (mProvidersByAuthority.containsKey(names[j])) { 8915 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8916 final String otherPackageName = 8917 ((other != null && other.getComponentName() != null) ? 8918 other.getComponentName().getPackageName() : "?"); 8919 throw new PackageManagerException( 8920 INSTALL_FAILED_CONFLICTING_PROVIDER, 8921 "Can't install because provider name " + names[j] 8922 + " (in package " + pkg.applicationInfo.packageName 8923 + ") is already used by " + otherPackageName); 8924 } 8925 } 8926 } 8927 } 8928 } 8929 } 8930 } 8931 8932 /** 8933 * Adds a scanned package to the system. When this method is finished, the package will 8934 * be available for query, resolution, etc... 8935 */ 8936 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 8937 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 8938 final String pkgName = pkg.packageName; 8939 if (mCustomResolverComponentName != null && 8940 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8941 setUpCustomResolverActivity(pkg); 8942 } 8943 8944 if (pkg.packageName.equals("android")) { 8945 synchronized (mPackages) { 8946 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8947 // Set up information for our fall-back user intent resolution activity. 8948 mPlatformPackage = pkg; 8949 pkg.mVersionCode = mSdkVersion; 8950 mAndroidApplication = pkg.applicationInfo; 8951 8952 if (!mResolverReplaced) { 8953 mResolveActivity.applicationInfo = mAndroidApplication; 8954 mResolveActivity.name = ResolverActivity.class.getName(); 8955 mResolveActivity.packageName = mAndroidApplication.packageName; 8956 mResolveActivity.processName = "system:ui"; 8957 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8958 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8959 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8960 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8961 mResolveActivity.exported = true; 8962 mResolveActivity.enabled = true; 8963 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8964 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8965 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8966 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8967 | ActivityInfo.CONFIG_ORIENTATION 8968 | ActivityInfo.CONFIG_KEYBOARD 8969 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8970 mResolveInfo.activityInfo = mResolveActivity; 8971 mResolveInfo.priority = 0; 8972 mResolveInfo.preferredOrder = 0; 8973 mResolveInfo.match = 0; 8974 mResolveComponentName = new ComponentName( 8975 mAndroidApplication.packageName, mResolveActivity.name); 8976 } 8977 } 8978 } 8979 } 8980 8981 ArrayList<PackageParser.Package> clientLibPkgs = null; 8982 // writer 8983 synchronized (mPackages) { 8984 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8985 // Only system apps can add new shared libraries. 8986 if (pkg.libraryNames != null) { 8987 for (int i=0; i<pkg.libraryNames.size(); i++) { 8988 String name = pkg.libraryNames.get(i); 8989 boolean allowed = false; 8990 if (pkg.isUpdatedSystemApp()) { 8991 // New library entries can only be added through the 8992 // system image. This is important to get rid of a lot 8993 // of nasty edge cases: for example if we allowed a non- 8994 // system update of the app to add a library, then uninstalling 8995 // the update would make the library go away, and assumptions 8996 // we made such as through app install filtering would now 8997 // have allowed apps on the device which aren't compatible 8998 // with it. Better to just have the restriction here, be 8999 // conservative, and create many fewer cases that can negatively 9000 // impact the user experience. 9001 final PackageSetting sysPs = mSettings 9002 .getDisabledSystemPkgLPr(pkg.packageName); 9003 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 9004 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 9005 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 9006 allowed = true; 9007 break; 9008 } 9009 } 9010 } 9011 } else { 9012 allowed = true; 9013 } 9014 if (allowed) { 9015 if (!mSharedLibraries.containsKey(name)) { 9016 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 9017 } else if (!name.equals(pkg.packageName)) { 9018 Slog.w(TAG, "Package " + pkg.packageName + " library " 9019 + name + " already exists; skipping"); 9020 } 9021 } else { 9022 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 9023 + name + " that is not declared on system image; skipping"); 9024 } 9025 } 9026 if ((scanFlags & SCAN_BOOTING) == 0) { 9027 // If we are not booting, we need to update any applications 9028 // that are clients of our shared library. If we are booting, 9029 // this will all be done once the scan is complete. 9030 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 9031 } 9032 } 9033 } 9034 } 9035 9036 if ((scanFlags & SCAN_BOOTING) != 0) { 9037 // No apps can run during boot scan, so they don't need to be frozen 9038 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 9039 // Caller asked to not kill app, so it's probably not frozen 9040 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 9041 // Caller asked us to ignore frozen check for some reason; they 9042 // probably didn't know the package name 9043 } else { 9044 // We're doing major surgery on this package, so it better be frozen 9045 // right now to keep it from launching 9046 checkPackageFrozen(pkgName); 9047 } 9048 9049 // Also need to kill any apps that are dependent on the library. 9050 if (clientLibPkgs != null) { 9051 for (int i=0; i<clientLibPkgs.size(); i++) { 9052 PackageParser.Package clientPkg = clientLibPkgs.get(i); 9053 killApplication(clientPkg.applicationInfo.packageName, 9054 clientPkg.applicationInfo.uid, "update lib"); 9055 } 9056 } 9057 9058 // writer 9059 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 9060 9061 boolean createIdmapFailed = false; 9062 synchronized (mPackages) { 9063 // We don't expect installation to fail beyond this point 9064 9065 if (pkgSetting.pkg != null) { 9066 // Note that |user| might be null during the initial boot scan. If a codePath 9067 // for an app has changed during a boot scan, it's due to an app update that's 9068 // part of the system partition and marker changes must be applied to all users. 9069 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 9070 final int[] userIds = resolveUserIds(userId); 9071 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 9072 } 9073 9074 // Add the new setting to mSettings 9075 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 9076 // Add the new setting to mPackages 9077 mPackages.put(pkg.applicationInfo.packageName, pkg); 9078 // Make sure we don't accidentally delete its data. 9079 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 9080 while (iter.hasNext()) { 9081 PackageCleanItem item = iter.next(); 9082 if (pkgName.equals(item.packageName)) { 9083 iter.remove(); 9084 } 9085 } 9086 9087 // Add the package's KeySets to the global KeySetManagerService 9088 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9089 ksms.addScannedPackageLPw(pkg); 9090 9091 int N = pkg.providers.size(); 9092 StringBuilder r = null; 9093 int i; 9094 for (i=0; i<N; i++) { 9095 PackageParser.Provider p = pkg.providers.get(i); 9096 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 9097 p.info.processName); 9098 mProviders.addProvider(p); 9099 p.syncable = p.info.isSyncable; 9100 if (p.info.authority != null) { 9101 String names[] = p.info.authority.split(";"); 9102 p.info.authority = null; 9103 for (int j = 0; j < names.length; j++) { 9104 if (j == 1 && p.syncable) { 9105 // We only want the first authority for a provider to possibly be 9106 // syncable, so if we already added this provider using a different 9107 // authority clear the syncable flag. We copy the provider before 9108 // changing it because the mProviders object contains a reference 9109 // to a provider that we don't want to change. 9110 // Only do this for the second authority since the resulting provider 9111 // object can be the same for all future authorities for this provider. 9112 p = new PackageParser.Provider(p); 9113 p.syncable = false; 9114 } 9115 if (!mProvidersByAuthority.containsKey(names[j])) { 9116 mProvidersByAuthority.put(names[j], p); 9117 if (p.info.authority == null) { 9118 p.info.authority = names[j]; 9119 } else { 9120 p.info.authority = p.info.authority + ";" + names[j]; 9121 } 9122 if (DEBUG_PACKAGE_SCANNING) { 9123 if (chatty) 9124 Log.d(TAG, "Registered content provider: " + names[j] 9125 + ", className = " + p.info.name + ", isSyncable = " 9126 + p.info.isSyncable); 9127 } 9128 } else { 9129 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9130 Slog.w(TAG, "Skipping provider name " + names[j] + 9131 " (in package " + pkg.applicationInfo.packageName + 9132 "): name already used by " 9133 + ((other != null && other.getComponentName() != null) 9134 ? other.getComponentName().getPackageName() : "?")); 9135 } 9136 } 9137 } 9138 if (chatty) { 9139 if (r == null) { 9140 r = new StringBuilder(256); 9141 } else { 9142 r.append(' '); 9143 } 9144 r.append(p.info.name); 9145 } 9146 } 9147 if (r != null) { 9148 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 9149 } 9150 9151 N = pkg.services.size(); 9152 r = null; 9153 for (i=0; i<N; i++) { 9154 PackageParser.Service s = pkg.services.get(i); 9155 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 9156 s.info.processName); 9157 mServices.addService(s); 9158 if (chatty) { 9159 if (r == null) { 9160 r = new StringBuilder(256); 9161 } else { 9162 r.append(' '); 9163 } 9164 r.append(s.info.name); 9165 } 9166 } 9167 if (r != null) { 9168 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 9169 } 9170 9171 N = pkg.receivers.size(); 9172 r = null; 9173 for (i=0; i<N; i++) { 9174 PackageParser.Activity a = pkg.receivers.get(i); 9175 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9176 a.info.processName); 9177 mReceivers.addActivity(a, "receiver"); 9178 if (chatty) { 9179 if (r == null) { 9180 r = new StringBuilder(256); 9181 } else { 9182 r.append(' '); 9183 } 9184 r.append(a.info.name); 9185 } 9186 } 9187 if (r != null) { 9188 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 9189 } 9190 9191 N = pkg.activities.size(); 9192 r = null; 9193 for (i=0; i<N; i++) { 9194 PackageParser.Activity a = pkg.activities.get(i); 9195 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9196 a.info.processName); 9197 mActivities.addActivity(a, "activity"); 9198 if (chatty) { 9199 if (r == null) { 9200 r = new StringBuilder(256); 9201 } else { 9202 r.append(' '); 9203 } 9204 r.append(a.info.name); 9205 } 9206 } 9207 if (r != null) { 9208 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 9209 } 9210 9211 N = pkg.permissionGroups.size(); 9212 r = null; 9213 for (i=0; i<N; i++) { 9214 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 9215 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 9216 final String curPackageName = cur == null ? null : cur.info.packageName; 9217 // Dont allow ephemeral apps to define new permission groups. 9218 if (pkg.applicationInfo.isEphemeralApp()) { 9219 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9220 + pg.info.packageName 9221 + " ignored: ephemeral apps cannot define new permission groups."); 9222 continue; 9223 } 9224 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 9225 if (cur == null || isPackageUpdate) { 9226 mPermissionGroups.put(pg.info.name, pg); 9227 if (chatty) { 9228 if (r == null) { 9229 r = new StringBuilder(256); 9230 } else { 9231 r.append(' '); 9232 } 9233 if (isPackageUpdate) { 9234 r.append("UPD:"); 9235 } 9236 r.append(pg.info.name); 9237 } 9238 } else { 9239 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9240 + pg.info.packageName + " ignored: original from " 9241 + cur.info.packageName); 9242 if (chatty) { 9243 if (r == null) { 9244 r = new StringBuilder(256); 9245 } else { 9246 r.append(' '); 9247 } 9248 r.append("DUP:"); 9249 r.append(pg.info.name); 9250 } 9251 } 9252 } 9253 if (r != null) { 9254 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 9255 } 9256 9257 N = pkg.permissions.size(); 9258 r = null; 9259 for (i=0; i<N; i++) { 9260 PackageParser.Permission p = pkg.permissions.get(i); 9261 9262 // Dont allow ephemeral apps to define new permissions. 9263 if (pkg.applicationInfo.isEphemeralApp()) { 9264 Slog.w(TAG, "Permission " + p.info.name + " from package " 9265 + p.info.packageName 9266 + " ignored: ephemeral apps cannot define new permissions."); 9267 continue; 9268 } 9269 9270 // Assume by default that we did not install this permission into the system. 9271 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 9272 9273 // Now that permission groups have a special meaning, we ignore permission 9274 // groups for legacy apps to prevent unexpected behavior. In particular, 9275 // permissions for one app being granted to someone just becase they happen 9276 // to be in a group defined by another app (before this had no implications). 9277 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 9278 p.group = mPermissionGroups.get(p.info.group); 9279 // Warn for a permission in an unknown group. 9280 if (p.info.group != null && p.group == null) { 9281 Slog.w(TAG, "Permission " + p.info.name + " from package " 9282 + p.info.packageName + " in an unknown group " + p.info.group); 9283 } 9284 } 9285 9286 ArrayMap<String, BasePermission> permissionMap = 9287 p.tree ? mSettings.mPermissionTrees 9288 : mSettings.mPermissions; 9289 BasePermission bp = permissionMap.get(p.info.name); 9290 9291 // Allow system apps to redefine non-system permissions 9292 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 9293 final boolean currentOwnerIsSystem = (bp.perm != null 9294 && isSystemApp(bp.perm.owner)); 9295 if (isSystemApp(p.owner)) { 9296 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 9297 // It's a built-in permission and no owner, take ownership now 9298 bp.packageSetting = pkgSetting; 9299 bp.perm = p; 9300 bp.uid = pkg.applicationInfo.uid; 9301 bp.sourcePackage = p.info.packageName; 9302 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9303 } else if (!currentOwnerIsSystem) { 9304 String msg = "New decl " + p.owner + " of permission " 9305 + p.info.name + " is system; overriding " + bp.sourcePackage; 9306 reportSettingsProblem(Log.WARN, msg); 9307 bp = null; 9308 } 9309 } 9310 } 9311 9312 if (bp == null) { 9313 bp = new BasePermission(p.info.name, p.info.packageName, 9314 BasePermission.TYPE_NORMAL); 9315 permissionMap.put(p.info.name, bp); 9316 } 9317 9318 if (bp.perm == null) { 9319 if (bp.sourcePackage == null 9320 || bp.sourcePackage.equals(p.info.packageName)) { 9321 BasePermission tree = findPermissionTreeLP(p.info.name); 9322 if (tree == null 9323 || tree.sourcePackage.equals(p.info.packageName)) { 9324 bp.packageSetting = pkgSetting; 9325 bp.perm = p; 9326 bp.uid = pkg.applicationInfo.uid; 9327 bp.sourcePackage = p.info.packageName; 9328 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9329 if (chatty) { 9330 if (r == null) { 9331 r = new StringBuilder(256); 9332 } else { 9333 r.append(' '); 9334 } 9335 r.append(p.info.name); 9336 } 9337 } else { 9338 Slog.w(TAG, "Permission " + p.info.name + " from package " 9339 + p.info.packageName + " ignored: base tree " 9340 + tree.name + " is from package " 9341 + tree.sourcePackage); 9342 } 9343 } else { 9344 Slog.w(TAG, "Permission " + p.info.name + " from package " 9345 + p.info.packageName + " ignored: original from " 9346 + bp.sourcePackage); 9347 } 9348 } else if (chatty) { 9349 if (r == null) { 9350 r = new StringBuilder(256); 9351 } else { 9352 r.append(' '); 9353 } 9354 r.append("DUP:"); 9355 r.append(p.info.name); 9356 } 9357 if (bp.perm == p) { 9358 bp.protectionLevel = p.info.protectionLevel; 9359 } 9360 } 9361 9362 if (r != null) { 9363 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 9364 } 9365 9366 N = pkg.instrumentation.size(); 9367 r = null; 9368 for (i=0; i<N; i++) { 9369 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9370 a.info.packageName = pkg.applicationInfo.packageName; 9371 a.info.sourceDir = pkg.applicationInfo.sourceDir; 9372 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 9373 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 9374 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 9375 a.info.dataDir = pkg.applicationInfo.dataDir; 9376 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 9377 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 9378 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 9379 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 9380 mInstrumentation.put(a.getComponentName(), a); 9381 if (chatty) { 9382 if (r == null) { 9383 r = new StringBuilder(256); 9384 } else { 9385 r.append(' '); 9386 } 9387 r.append(a.info.name); 9388 } 9389 } 9390 if (r != null) { 9391 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9392 } 9393 9394 if (pkg.protectedBroadcasts != null) { 9395 N = pkg.protectedBroadcasts.size(); 9396 for (i=0; i<N; i++) { 9397 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9398 } 9399 } 9400 9401 // Create idmap files for pairs of (packages, overlay packages). 9402 // Note: "android", ie framework-res.apk, is handled by native layers. 9403 if (pkg.mOverlayTarget != null) { 9404 // This is an overlay package. 9405 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9406 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9407 mOverlays.put(pkg.mOverlayTarget, 9408 new ArrayMap<String, PackageParser.Package>()); 9409 } 9410 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9411 map.put(pkg.packageName, pkg); 9412 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9413 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9414 createIdmapFailed = true; 9415 } 9416 } 9417 } else if (mOverlays.containsKey(pkg.packageName) && 9418 !pkg.packageName.equals("android")) { 9419 // This is a regular package, with one or more known overlay packages. 9420 createIdmapsForPackageLI(pkg); 9421 } 9422 } 9423 9424 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9425 9426 if (createIdmapFailed) { 9427 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9428 "scanPackageLI failed to createIdmap"); 9429 } 9430 } 9431 9432 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9433 PackageParser.Package update, int[] userIds) { 9434 if (existing.applicationInfo == null || update.applicationInfo == null) { 9435 // This isn't due to an app installation. 9436 return; 9437 } 9438 9439 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9440 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9441 9442 // The codePath hasn't changed, so there's nothing for us to do. 9443 if (Objects.equals(oldCodePath, newCodePath)) { 9444 return; 9445 } 9446 9447 File canonicalNewCodePath; 9448 try { 9449 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9450 } catch (IOException e) { 9451 Slog.w(TAG, "Failed to get canonical path.", e); 9452 return; 9453 } 9454 9455 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9456 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9457 // that the last component of the path (i.e, the name) doesn't need canonicalization 9458 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9459 // but may change in the future. Hopefully this function won't exist at that point. 9460 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9461 oldCodePath.getName()); 9462 9463 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9464 // with "@". 9465 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9466 if (!oldMarkerPrefix.endsWith("@")) { 9467 oldMarkerPrefix += "@"; 9468 } 9469 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9470 if (!newMarkerPrefix.endsWith("@")) { 9471 newMarkerPrefix += "@"; 9472 } 9473 9474 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9475 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9476 for (String updatedPath : updatedPaths) { 9477 String updatedPathName = new File(updatedPath).getName(); 9478 markerSuffixes.add(updatedPathName.replace('/', '@')); 9479 } 9480 9481 for (int userId : userIds) { 9482 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9483 9484 for (String markerSuffix : markerSuffixes) { 9485 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9486 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9487 if (oldForeignUseMark.exists()) { 9488 try { 9489 Os.rename(oldForeignUseMark.getAbsolutePath(), 9490 newForeignUseMark.getAbsolutePath()); 9491 } catch (ErrnoException e) { 9492 Slog.w(TAG, "Failed to rename foreign use marker", e); 9493 oldForeignUseMark.delete(); 9494 } 9495 } 9496 } 9497 } 9498 } 9499 9500 /** 9501 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9502 * is derived purely on the basis of the contents of {@code scanFile} and 9503 * {@code cpuAbiOverride}. 9504 * 9505 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9506 */ 9507 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9508 String cpuAbiOverride, boolean extractLibs, 9509 File appLib32InstallDir) 9510 throws PackageManagerException { 9511 // Give ourselves some initial paths; we'll come back for another 9512 // pass once we've determined ABI below. 9513 setNativeLibraryPaths(pkg, appLib32InstallDir); 9514 9515 // We would never need to extract libs for forward-locked and external packages, 9516 // since the container service will do it for us. We shouldn't attempt to 9517 // extract libs from system app when it was not updated. 9518 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9519 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9520 extractLibs = false; 9521 } 9522 9523 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9524 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9525 9526 NativeLibraryHelper.Handle handle = null; 9527 try { 9528 handle = NativeLibraryHelper.Handle.create(pkg); 9529 // TODO(multiArch): This can be null for apps that didn't go through the 9530 // usual installation process. We can calculate it again, like we 9531 // do during install time. 9532 // 9533 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9534 // unnecessary. 9535 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9536 9537 // Null out the abis so that they can be recalculated. 9538 pkg.applicationInfo.primaryCpuAbi = null; 9539 pkg.applicationInfo.secondaryCpuAbi = null; 9540 if (isMultiArch(pkg.applicationInfo)) { 9541 // Warn if we've set an abiOverride for multi-lib packages.. 9542 // By definition, we need to copy both 32 and 64 bit libraries for 9543 // such packages. 9544 if (pkg.cpuAbiOverride != null 9545 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9546 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9547 } 9548 9549 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9550 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9551 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9552 if (extractLibs) { 9553 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9554 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9555 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9556 useIsaSpecificSubdirs); 9557 } else { 9558 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9559 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9560 } 9561 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9562 } 9563 9564 maybeThrowExceptionForMultiArchCopy( 9565 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9566 9567 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9568 if (extractLibs) { 9569 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9570 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9571 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9572 useIsaSpecificSubdirs); 9573 } else { 9574 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9575 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9576 } 9577 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9578 } 9579 9580 maybeThrowExceptionForMultiArchCopy( 9581 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9582 9583 if (abi64 >= 0) { 9584 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9585 } 9586 9587 if (abi32 >= 0) { 9588 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9589 if (abi64 >= 0) { 9590 if (pkg.use32bitAbi) { 9591 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9592 pkg.applicationInfo.primaryCpuAbi = abi; 9593 } else { 9594 pkg.applicationInfo.secondaryCpuAbi = abi; 9595 } 9596 } else { 9597 pkg.applicationInfo.primaryCpuAbi = abi; 9598 } 9599 } 9600 9601 } else { 9602 String[] abiList = (cpuAbiOverride != null) ? 9603 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9604 9605 // Enable gross and lame hacks for apps that are built with old 9606 // SDK tools. We must scan their APKs for renderscript bitcode and 9607 // not launch them if it's present. Don't bother checking on devices 9608 // that don't have 64 bit support. 9609 boolean needsRenderScriptOverride = false; 9610 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9611 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9612 abiList = Build.SUPPORTED_32_BIT_ABIS; 9613 needsRenderScriptOverride = true; 9614 } 9615 9616 final int copyRet; 9617 if (extractLibs) { 9618 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9619 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9620 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9621 } else { 9622 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9623 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9624 } 9625 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9626 9627 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9628 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9629 "Error unpackaging native libs for app, errorCode=" + copyRet); 9630 } 9631 9632 if (copyRet >= 0) { 9633 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9634 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9635 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9636 } else if (needsRenderScriptOverride) { 9637 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9638 } 9639 } 9640 } catch (IOException ioe) { 9641 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9642 } finally { 9643 IoUtils.closeQuietly(handle); 9644 } 9645 9646 // Now that we've calculated the ABIs and determined if it's an internal app, 9647 // we will go ahead and populate the nativeLibraryPath. 9648 setNativeLibraryPaths(pkg, appLib32InstallDir); 9649 } 9650 9651 /** 9652 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9653 * i.e, so that all packages can be run inside a single process if required. 9654 * 9655 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9656 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9657 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9658 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9659 * updating a package that belongs to a shared user. 9660 * 9661 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9662 * adds unnecessary complexity. 9663 */ 9664 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9665 PackageParser.Package scannedPackage) { 9666 String requiredInstructionSet = null; 9667 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9668 requiredInstructionSet = VMRuntime.getInstructionSet( 9669 scannedPackage.applicationInfo.primaryCpuAbi); 9670 } 9671 9672 PackageSetting requirer = null; 9673 for (PackageSetting ps : packagesForUser) { 9674 // If packagesForUser contains scannedPackage, we skip it. This will happen 9675 // when scannedPackage is an update of an existing package. Without this check, 9676 // we will never be able to change the ABI of any package belonging to a shared 9677 // user, even if it's compatible with other packages. 9678 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9679 if (ps.primaryCpuAbiString == null) { 9680 continue; 9681 } 9682 9683 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9684 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9685 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9686 // this but there's not much we can do. 9687 String errorMessage = "Instruction set mismatch, " 9688 + ((requirer == null) ? "[caller]" : requirer) 9689 + " requires " + requiredInstructionSet + " whereas " + ps 9690 + " requires " + instructionSet; 9691 Slog.w(TAG, errorMessage); 9692 } 9693 9694 if (requiredInstructionSet == null) { 9695 requiredInstructionSet = instructionSet; 9696 requirer = ps; 9697 } 9698 } 9699 } 9700 9701 if (requiredInstructionSet != null) { 9702 String adjustedAbi; 9703 if (requirer != null) { 9704 // requirer != null implies that either scannedPackage was null or that scannedPackage 9705 // did not require an ABI, in which case we have to adjust scannedPackage to match 9706 // the ABI of the set (which is the same as requirer's ABI) 9707 adjustedAbi = requirer.primaryCpuAbiString; 9708 if (scannedPackage != null) { 9709 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9710 } 9711 } else { 9712 // requirer == null implies that we're updating all ABIs in the set to 9713 // match scannedPackage. 9714 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9715 } 9716 9717 for (PackageSetting ps : packagesForUser) { 9718 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9719 if (ps.primaryCpuAbiString != null) { 9720 continue; 9721 } 9722 9723 ps.primaryCpuAbiString = adjustedAbi; 9724 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9725 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9726 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9727 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9728 + " (requirer=" 9729 + (requirer == null ? "null" : requirer.pkg.packageName) 9730 + ", scannedPackage=" 9731 + (scannedPackage != null ? scannedPackage.packageName : "null") 9732 + ")"); 9733 try { 9734 mInstaller.rmdex(ps.codePathString, 9735 getDexCodeInstructionSet(getPreferredInstructionSet())); 9736 } catch (InstallerException ignored) { 9737 } 9738 } 9739 } 9740 } 9741 } 9742 } 9743 9744 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9745 synchronized (mPackages) { 9746 mResolverReplaced = true; 9747 // Set up information for custom user intent resolution activity. 9748 mResolveActivity.applicationInfo = pkg.applicationInfo; 9749 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9750 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9751 mResolveActivity.processName = pkg.applicationInfo.packageName; 9752 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9753 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9754 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9755 mResolveActivity.theme = 0; 9756 mResolveActivity.exported = true; 9757 mResolveActivity.enabled = true; 9758 mResolveInfo.activityInfo = mResolveActivity; 9759 mResolveInfo.priority = 0; 9760 mResolveInfo.preferredOrder = 0; 9761 mResolveInfo.match = 0; 9762 mResolveComponentName = mCustomResolverComponentName; 9763 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9764 mResolveComponentName); 9765 } 9766 } 9767 9768 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9769 if (installerComponent == null) { 9770 if (DEBUG_EPHEMERAL) { 9771 Slog.d(TAG, "Clear ephemeral installer activity"); 9772 } 9773 mEphemeralInstallerActivity.applicationInfo = null; 9774 return; 9775 } 9776 9777 if (DEBUG_EPHEMERAL) { 9778 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 9779 } 9780 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9781 // Set up information for ephemeral installer activity 9782 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9783 mEphemeralInstallerActivity.name = installerComponent.getClassName(); 9784 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9785 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9786 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9787 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9788 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9789 mEphemeralInstallerActivity.theme = 0; 9790 mEphemeralInstallerActivity.exported = true; 9791 mEphemeralInstallerActivity.enabled = true; 9792 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9793 mEphemeralInstallerInfo.priority = 0; 9794 mEphemeralInstallerInfo.preferredOrder = 1; 9795 mEphemeralInstallerInfo.isDefault = true; 9796 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9797 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9798 } 9799 9800 private static String calculateBundledApkRoot(final String codePathString) { 9801 final File codePath = new File(codePathString); 9802 final File codeRoot; 9803 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9804 codeRoot = Environment.getRootDirectory(); 9805 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9806 codeRoot = Environment.getOemDirectory(); 9807 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9808 codeRoot = Environment.getVendorDirectory(); 9809 } else { 9810 // Unrecognized code path; take its top real segment as the apk root: 9811 // e.g. /something/app/blah.apk => /something 9812 try { 9813 File f = codePath.getCanonicalFile(); 9814 File parent = f.getParentFile(); // non-null because codePath is a file 9815 File tmp; 9816 while ((tmp = parent.getParentFile()) != null) { 9817 f = parent; 9818 parent = tmp; 9819 } 9820 codeRoot = f; 9821 Slog.w(TAG, "Unrecognized code path " 9822 + codePath + " - using " + codeRoot); 9823 } catch (IOException e) { 9824 // Can't canonicalize the code path -- shenanigans? 9825 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9826 return Environment.getRootDirectory().getPath(); 9827 } 9828 } 9829 return codeRoot.getPath(); 9830 } 9831 9832 /** 9833 * Derive and set the location of native libraries for the given package, 9834 * which varies depending on where and how the package was installed. 9835 */ 9836 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 9837 final ApplicationInfo info = pkg.applicationInfo; 9838 final String codePath = pkg.codePath; 9839 final File codeFile = new File(codePath); 9840 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9841 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9842 9843 info.nativeLibraryRootDir = null; 9844 info.nativeLibraryRootRequiresIsa = false; 9845 info.nativeLibraryDir = null; 9846 info.secondaryNativeLibraryDir = null; 9847 9848 if (isApkFile(codeFile)) { 9849 // Monolithic install 9850 if (bundledApp) { 9851 // If "/system/lib64/apkname" exists, assume that is the per-package 9852 // native library directory to use; otherwise use "/system/lib/apkname". 9853 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9854 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9855 getPrimaryInstructionSet(info)); 9856 9857 // This is a bundled system app so choose the path based on the ABI. 9858 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9859 // is just the default path. 9860 final String apkName = deriveCodePathName(codePath); 9861 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9862 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9863 apkName).getAbsolutePath(); 9864 9865 if (info.secondaryCpuAbi != null) { 9866 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9867 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9868 secondaryLibDir, apkName).getAbsolutePath(); 9869 } 9870 } else if (asecApp) { 9871 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9872 .getAbsolutePath(); 9873 } else { 9874 final String apkName = deriveCodePathName(codePath); 9875 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 9876 .getAbsolutePath(); 9877 } 9878 9879 info.nativeLibraryRootRequiresIsa = false; 9880 info.nativeLibraryDir = info.nativeLibraryRootDir; 9881 } else { 9882 // Cluster install 9883 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9884 info.nativeLibraryRootRequiresIsa = true; 9885 9886 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9887 getPrimaryInstructionSet(info)).getAbsolutePath(); 9888 9889 if (info.secondaryCpuAbi != null) { 9890 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9891 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9892 } 9893 } 9894 } 9895 9896 /** 9897 * Calculate the abis and roots for a bundled app. These can uniquely 9898 * be determined from the contents of the system partition, i.e whether 9899 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9900 * of this information, and instead assume that the system was built 9901 * sensibly. 9902 */ 9903 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9904 PackageSetting pkgSetting) { 9905 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9906 9907 // If "/system/lib64/apkname" exists, assume that is the per-package 9908 // native library directory to use; otherwise use "/system/lib/apkname". 9909 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9910 setBundledAppAbi(pkg, apkRoot, apkName); 9911 // pkgSetting might be null during rescan following uninstall of updates 9912 // to a bundled app, so accommodate that possibility. The settings in 9913 // that case will be established later from the parsed package. 9914 // 9915 // If the settings aren't null, sync them up with what we've just derived. 9916 // note that apkRoot isn't stored in the package settings. 9917 if (pkgSetting != null) { 9918 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9919 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9920 } 9921 } 9922 9923 /** 9924 * Deduces the ABI of a bundled app and sets the relevant fields on the 9925 * parsed pkg object. 9926 * 9927 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9928 * under which system libraries are installed. 9929 * @param apkName the name of the installed package. 9930 */ 9931 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9932 final File codeFile = new File(pkg.codePath); 9933 9934 final boolean has64BitLibs; 9935 final boolean has32BitLibs; 9936 if (isApkFile(codeFile)) { 9937 // Monolithic install 9938 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9939 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9940 } else { 9941 // Cluster install 9942 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9943 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9944 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9945 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9946 has64BitLibs = (new File(rootDir, isa)).exists(); 9947 } else { 9948 has64BitLibs = false; 9949 } 9950 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9951 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9952 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9953 has32BitLibs = (new File(rootDir, isa)).exists(); 9954 } else { 9955 has32BitLibs = false; 9956 } 9957 } 9958 9959 if (has64BitLibs && !has32BitLibs) { 9960 // The package has 64 bit libs, but not 32 bit libs. Its primary 9961 // ABI should be 64 bit. We can safely assume here that the bundled 9962 // native libraries correspond to the most preferred ABI in the list. 9963 9964 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9965 pkg.applicationInfo.secondaryCpuAbi = null; 9966 } else if (has32BitLibs && !has64BitLibs) { 9967 // The package has 32 bit libs but not 64 bit libs. Its primary 9968 // ABI should be 32 bit. 9969 9970 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9971 pkg.applicationInfo.secondaryCpuAbi = null; 9972 } else if (has32BitLibs && has64BitLibs) { 9973 // The application has both 64 and 32 bit bundled libraries. We check 9974 // here that the app declares multiArch support, and warn if it doesn't. 9975 // 9976 // We will be lenient here and record both ABIs. The primary will be the 9977 // ABI that's higher on the list, i.e, a device that's configured to prefer 9978 // 64 bit apps will see a 64 bit primary ABI, 9979 9980 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9981 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9982 } 9983 9984 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9985 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9986 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9987 } else { 9988 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9989 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9990 } 9991 } else { 9992 pkg.applicationInfo.primaryCpuAbi = null; 9993 pkg.applicationInfo.secondaryCpuAbi = null; 9994 } 9995 } 9996 9997 private void killApplication(String pkgName, int appId, String reason) { 9998 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9999 } 10000 10001 private void killApplication(String pkgName, int appId, int userId, String reason) { 10002 // Request the ActivityManager to kill the process(only for existing packages) 10003 // so that we do not end up in a confused state while the user is still using the older 10004 // version of the application while the new one gets installed. 10005 final long token = Binder.clearCallingIdentity(); 10006 try { 10007 IActivityManager am = ActivityManager.getService(); 10008 if (am != null) { 10009 try { 10010 am.killApplication(pkgName, appId, userId, reason); 10011 } catch (RemoteException e) { 10012 } 10013 } 10014 } finally { 10015 Binder.restoreCallingIdentity(token); 10016 } 10017 } 10018 10019 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10020 // Remove the parent package setting 10021 PackageSetting ps = (PackageSetting) pkg.mExtras; 10022 if (ps != null) { 10023 removePackageLI(ps, chatty); 10024 } 10025 // Remove the child package setting 10026 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10027 for (int i = 0; i < childCount; i++) { 10028 PackageParser.Package childPkg = pkg.childPackages.get(i); 10029 ps = (PackageSetting) childPkg.mExtras; 10030 if (ps != null) { 10031 removePackageLI(ps, chatty); 10032 } 10033 } 10034 } 10035 10036 void removePackageLI(PackageSetting ps, boolean chatty) { 10037 if (DEBUG_INSTALL) { 10038 if (chatty) 10039 Log.d(TAG, "Removing package " + ps.name); 10040 } 10041 10042 // writer 10043 synchronized (mPackages) { 10044 mPackages.remove(ps.name); 10045 final PackageParser.Package pkg = ps.pkg; 10046 if (pkg != null) { 10047 cleanPackageDataStructuresLILPw(pkg, chatty); 10048 } 10049 } 10050 } 10051 10052 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10053 if (DEBUG_INSTALL) { 10054 if (chatty) 10055 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10056 } 10057 10058 // writer 10059 synchronized (mPackages) { 10060 // Remove the parent package 10061 mPackages.remove(pkg.applicationInfo.packageName); 10062 cleanPackageDataStructuresLILPw(pkg, chatty); 10063 10064 // Remove the child packages 10065 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10066 for (int i = 0; i < childCount; i++) { 10067 PackageParser.Package childPkg = pkg.childPackages.get(i); 10068 mPackages.remove(childPkg.applicationInfo.packageName); 10069 cleanPackageDataStructuresLILPw(childPkg, chatty); 10070 } 10071 } 10072 } 10073 10074 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10075 int N = pkg.providers.size(); 10076 StringBuilder r = null; 10077 int i; 10078 for (i=0; i<N; i++) { 10079 PackageParser.Provider p = pkg.providers.get(i); 10080 mProviders.removeProvider(p); 10081 if (p.info.authority == null) { 10082 10083 /* There was another ContentProvider with this authority when 10084 * this app was installed so this authority is null, 10085 * Ignore it as we don't have to unregister the provider. 10086 */ 10087 continue; 10088 } 10089 String names[] = p.info.authority.split(";"); 10090 for (int j = 0; j < names.length; j++) { 10091 if (mProvidersByAuthority.get(names[j]) == p) { 10092 mProvidersByAuthority.remove(names[j]); 10093 if (DEBUG_REMOVE) { 10094 if (chatty) 10095 Log.d(TAG, "Unregistered content provider: " + names[j] 10096 + ", className = " + p.info.name + ", isSyncable = " 10097 + p.info.isSyncable); 10098 } 10099 } 10100 } 10101 if (DEBUG_REMOVE && chatty) { 10102 if (r == null) { 10103 r = new StringBuilder(256); 10104 } else { 10105 r.append(' '); 10106 } 10107 r.append(p.info.name); 10108 } 10109 } 10110 if (r != null) { 10111 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 10112 } 10113 10114 N = pkg.services.size(); 10115 r = null; 10116 for (i=0; i<N; i++) { 10117 PackageParser.Service s = pkg.services.get(i); 10118 mServices.removeService(s); 10119 if (chatty) { 10120 if (r == null) { 10121 r = new StringBuilder(256); 10122 } else { 10123 r.append(' '); 10124 } 10125 r.append(s.info.name); 10126 } 10127 } 10128 if (r != null) { 10129 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 10130 } 10131 10132 N = pkg.receivers.size(); 10133 r = null; 10134 for (i=0; i<N; i++) { 10135 PackageParser.Activity a = pkg.receivers.get(i); 10136 mReceivers.removeActivity(a, "receiver"); 10137 if (DEBUG_REMOVE && chatty) { 10138 if (r == null) { 10139 r = new StringBuilder(256); 10140 } else { 10141 r.append(' '); 10142 } 10143 r.append(a.info.name); 10144 } 10145 } 10146 if (r != null) { 10147 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 10148 } 10149 10150 N = pkg.activities.size(); 10151 r = null; 10152 for (i=0; i<N; i++) { 10153 PackageParser.Activity a = pkg.activities.get(i); 10154 mActivities.removeActivity(a, "activity"); 10155 if (DEBUG_REMOVE && chatty) { 10156 if (r == null) { 10157 r = new StringBuilder(256); 10158 } else { 10159 r.append(' '); 10160 } 10161 r.append(a.info.name); 10162 } 10163 } 10164 if (r != null) { 10165 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 10166 } 10167 10168 N = pkg.permissions.size(); 10169 r = null; 10170 for (i=0; i<N; i++) { 10171 PackageParser.Permission p = pkg.permissions.get(i); 10172 BasePermission bp = mSettings.mPermissions.get(p.info.name); 10173 if (bp == null) { 10174 bp = mSettings.mPermissionTrees.get(p.info.name); 10175 } 10176 if (bp != null && bp.perm == p) { 10177 bp.perm = null; 10178 if (DEBUG_REMOVE && chatty) { 10179 if (r == null) { 10180 r = new StringBuilder(256); 10181 } else { 10182 r.append(' '); 10183 } 10184 r.append(p.info.name); 10185 } 10186 } 10187 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10188 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 10189 if (appOpPkgs != null) { 10190 appOpPkgs.remove(pkg.packageName); 10191 } 10192 } 10193 } 10194 if (r != null) { 10195 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10196 } 10197 10198 N = pkg.requestedPermissions.size(); 10199 r = null; 10200 for (i=0; i<N; i++) { 10201 String perm = pkg.requestedPermissions.get(i); 10202 BasePermission bp = mSettings.mPermissions.get(perm); 10203 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10204 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 10205 if (appOpPkgs != null) { 10206 appOpPkgs.remove(pkg.packageName); 10207 if (appOpPkgs.isEmpty()) { 10208 mAppOpPermissionPackages.remove(perm); 10209 } 10210 } 10211 } 10212 } 10213 if (r != null) { 10214 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10215 } 10216 10217 N = pkg.instrumentation.size(); 10218 r = null; 10219 for (i=0; i<N; i++) { 10220 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10221 mInstrumentation.remove(a.getComponentName()); 10222 if (DEBUG_REMOVE && chatty) { 10223 if (r == null) { 10224 r = new StringBuilder(256); 10225 } else { 10226 r.append(' '); 10227 } 10228 r.append(a.info.name); 10229 } 10230 } 10231 if (r != null) { 10232 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 10233 } 10234 10235 r = null; 10236 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 10237 // Only system apps can hold shared libraries. 10238 if (pkg.libraryNames != null) { 10239 for (i=0; i<pkg.libraryNames.size(); i++) { 10240 String name = pkg.libraryNames.get(i); 10241 SharedLibraryEntry cur = mSharedLibraries.get(name); 10242 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 10243 mSharedLibraries.remove(name); 10244 if (DEBUG_REMOVE && chatty) { 10245 if (r == null) { 10246 r = new StringBuilder(256); 10247 } else { 10248 r.append(' '); 10249 } 10250 r.append(name); 10251 } 10252 } 10253 } 10254 } 10255 } 10256 if (r != null) { 10257 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 10258 } 10259 } 10260 10261 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 10262 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 10263 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 10264 return true; 10265 } 10266 } 10267 return false; 10268 } 10269 10270 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 10271 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 10272 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 10273 10274 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 10275 // Update the parent permissions 10276 updatePermissionsLPw(pkg.packageName, pkg, flags); 10277 // Update the child permissions 10278 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10279 for (int i = 0; i < childCount; i++) { 10280 PackageParser.Package childPkg = pkg.childPackages.get(i); 10281 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 10282 } 10283 } 10284 10285 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 10286 int flags) { 10287 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 10288 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 10289 } 10290 10291 private void updatePermissionsLPw(String changingPkg, 10292 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 10293 // Make sure there are no dangling permission trees. 10294 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 10295 while (it.hasNext()) { 10296 final BasePermission bp = it.next(); 10297 if (bp.packageSetting == null) { 10298 // We may not yet have parsed the package, so just see if 10299 // we still know about its settings. 10300 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10301 } 10302 if (bp.packageSetting == null) { 10303 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 10304 + " from package " + bp.sourcePackage); 10305 it.remove(); 10306 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10307 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10308 Slog.i(TAG, "Removing old permission tree: " + bp.name 10309 + " from package " + bp.sourcePackage); 10310 flags |= UPDATE_PERMISSIONS_ALL; 10311 it.remove(); 10312 } 10313 } 10314 } 10315 10316 // Make sure all dynamic permissions have been assigned to a package, 10317 // and make sure there are no dangling permissions. 10318 it = mSettings.mPermissions.values().iterator(); 10319 while (it.hasNext()) { 10320 final BasePermission bp = it.next(); 10321 if (bp.type == BasePermission.TYPE_DYNAMIC) { 10322 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 10323 + bp.name + " pkg=" + bp.sourcePackage 10324 + " info=" + bp.pendingInfo); 10325 if (bp.packageSetting == null && bp.pendingInfo != null) { 10326 final BasePermission tree = findPermissionTreeLP(bp.name); 10327 if (tree != null && tree.perm != null) { 10328 bp.packageSetting = tree.packageSetting; 10329 bp.perm = new PackageParser.Permission(tree.perm.owner, 10330 new PermissionInfo(bp.pendingInfo)); 10331 bp.perm.info.packageName = tree.perm.info.packageName; 10332 bp.perm.info.name = bp.name; 10333 bp.uid = tree.uid; 10334 } 10335 } 10336 } 10337 if (bp.packageSetting == null) { 10338 // We may not yet have parsed the package, so just see if 10339 // we still know about its settings. 10340 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10341 } 10342 if (bp.packageSetting == null) { 10343 Slog.w(TAG, "Removing dangling permission: " + bp.name 10344 + " from package " + bp.sourcePackage); 10345 it.remove(); 10346 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10347 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10348 Slog.i(TAG, "Removing old permission: " + bp.name 10349 + " from package " + bp.sourcePackage); 10350 flags |= UPDATE_PERMISSIONS_ALL; 10351 it.remove(); 10352 } 10353 } 10354 } 10355 10356 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 10357 // Now update the permissions for all packages, in particular 10358 // replace the granted permissions of the system packages. 10359 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 10360 for (PackageParser.Package pkg : mPackages.values()) { 10361 if (pkg != pkgInfo) { 10362 // Only replace for packages on requested volume 10363 final String volumeUuid = getVolumeUuidForPackage(pkg); 10364 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 10365 && Objects.equals(replaceVolumeUuid, volumeUuid); 10366 grantPermissionsLPw(pkg, replace, changingPkg); 10367 } 10368 } 10369 } 10370 10371 if (pkgInfo != null) { 10372 // Only replace for packages on requested volume 10373 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 10374 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 10375 && Objects.equals(replaceVolumeUuid, volumeUuid); 10376 grantPermissionsLPw(pkgInfo, replace, changingPkg); 10377 } 10378 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10379 } 10380 10381 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 10382 String packageOfInterest) { 10383 // IMPORTANT: There are two types of permissions: install and runtime. 10384 // Install time permissions are granted when the app is installed to 10385 // all device users and users added in the future. Runtime permissions 10386 // are granted at runtime explicitly to specific users. Normal and signature 10387 // protected permissions are install time permissions. Dangerous permissions 10388 // are install permissions if the app's target SDK is Lollipop MR1 or older, 10389 // otherwise they are runtime permissions. This function does not manage 10390 // runtime permissions except for the case an app targeting Lollipop MR1 10391 // being upgraded to target a newer SDK, in which case dangerous permissions 10392 // are transformed from install time to runtime ones. 10393 10394 final PackageSetting ps = (PackageSetting) pkg.mExtras; 10395 if (ps == null) { 10396 return; 10397 } 10398 10399 PermissionsState permissionsState = ps.getPermissionsState(); 10400 PermissionsState origPermissions = permissionsState; 10401 10402 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10403 10404 boolean runtimePermissionsRevoked = false; 10405 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10406 10407 boolean changedInstallPermission = false; 10408 10409 if (replace) { 10410 ps.installPermissionsFixed = false; 10411 if (!ps.isSharedUser()) { 10412 origPermissions = new PermissionsState(permissionsState); 10413 permissionsState.reset(); 10414 } else { 10415 // We need to know only about runtime permission changes since the 10416 // calling code always writes the install permissions state but 10417 // the runtime ones are written only if changed. The only cases of 10418 // changed runtime permissions here are promotion of an install to 10419 // runtime and revocation of a runtime from a shared user. 10420 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10421 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10422 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10423 runtimePermissionsRevoked = true; 10424 } 10425 } 10426 } 10427 10428 permissionsState.setGlobalGids(mGlobalGids); 10429 10430 final int N = pkg.requestedPermissions.size(); 10431 for (int i=0; i<N; i++) { 10432 final String name = pkg.requestedPermissions.get(i); 10433 final BasePermission bp = mSettings.mPermissions.get(name); 10434 10435 if (DEBUG_INSTALL) { 10436 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10437 } 10438 10439 if (bp == null || bp.packageSetting == null) { 10440 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10441 Slog.w(TAG, "Unknown permission " + name 10442 + " in package " + pkg.packageName); 10443 } 10444 continue; 10445 } 10446 10447 10448 // Limit ephemeral apps to ephemeral allowed permissions. 10449 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 10450 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 10451 + pkg.packageName); 10452 continue; 10453 } 10454 10455 final String perm = bp.name; 10456 boolean allowedSig = false; 10457 int grant = GRANT_DENIED; 10458 10459 // Keep track of app op permissions. 10460 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10461 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10462 if (pkgs == null) { 10463 pkgs = new ArraySet<>(); 10464 mAppOpPermissionPackages.put(bp.name, pkgs); 10465 } 10466 pkgs.add(pkg.packageName); 10467 } 10468 10469 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10470 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10471 >= Build.VERSION_CODES.M; 10472 switch (level) { 10473 case PermissionInfo.PROTECTION_NORMAL: { 10474 // For all apps normal permissions are install time ones. 10475 grant = GRANT_INSTALL; 10476 } break; 10477 10478 case PermissionInfo.PROTECTION_DANGEROUS: { 10479 // If a permission review is required for legacy apps we represent 10480 // their permissions as always granted runtime ones since we need 10481 // to keep the review required permission flag per user while an 10482 // install permission's state is shared across all users. 10483 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 10484 // For legacy apps dangerous permissions are install time ones. 10485 grant = GRANT_INSTALL; 10486 } else if (origPermissions.hasInstallPermission(bp.name)) { 10487 // For legacy apps that became modern, install becomes runtime. 10488 grant = GRANT_UPGRADE; 10489 } else if (mPromoteSystemApps 10490 && isSystemApp(ps) 10491 && mExistingSystemPackages.contains(ps.name)) { 10492 // For legacy system apps, install becomes runtime. 10493 // We cannot check hasInstallPermission() for system apps since those 10494 // permissions were granted implicitly and not persisted pre-M. 10495 grant = GRANT_UPGRADE; 10496 } else { 10497 // For modern apps keep runtime permissions unchanged. 10498 grant = GRANT_RUNTIME; 10499 } 10500 } break; 10501 10502 case PermissionInfo.PROTECTION_SIGNATURE: { 10503 // For all apps signature permissions are install time ones. 10504 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10505 if (allowedSig) { 10506 grant = GRANT_INSTALL; 10507 } 10508 } break; 10509 } 10510 10511 if (DEBUG_INSTALL) { 10512 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10513 } 10514 10515 if (grant != GRANT_DENIED) { 10516 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10517 // If this is an existing, non-system package, then 10518 // we can't add any new permissions to it. 10519 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10520 // Except... if this is a permission that was added 10521 // to the platform (note: need to only do this when 10522 // updating the platform). 10523 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10524 grant = GRANT_DENIED; 10525 } 10526 } 10527 } 10528 10529 switch (grant) { 10530 case GRANT_INSTALL: { 10531 // Revoke this as runtime permission to handle the case of 10532 // a runtime permission being downgraded to an install one. 10533 // Also in permission review mode we keep dangerous permissions 10534 // for legacy apps 10535 for (int userId : UserManagerService.getInstance().getUserIds()) { 10536 if (origPermissions.getRuntimePermissionState( 10537 bp.name, userId) != null) { 10538 // Revoke the runtime permission and clear the flags. 10539 origPermissions.revokeRuntimePermission(bp, userId); 10540 origPermissions.updatePermissionFlags(bp, userId, 10541 PackageManager.MASK_PERMISSION_FLAGS, 0); 10542 // If we revoked a permission permission, we have to write. 10543 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10544 changedRuntimePermissionUserIds, userId); 10545 } 10546 } 10547 // Grant an install permission. 10548 if (permissionsState.grantInstallPermission(bp) != 10549 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10550 changedInstallPermission = true; 10551 } 10552 } break; 10553 10554 case GRANT_RUNTIME: { 10555 // Grant previously granted runtime permissions. 10556 for (int userId : UserManagerService.getInstance().getUserIds()) { 10557 PermissionState permissionState = origPermissions 10558 .getRuntimePermissionState(bp.name, userId); 10559 int flags = permissionState != null 10560 ? permissionState.getFlags() : 0; 10561 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10562 if (permissionsState.grantRuntimePermission(bp, userId) == 10563 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10564 // If we cannot put the permission as it was, we have to write. 10565 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10566 changedRuntimePermissionUserIds, userId); 10567 } 10568 // If the app supports runtime permissions no need for a review. 10569 if (mPermissionReviewRequired 10570 && appSupportsRuntimePermissions 10571 && (flags & PackageManager 10572 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10573 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10574 // Since we changed the flags, we have to write. 10575 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10576 changedRuntimePermissionUserIds, userId); 10577 } 10578 } else if (mPermissionReviewRequired 10579 && !appSupportsRuntimePermissions) { 10580 // For legacy apps that need a permission review, every new 10581 // runtime permission is granted but it is pending a review. 10582 // We also need to review only platform defined runtime 10583 // permissions as these are the only ones the platform knows 10584 // how to disable the API to simulate revocation as legacy 10585 // apps don't expect to run with revoked permissions. 10586 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10587 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10588 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10589 // We changed the flags, hence have to write. 10590 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10591 changedRuntimePermissionUserIds, userId); 10592 } 10593 } 10594 if (permissionsState.grantRuntimePermission(bp, userId) 10595 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10596 // We changed the permission, hence have to write. 10597 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10598 changedRuntimePermissionUserIds, userId); 10599 } 10600 } 10601 // Propagate the permission flags. 10602 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10603 } 10604 } break; 10605 10606 case GRANT_UPGRADE: { 10607 // Grant runtime permissions for a previously held install permission. 10608 PermissionState permissionState = origPermissions 10609 .getInstallPermissionState(bp.name); 10610 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10611 10612 if (origPermissions.revokeInstallPermission(bp) 10613 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10614 // We will be transferring the permission flags, so clear them. 10615 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10616 PackageManager.MASK_PERMISSION_FLAGS, 0); 10617 changedInstallPermission = true; 10618 } 10619 10620 // If the permission is not to be promoted to runtime we ignore it and 10621 // also its other flags as they are not applicable to install permissions. 10622 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10623 for (int userId : currentUserIds) { 10624 if (permissionsState.grantRuntimePermission(bp, userId) != 10625 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10626 // Transfer the permission flags. 10627 permissionsState.updatePermissionFlags(bp, userId, 10628 flags, flags); 10629 // If we granted the permission, we have to write. 10630 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10631 changedRuntimePermissionUserIds, userId); 10632 } 10633 } 10634 } 10635 } break; 10636 10637 default: { 10638 if (packageOfInterest == null 10639 || packageOfInterest.equals(pkg.packageName)) { 10640 Slog.w(TAG, "Not granting permission " + perm 10641 + " to package " + pkg.packageName 10642 + " because it was previously installed without"); 10643 } 10644 } break; 10645 } 10646 } else { 10647 if (permissionsState.revokeInstallPermission(bp) != 10648 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10649 // Also drop the permission flags. 10650 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10651 PackageManager.MASK_PERMISSION_FLAGS, 0); 10652 changedInstallPermission = true; 10653 Slog.i(TAG, "Un-granting permission " + perm 10654 + " from package " + pkg.packageName 10655 + " (protectionLevel=" + bp.protectionLevel 10656 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10657 + ")"); 10658 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10659 // Don't print warning for app op permissions, since it is fine for them 10660 // not to be granted, there is a UI for the user to decide. 10661 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10662 Slog.w(TAG, "Not granting permission " + perm 10663 + " to package " + pkg.packageName 10664 + " (protectionLevel=" + bp.protectionLevel 10665 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10666 + ")"); 10667 } 10668 } 10669 } 10670 } 10671 10672 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10673 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10674 // This is the first that we have heard about this package, so the 10675 // permissions we have now selected are fixed until explicitly 10676 // changed. 10677 ps.installPermissionsFixed = true; 10678 } 10679 10680 // Persist the runtime permissions state for users with changes. If permissions 10681 // were revoked because no app in the shared user declares them we have to 10682 // write synchronously to avoid losing runtime permissions state. 10683 for (int userId : changedRuntimePermissionUserIds) { 10684 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10685 } 10686 } 10687 10688 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10689 boolean allowed = false; 10690 final int NP = PackageParser.NEW_PERMISSIONS.length; 10691 for (int ip=0; ip<NP; ip++) { 10692 final PackageParser.NewPermissionInfo npi 10693 = PackageParser.NEW_PERMISSIONS[ip]; 10694 if (npi.name.equals(perm) 10695 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10696 allowed = true; 10697 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10698 + pkg.packageName); 10699 break; 10700 } 10701 } 10702 return allowed; 10703 } 10704 10705 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10706 BasePermission bp, PermissionsState origPermissions) { 10707 boolean privilegedPermission = (bp.protectionLevel 10708 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 10709 boolean privappPermissionsDisable = 10710 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 10711 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 10712 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 10713 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 10714 && !platformPackage && platformPermission) { 10715 ArraySet<String> wlPermissions = SystemConfig.getInstance() 10716 .getPrivAppPermissions(pkg.packageName); 10717 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 10718 if (!whitelisted) { 10719 Slog.w(TAG, "Privileged permission " + perm + " for package " 10720 + pkg.packageName + " - not in privapp-permissions whitelist"); 10721 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 10722 return false; 10723 } 10724 } 10725 } 10726 boolean allowed = (compareSignatures( 10727 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10728 == PackageManager.SIGNATURE_MATCH) 10729 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10730 == PackageManager.SIGNATURE_MATCH); 10731 if (!allowed && privilegedPermission) { 10732 if (isSystemApp(pkg)) { 10733 // For updated system applications, a system permission 10734 // is granted only if it had been defined by the original application. 10735 if (pkg.isUpdatedSystemApp()) { 10736 final PackageSetting sysPs = mSettings 10737 .getDisabledSystemPkgLPr(pkg.packageName); 10738 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10739 // If the original was granted this permission, we take 10740 // that grant decision as read and propagate it to the 10741 // update. 10742 if (sysPs.isPrivileged()) { 10743 allowed = true; 10744 } 10745 } else { 10746 // The system apk may have been updated with an older 10747 // version of the one on the data partition, but which 10748 // granted a new system permission that it didn't have 10749 // before. In this case we do want to allow the app to 10750 // now get the new permission if the ancestral apk is 10751 // privileged to get it. 10752 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10753 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10754 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10755 allowed = true; 10756 break; 10757 } 10758 } 10759 } 10760 // Also if a privileged parent package on the system image or any of 10761 // its children requested a privileged permission, the updated child 10762 // packages can also get the permission. 10763 if (pkg.parentPackage != null) { 10764 final PackageSetting disabledSysParentPs = mSettings 10765 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10766 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10767 && disabledSysParentPs.isPrivileged()) { 10768 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10769 allowed = true; 10770 } else if (disabledSysParentPs.pkg.childPackages != null) { 10771 final int count = disabledSysParentPs.pkg.childPackages.size(); 10772 for (int i = 0; i < count; i++) { 10773 PackageParser.Package disabledSysChildPkg = 10774 disabledSysParentPs.pkg.childPackages.get(i); 10775 if (isPackageRequestingPermission(disabledSysChildPkg, 10776 perm)) { 10777 allowed = true; 10778 break; 10779 } 10780 } 10781 } 10782 } 10783 } 10784 } 10785 } else { 10786 allowed = isPrivilegedApp(pkg); 10787 } 10788 } 10789 } 10790 if (!allowed) { 10791 if (!allowed && (bp.protectionLevel 10792 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10793 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10794 // If this was a previously normal/dangerous permission that got moved 10795 // to a system permission as part of the runtime permission redesign, then 10796 // we still want to blindly grant it to old apps. 10797 allowed = true; 10798 } 10799 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10800 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10801 // If this permission is to be granted to the system installer and 10802 // this app is an installer, then it gets the permission. 10803 allowed = true; 10804 } 10805 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10806 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10807 // If this permission is to be granted to the system verifier and 10808 // this app is a verifier, then it gets the permission. 10809 allowed = true; 10810 } 10811 if (!allowed && (bp.protectionLevel 10812 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10813 && isSystemApp(pkg)) { 10814 // Any pre-installed system app is allowed to get this permission. 10815 allowed = true; 10816 } 10817 if (!allowed && (bp.protectionLevel 10818 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10819 // For development permissions, a development permission 10820 // is granted only if it was already granted. 10821 allowed = origPermissions.hasInstallPermission(perm); 10822 } 10823 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10824 && pkg.packageName.equals(mSetupWizardPackage)) { 10825 // If this permission is to be granted to the system setup wizard and 10826 // this app is a setup wizard, then it gets the permission. 10827 allowed = true; 10828 } 10829 } 10830 return allowed; 10831 } 10832 10833 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10834 final int permCount = pkg.requestedPermissions.size(); 10835 for (int j = 0; j < permCount; j++) { 10836 String requestedPermission = pkg.requestedPermissions.get(j); 10837 if (permission.equals(requestedPermission)) { 10838 return true; 10839 } 10840 } 10841 return false; 10842 } 10843 10844 final class ActivityIntentResolver 10845 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10846 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10847 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 10848 if (!sUserManager.exists(userId)) return null; 10849 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0) 10850 | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0) 10851 | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0); 10852 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 10853 isEphemeral, userId); 10854 } 10855 10856 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10857 int userId) { 10858 if (!sUserManager.exists(userId)) return null; 10859 mFlags = flags; 10860 return super.queryIntent(intent, resolvedType, 10861 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 10862 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 10863 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 10864 } 10865 10866 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10867 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10868 if (!sUserManager.exists(userId)) return null; 10869 if (packageActivities == null) { 10870 return null; 10871 } 10872 mFlags = flags; 10873 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10874 final boolean vislbleToEphemeral = 10875 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 10876 final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0; 10877 final int N = packageActivities.size(); 10878 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10879 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10880 10881 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10882 for (int i = 0; i < N; ++i) { 10883 intentFilters = packageActivities.get(i).intents; 10884 if (intentFilters != null && intentFilters.size() > 0) { 10885 PackageParser.ActivityIntentInfo[] array = 10886 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10887 intentFilters.toArray(array); 10888 listCut.add(array); 10889 } 10890 } 10891 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 10892 vislbleToEphemeral, isEphemeral, listCut, userId); 10893 } 10894 10895 /** 10896 * Finds a privileged activity that matches the specified activity names. 10897 */ 10898 private PackageParser.Activity findMatchingActivity( 10899 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10900 for (PackageParser.Activity sysActivity : activityList) { 10901 if (sysActivity.info.name.equals(activityInfo.name)) { 10902 return sysActivity; 10903 } 10904 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10905 return sysActivity; 10906 } 10907 if (sysActivity.info.targetActivity != null) { 10908 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10909 return sysActivity; 10910 } 10911 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10912 return sysActivity; 10913 } 10914 } 10915 } 10916 return null; 10917 } 10918 10919 public class IterGenerator<E> { 10920 public Iterator<E> generate(ActivityIntentInfo info) { 10921 return null; 10922 } 10923 } 10924 10925 public class ActionIterGenerator extends IterGenerator<String> { 10926 @Override 10927 public Iterator<String> generate(ActivityIntentInfo info) { 10928 return info.actionsIterator(); 10929 } 10930 } 10931 10932 public class CategoriesIterGenerator extends IterGenerator<String> { 10933 @Override 10934 public Iterator<String> generate(ActivityIntentInfo info) { 10935 return info.categoriesIterator(); 10936 } 10937 } 10938 10939 public class SchemesIterGenerator extends IterGenerator<String> { 10940 @Override 10941 public Iterator<String> generate(ActivityIntentInfo info) { 10942 return info.schemesIterator(); 10943 } 10944 } 10945 10946 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10947 @Override 10948 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10949 return info.authoritiesIterator(); 10950 } 10951 } 10952 10953 /** 10954 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10955 * MODIFIED. Do not pass in a list that should not be changed. 10956 */ 10957 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10958 IterGenerator<T> generator, Iterator<T> searchIterator) { 10959 // loop through the set of actions; every one must be found in the intent filter 10960 while (searchIterator.hasNext()) { 10961 // we must have at least one filter in the list to consider a match 10962 if (intentList.size() == 0) { 10963 break; 10964 } 10965 10966 final T searchAction = searchIterator.next(); 10967 10968 // loop through the set of intent filters 10969 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10970 while (intentIter.hasNext()) { 10971 final ActivityIntentInfo intentInfo = intentIter.next(); 10972 boolean selectionFound = false; 10973 10974 // loop through the intent filter's selection criteria; at least one 10975 // of them must match the searched criteria 10976 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10977 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10978 final T intentSelection = intentSelectionIter.next(); 10979 if (intentSelection != null && intentSelection.equals(searchAction)) { 10980 selectionFound = true; 10981 break; 10982 } 10983 } 10984 10985 // the selection criteria wasn't found in this filter's set; this filter 10986 // is not a potential match 10987 if (!selectionFound) { 10988 intentIter.remove(); 10989 } 10990 } 10991 } 10992 } 10993 10994 private boolean isProtectedAction(ActivityIntentInfo filter) { 10995 final Iterator<String> actionsIter = filter.actionsIterator(); 10996 while (actionsIter != null && actionsIter.hasNext()) { 10997 final String filterAction = actionsIter.next(); 10998 if (PROTECTED_ACTIONS.contains(filterAction)) { 10999 return true; 11000 } 11001 } 11002 return false; 11003 } 11004 11005 /** 11006 * Adjusts the priority of the given intent filter according to policy. 11007 * <p> 11008 * <ul> 11009 * <li>The priority for non privileged applications is capped to '0'</li> 11010 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11011 * <li>The priority for unbundled updates to privileged applications is capped to the 11012 * priority defined on the system partition</li> 11013 * </ul> 11014 * <p> 11015 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11016 * allowed to obtain any priority on any action. 11017 */ 11018 private void adjustPriority( 11019 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11020 // nothing to do; priority is fine as-is 11021 if (intent.getPriority() <= 0) { 11022 return; 11023 } 11024 11025 final ActivityInfo activityInfo = intent.activity.info; 11026 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11027 11028 final boolean privilegedApp = 11029 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11030 if (!privilegedApp) { 11031 // non-privileged applications can never define a priority >0 11032 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11033 + " package: " + applicationInfo.packageName 11034 + " activity: " + intent.activity.className 11035 + " origPrio: " + intent.getPriority()); 11036 intent.setPriority(0); 11037 return; 11038 } 11039 11040 if (systemActivities == null) { 11041 // the system package is not disabled; we're parsing the system partition 11042 if (isProtectedAction(intent)) { 11043 if (mDeferProtectedFilters) { 11044 // We can't deal with these just yet. No component should ever obtain a 11045 // >0 priority for a protected actions, with ONE exception -- the setup 11046 // wizard. The setup wizard, however, cannot be known until we're able to 11047 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11048 // until all intent filters have been processed. Chicken, meet egg. 11049 // Let the filter temporarily have a high priority and rectify the 11050 // priorities after all system packages have been scanned. 11051 mProtectedFilters.add(intent); 11052 if (DEBUG_FILTERS) { 11053 Slog.i(TAG, "Protected action; save for later;" 11054 + " package: " + applicationInfo.packageName 11055 + " activity: " + intent.activity.className 11056 + " origPrio: " + intent.getPriority()); 11057 } 11058 return; 11059 } else { 11060 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 11061 Slog.i(TAG, "No setup wizard;" 11062 + " All protected intents capped to priority 0"); 11063 } 11064 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 11065 if (DEBUG_FILTERS) { 11066 Slog.i(TAG, "Found setup wizard;" 11067 + " allow priority " + intent.getPriority() + ";" 11068 + " package: " + intent.activity.info.packageName 11069 + " activity: " + intent.activity.className 11070 + " priority: " + intent.getPriority()); 11071 } 11072 // setup wizard gets whatever it wants 11073 return; 11074 } 11075 Slog.w(TAG, "Protected action; cap priority to 0;" 11076 + " package: " + intent.activity.info.packageName 11077 + " activity: " + intent.activity.className 11078 + " origPrio: " + intent.getPriority()); 11079 intent.setPriority(0); 11080 return; 11081 } 11082 } 11083 // privileged apps on the system image get whatever priority they request 11084 return; 11085 } 11086 11087 // privileged app unbundled update ... try to find the same activity 11088 final PackageParser.Activity foundActivity = 11089 findMatchingActivity(systemActivities, activityInfo); 11090 if (foundActivity == null) { 11091 // this is a new activity; it cannot obtain >0 priority 11092 if (DEBUG_FILTERS) { 11093 Slog.i(TAG, "New activity; cap priority to 0;" 11094 + " package: " + applicationInfo.packageName 11095 + " activity: " + intent.activity.className 11096 + " origPrio: " + intent.getPriority()); 11097 } 11098 intent.setPriority(0); 11099 return; 11100 } 11101 11102 // found activity, now check for filter equivalence 11103 11104 // a shallow copy is enough; we modify the list, not its contents 11105 final List<ActivityIntentInfo> intentListCopy = 11106 new ArrayList<>(foundActivity.intents); 11107 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 11108 11109 // find matching action subsets 11110 final Iterator<String> actionsIterator = intent.actionsIterator(); 11111 if (actionsIterator != null) { 11112 getIntentListSubset( 11113 intentListCopy, new ActionIterGenerator(), actionsIterator); 11114 if (intentListCopy.size() == 0) { 11115 // no more intents to match; we're not equivalent 11116 if (DEBUG_FILTERS) { 11117 Slog.i(TAG, "Mismatched action; cap priority to 0;" 11118 + " package: " + applicationInfo.packageName 11119 + " activity: " + intent.activity.className 11120 + " origPrio: " + intent.getPriority()); 11121 } 11122 intent.setPriority(0); 11123 return; 11124 } 11125 } 11126 11127 // find matching category subsets 11128 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 11129 if (categoriesIterator != null) { 11130 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 11131 categoriesIterator); 11132 if (intentListCopy.size() == 0) { 11133 // no more intents to match; we're not equivalent 11134 if (DEBUG_FILTERS) { 11135 Slog.i(TAG, "Mismatched category; cap priority to 0;" 11136 + " package: " + applicationInfo.packageName 11137 + " activity: " + intent.activity.className 11138 + " origPrio: " + intent.getPriority()); 11139 } 11140 intent.setPriority(0); 11141 return; 11142 } 11143 } 11144 11145 // find matching schemes subsets 11146 final Iterator<String> schemesIterator = intent.schemesIterator(); 11147 if (schemesIterator != null) { 11148 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 11149 schemesIterator); 11150 if (intentListCopy.size() == 0) { 11151 // no more intents to match; we're not equivalent 11152 if (DEBUG_FILTERS) { 11153 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 11154 + " package: " + applicationInfo.packageName 11155 + " activity: " + intent.activity.className 11156 + " origPrio: " + intent.getPriority()); 11157 } 11158 intent.setPriority(0); 11159 return; 11160 } 11161 } 11162 11163 // find matching authorities subsets 11164 final Iterator<IntentFilter.AuthorityEntry> 11165 authoritiesIterator = intent.authoritiesIterator(); 11166 if (authoritiesIterator != null) { 11167 getIntentListSubset(intentListCopy, 11168 new AuthoritiesIterGenerator(), 11169 authoritiesIterator); 11170 if (intentListCopy.size() == 0) { 11171 // no more intents to match; we're not equivalent 11172 if (DEBUG_FILTERS) { 11173 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 11174 + " package: " + applicationInfo.packageName 11175 + " activity: " + intent.activity.className 11176 + " origPrio: " + intent.getPriority()); 11177 } 11178 intent.setPriority(0); 11179 return; 11180 } 11181 } 11182 11183 // we found matching filter(s); app gets the max priority of all intents 11184 int cappedPriority = 0; 11185 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 11186 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 11187 } 11188 if (intent.getPriority() > cappedPriority) { 11189 if (DEBUG_FILTERS) { 11190 Slog.i(TAG, "Found matching filter(s);" 11191 + " cap priority to " + cappedPriority + ";" 11192 + " package: " + applicationInfo.packageName 11193 + " activity: " + intent.activity.className 11194 + " origPrio: " + intent.getPriority()); 11195 } 11196 intent.setPriority(cappedPriority); 11197 return; 11198 } 11199 // all this for nothing; the requested priority was <= what was on the system 11200 } 11201 11202 public final void addActivity(PackageParser.Activity a, String type) { 11203 mActivities.put(a.getComponentName(), a); 11204 if (DEBUG_SHOW_INFO) 11205 Log.v( 11206 TAG, " " + type + " " + 11207 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 11208 if (DEBUG_SHOW_INFO) 11209 Log.v(TAG, " Class=" + a.info.name); 11210 final int NI = a.intents.size(); 11211 for (int j=0; j<NI; j++) { 11212 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11213 if ("activity".equals(type)) { 11214 final PackageSetting ps = 11215 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 11216 final List<PackageParser.Activity> systemActivities = 11217 ps != null && ps.pkg != null ? ps.pkg.activities : null; 11218 adjustPriority(systemActivities, intent); 11219 } 11220 if (DEBUG_SHOW_INFO) { 11221 Log.v(TAG, " IntentFilter:"); 11222 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11223 } 11224 if (!intent.debugCheck()) { 11225 Log.w(TAG, "==> For Activity " + a.info.name); 11226 } 11227 addFilter(intent); 11228 } 11229 } 11230 11231 public final void removeActivity(PackageParser.Activity a, String type) { 11232 mActivities.remove(a.getComponentName()); 11233 if (DEBUG_SHOW_INFO) { 11234 Log.v(TAG, " " + type + " " 11235 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 11236 : a.info.name) + ":"); 11237 Log.v(TAG, " Class=" + a.info.name); 11238 } 11239 final int NI = a.intents.size(); 11240 for (int j=0; j<NI; j++) { 11241 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11242 if (DEBUG_SHOW_INFO) { 11243 Log.v(TAG, " IntentFilter:"); 11244 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11245 } 11246 removeFilter(intent); 11247 } 11248 } 11249 11250 @Override 11251 protected boolean allowFilterResult( 11252 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 11253 ActivityInfo filterAi = filter.activity.info; 11254 for (int i=dest.size()-1; i>=0; i--) { 11255 ActivityInfo destAi = dest.get(i).activityInfo; 11256 if (destAi.name == filterAi.name 11257 && destAi.packageName == filterAi.packageName) { 11258 return false; 11259 } 11260 } 11261 return true; 11262 } 11263 11264 @Override 11265 protected ActivityIntentInfo[] newArray(int size) { 11266 return new ActivityIntentInfo[size]; 11267 } 11268 11269 @Override 11270 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 11271 if (!sUserManager.exists(userId)) return true; 11272 PackageParser.Package p = filter.activity.owner; 11273 if (p != null) { 11274 PackageSetting ps = (PackageSetting)p.mExtras; 11275 if (ps != null) { 11276 // System apps are never considered stopped for purposes of 11277 // filtering, because there may be no way for the user to 11278 // actually re-launch them. 11279 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 11280 && ps.getStopped(userId); 11281 } 11282 } 11283 return false; 11284 } 11285 11286 @Override 11287 protected boolean isPackageForFilter(String packageName, 11288 PackageParser.ActivityIntentInfo info) { 11289 return packageName.equals(info.activity.owner.packageName); 11290 } 11291 11292 @Override 11293 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 11294 int match, int userId) { 11295 if (!sUserManager.exists(userId)) return null; 11296 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 11297 return null; 11298 } 11299 final PackageParser.Activity activity = info.activity; 11300 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 11301 if (ps == null) { 11302 return null; 11303 } 11304 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 11305 ps.readUserState(userId), userId); 11306 if (ai == null) { 11307 return null; 11308 } 11309 final ResolveInfo res = new ResolveInfo(); 11310 res.activityInfo = ai; 11311 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11312 res.filter = info; 11313 } 11314 if (info != null) { 11315 res.handleAllWebDataURI = info.handleAllWebDataURI(); 11316 } 11317 res.priority = info.getPriority(); 11318 res.preferredOrder = activity.owner.mPreferredOrder; 11319 //System.out.println("Result: " + res.activityInfo.className + 11320 // " = " + res.priority); 11321 res.match = match; 11322 res.isDefault = info.hasDefault; 11323 res.labelRes = info.labelRes; 11324 res.nonLocalizedLabel = info.nonLocalizedLabel; 11325 if (userNeedsBadging(userId)) { 11326 res.noResourceId = true; 11327 } else { 11328 res.icon = info.icon; 11329 } 11330 res.iconResourceId = info.icon; 11331 res.system = res.activityInfo.applicationInfo.isSystemApp(); 11332 return res; 11333 } 11334 11335 @Override 11336 protected void sortResults(List<ResolveInfo> results) { 11337 Collections.sort(results, mResolvePrioritySorter); 11338 } 11339 11340 @Override 11341 protected void dumpFilter(PrintWriter out, String prefix, 11342 PackageParser.ActivityIntentInfo filter) { 11343 out.print(prefix); out.print( 11344 Integer.toHexString(System.identityHashCode(filter.activity))); 11345 out.print(' '); 11346 filter.activity.printComponentShortName(out); 11347 out.print(" filter "); 11348 out.println(Integer.toHexString(System.identityHashCode(filter))); 11349 } 11350 11351 @Override 11352 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 11353 return filter.activity; 11354 } 11355 11356 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11357 PackageParser.Activity activity = (PackageParser.Activity)label; 11358 out.print(prefix); out.print( 11359 Integer.toHexString(System.identityHashCode(activity))); 11360 out.print(' '); 11361 activity.printComponentShortName(out); 11362 if (count > 1) { 11363 out.print(" ("); out.print(count); out.print(" filters)"); 11364 } 11365 out.println(); 11366 } 11367 11368 // Keys are String (activity class name), values are Activity. 11369 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 11370 = new ArrayMap<ComponentName, PackageParser.Activity>(); 11371 private int mFlags; 11372 } 11373 11374 private final class ServiceIntentResolver 11375 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 11376 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11377 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 11378 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11379 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 11380 isEphemeral, userId); 11381 } 11382 11383 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11384 int userId) { 11385 if (!sUserManager.exists(userId)) return null; 11386 mFlags = flags; 11387 return super.queryIntent(intent, resolvedType, 11388 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11389 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 11390 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 11391 } 11392 11393 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11394 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 11395 if (!sUserManager.exists(userId)) return null; 11396 if (packageServices == null) { 11397 return null; 11398 } 11399 mFlags = flags; 11400 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 11401 final boolean vislbleToEphemeral = 11402 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 11403 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 11404 final int N = packageServices.size(); 11405 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 11406 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 11407 11408 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 11409 for (int i = 0; i < N; ++i) { 11410 intentFilters = packageServices.get(i).intents; 11411 if (intentFilters != null && intentFilters.size() > 0) { 11412 PackageParser.ServiceIntentInfo[] array = 11413 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 11414 intentFilters.toArray(array); 11415 listCut.add(array); 11416 } 11417 } 11418 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 11419 vislbleToEphemeral, isEphemeral, listCut, userId); 11420 } 11421 11422 public final void addService(PackageParser.Service s) { 11423 mServices.put(s.getComponentName(), s); 11424 if (DEBUG_SHOW_INFO) { 11425 Log.v(TAG, " " 11426 + (s.info.nonLocalizedLabel != null 11427 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11428 Log.v(TAG, " Class=" + s.info.name); 11429 } 11430 final int NI = s.intents.size(); 11431 int j; 11432 for (j=0; j<NI; j++) { 11433 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11434 if (DEBUG_SHOW_INFO) { 11435 Log.v(TAG, " IntentFilter:"); 11436 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11437 } 11438 if (!intent.debugCheck()) { 11439 Log.w(TAG, "==> For Service " + s.info.name); 11440 } 11441 addFilter(intent); 11442 } 11443 } 11444 11445 public final void removeService(PackageParser.Service s) { 11446 mServices.remove(s.getComponentName()); 11447 if (DEBUG_SHOW_INFO) { 11448 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11449 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11450 Log.v(TAG, " Class=" + s.info.name); 11451 } 11452 final int NI = s.intents.size(); 11453 int j; 11454 for (j=0; j<NI; j++) { 11455 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11456 if (DEBUG_SHOW_INFO) { 11457 Log.v(TAG, " IntentFilter:"); 11458 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11459 } 11460 removeFilter(intent); 11461 } 11462 } 11463 11464 @Override 11465 protected boolean allowFilterResult( 11466 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11467 ServiceInfo filterSi = filter.service.info; 11468 for (int i=dest.size()-1; i>=0; i--) { 11469 ServiceInfo destAi = dest.get(i).serviceInfo; 11470 if (destAi.name == filterSi.name 11471 && destAi.packageName == filterSi.packageName) { 11472 return false; 11473 } 11474 } 11475 return true; 11476 } 11477 11478 @Override 11479 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11480 return new PackageParser.ServiceIntentInfo[size]; 11481 } 11482 11483 @Override 11484 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11485 if (!sUserManager.exists(userId)) return true; 11486 PackageParser.Package p = filter.service.owner; 11487 if (p != null) { 11488 PackageSetting ps = (PackageSetting)p.mExtras; 11489 if (ps != null) { 11490 // System apps are never considered stopped for purposes of 11491 // filtering, because there may be no way for the user to 11492 // actually re-launch them. 11493 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11494 && ps.getStopped(userId); 11495 } 11496 } 11497 return false; 11498 } 11499 11500 @Override 11501 protected boolean isPackageForFilter(String packageName, 11502 PackageParser.ServiceIntentInfo info) { 11503 return packageName.equals(info.service.owner.packageName); 11504 } 11505 11506 @Override 11507 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11508 int match, int userId) { 11509 if (!sUserManager.exists(userId)) return null; 11510 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11511 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11512 return null; 11513 } 11514 final PackageParser.Service service = info.service; 11515 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11516 if (ps == null) { 11517 return null; 11518 } 11519 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11520 ps.readUserState(userId), userId); 11521 if (si == null) { 11522 return null; 11523 } 11524 final ResolveInfo res = new ResolveInfo(); 11525 res.serviceInfo = si; 11526 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11527 res.filter = filter; 11528 } 11529 res.priority = info.getPriority(); 11530 res.preferredOrder = service.owner.mPreferredOrder; 11531 res.match = match; 11532 res.isDefault = info.hasDefault; 11533 res.labelRes = info.labelRes; 11534 res.nonLocalizedLabel = info.nonLocalizedLabel; 11535 res.icon = info.icon; 11536 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11537 return res; 11538 } 11539 11540 @Override 11541 protected void sortResults(List<ResolveInfo> results) { 11542 Collections.sort(results, mResolvePrioritySorter); 11543 } 11544 11545 @Override 11546 protected void dumpFilter(PrintWriter out, String prefix, 11547 PackageParser.ServiceIntentInfo filter) { 11548 out.print(prefix); out.print( 11549 Integer.toHexString(System.identityHashCode(filter.service))); 11550 out.print(' '); 11551 filter.service.printComponentShortName(out); 11552 out.print(" filter "); 11553 out.println(Integer.toHexString(System.identityHashCode(filter))); 11554 } 11555 11556 @Override 11557 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11558 return filter.service; 11559 } 11560 11561 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11562 PackageParser.Service service = (PackageParser.Service)label; 11563 out.print(prefix); out.print( 11564 Integer.toHexString(System.identityHashCode(service))); 11565 out.print(' '); 11566 service.printComponentShortName(out); 11567 if (count > 1) { 11568 out.print(" ("); out.print(count); out.print(" filters)"); 11569 } 11570 out.println(); 11571 } 11572 11573// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11574// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11575// final List<ResolveInfo> retList = Lists.newArrayList(); 11576// while (i.hasNext()) { 11577// final ResolveInfo resolveInfo = (ResolveInfo) i; 11578// if (isEnabledLP(resolveInfo.serviceInfo)) { 11579// retList.add(resolveInfo); 11580// } 11581// } 11582// return retList; 11583// } 11584 11585 // Keys are String (activity class name), values are Activity. 11586 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11587 = new ArrayMap<ComponentName, PackageParser.Service>(); 11588 private int mFlags; 11589 } 11590 11591 private final class ProviderIntentResolver 11592 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11593 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11594 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 11595 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11596 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 11597 isEphemeral, userId); 11598 } 11599 11600 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11601 int userId) { 11602 if (!sUserManager.exists(userId)) 11603 return null; 11604 mFlags = flags; 11605 return super.queryIntent(intent, resolvedType, 11606 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11607 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 11608 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 11609 } 11610 11611 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11612 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11613 if (!sUserManager.exists(userId)) 11614 return null; 11615 if (packageProviders == null) { 11616 return null; 11617 } 11618 mFlags = flags; 11619 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11620 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 11621 final boolean vislbleToEphemeral = 11622 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 11623 final int N = packageProviders.size(); 11624 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11625 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11626 11627 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11628 for (int i = 0; i < N; ++i) { 11629 intentFilters = packageProviders.get(i).intents; 11630 if (intentFilters != null && intentFilters.size() > 0) { 11631 PackageParser.ProviderIntentInfo[] array = 11632 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11633 intentFilters.toArray(array); 11634 listCut.add(array); 11635 } 11636 } 11637 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 11638 vislbleToEphemeral, isEphemeral, listCut, userId); 11639 } 11640 11641 public final void addProvider(PackageParser.Provider p) { 11642 if (mProviders.containsKey(p.getComponentName())) { 11643 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11644 return; 11645 } 11646 11647 mProviders.put(p.getComponentName(), p); 11648 if (DEBUG_SHOW_INFO) { 11649 Log.v(TAG, " " 11650 + (p.info.nonLocalizedLabel != null 11651 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11652 Log.v(TAG, " Class=" + p.info.name); 11653 } 11654 final int NI = p.intents.size(); 11655 int j; 11656 for (j = 0; j < NI; j++) { 11657 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11658 if (DEBUG_SHOW_INFO) { 11659 Log.v(TAG, " IntentFilter:"); 11660 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11661 } 11662 if (!intent.debugCheck()) { 11663 Log.w(TAG, "==> For Provider " + p.info.name); 11664 } 11665 addFilter(intent); 11666 } 11667 } 11668 11669 public final void removeProvider(PackageParser.Provider p) { 11670 mProviders.remove(p.getComponentName()); 11671 if (DEBUG_SHOW_INFO) { 11672 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11673 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11674 Log.v(TAG, " Class=" + p.info.name); 11675 } 11676 final int NI = p.intents.size(); 11677 int j; 11678 for (j = 0; j < NI; j++) { 11679 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11680 if (DEBUG_SHOW_INFO) { 11681 Log.v(TAG, " IntentFilter:"); 11682 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11683 } 11684 removeFilter(intent); 11685 } 11686 } 11687 11688 @Override 11689 protected boolean allowFilterResult( 11690 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11691 ProviderInfo filterPi = filter.provider.info; 11692 for (int i = dest.size() - 1; i >= 0; i--) { 11693 ProviderInfo destPi = dest.get(i).providerInfo; 11694 if (destPi.name == filterPi.name 11695 && destPi.packageName == filterPi.packageName) { 11696 return false; 11697 } 11698 } 11699 return true; 11700 } 11701 11702 @Override 11703 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11704 return new PackageParser.ProviderIntentInfo[size]; 11705 } 11706 11707 @Override 11708 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11709 if (!sUserManager.exists(userId)) 11710 return true; 11711 PackageParser.Package p = filter.provider.owner; 11712 if (p != null) { 11713 PackageSetting ps = (PackageSetting) p.mExtras; 11714 if (ps != null) { 11715 // System apps are never considered stopped for purposes of 11716 // filtering, because there may be no way for the user to 11717 // actually re-launch them. 11718 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11719 && ps.getStopped(userId); 11720 } 11721 } 11722 return false; 11723 } 11724 11725 @Override 11726 protected boolean isPackageForFilter(String packageName, 11727 PackageParser.ProviderIntentInfo info) { 11728 return packageName.equals(info.provider.owner.packageName); 11729 } 11730 11731 @Override 11732 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11733 int match, int userId) { 11734 if (!sUserManager.exists(userId)) 11735 return null; 11736 final PackageParser.ProviderIntentInfo info = filter; 11737 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11738 return null; 11739 } 11740 final PackageParser.Provider provider = info.provider; 11741 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11742 if (ps == null) { 11743 return null; 11744 } 11745 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11746 ps.readUserState(userId), userId); 11747 if (pi == null) { 11748 return null; 11749 } 11750 final ResolveInfo res = new ResolveInfo(); 11751 res.providerInfo = pi; 11752 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11753 res.filter = filter; 11754 } 11755 res.priority = info.getPriority(); 11756 res.preferredOrder = provider.owner.mPreferredOrder; 11757 res.match = match; 11758 res.isDefault = info.hasDefault; 11759 res.labelRes = info.labelRes; 11760 res.nonLocalizedLabel = info.nonLocalizedLabel; 11761 res.icon = info.icon; 11762 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11763 return res; 11764 } 11765 11766 @Override 11767 protected void sortResults(List<ResolveInfo> results) { 11768 Collections.sort(results, mResolvePrioritySorter); 11769 } 11770 11771 @Override 11772 protected void dumpFilter(PrintWriter out, String prefix, 11773 PackageParser.ProviderIntentInfo filter) { 11774 out.print(prefix); 11775 out.print( 11776 Integer.toHexString(System.identityHashCode(filter.provider))); 11777 out.print(' '); 11778 filter.provider.printComponentShortName(out); 11779 out.print(" filter "); 11780 out.println(Integer.toHexString(System.identityHashCode(filter))); 11781 } 11782 11783 @Override 11784 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11785 return filter.provider; 11786 } 11787 11788 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11789 PackageParser.Provider provider = (PackageParser.Provider)label; 11790 out.print(prefix); out.print( 11791 Integer.toHexString(System.identityHashCode(provider))); 11792 out.print(' '); 11793 provider.printComponentShortName(out); 11794 if (count > 1) { 11795 out.print(" ("); out.print(count); out.print(" filters)"); 11796 } 11797 out.println(); 11798 } 11799 11800 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11801 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11802 private int mFlags; 11803 } 11804 11805 static final class EphemeralIntentResolver 11806 extends IntentResolver<EphemeralResponse, EphemeralResponse> { 11807 /** 11808 * The result that has the highest defined order. Ordering applies on a 11809 * per-package basis. Mapping is from package name to Pair of order and 11810 * EphemeralResolveInfo. 11811 * <p> 11812 * NOTE: This is implemented as a field variable for convenience and efficiency. 11813 * By having a field variable, we're able to track filter ordering as soon as 11814 * a non-zero order is defined. Otherwise, multiple loops across the result set 11815 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11816 * this needs to be contained entirely within {@link #filterResults()}. 11817 */ 11818 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11819 11820 @Override 11821 protected EphemeralResponse[] newArray(int size) { 11822 return new EphemeralResponse[size]; 11823 } 11824 11825 @Override 11826 protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) { 11827 return true; 11828 } 11829 11830 @Override 11831 protected EphemeralResponse newResult(EphemeralResponse responseObj, int match, 11832 int userId) { 11833 if (!sUserManager.exists(userId)) { 11834 return null; 11835 } 11836 final String packageName = responseObj.resolveInfo.getPackageName(); 11837 final Integer order = responseObj.getOrder(); 11838 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11839 mOrderResult.get(packageName); 11840 // ordering is enabled and this item's order isn't high enough 11841 if (lastOrderResult != null && lastOrderResult.first >= order) { 11842 return null; 11843 } 11844 final EphemeralResolveInfo res = responseObj.resolveInfo; 11845 if (order > 0) { 11846 // non-zero order, enable ordering 11847 mOrderResult.put(packageName, new Pair<>(order, res)); 11848 } 11849 return responseObj; 11850 } 11851 11852 @Override 11853 protected void filterResults(List<EphemeralResponse> results) { 11854 // only do work if ordering is enabled [most of the time it won't be] 11855 if (mOrderResult.size() == 0) { 11856 return; 11857 } 11858 int resultSize = results.size(); 11859 for (int i = 0; i < resultSize; i++) { 11860 final EphemeralResolveInfo info = results.get(i).resolveInfo; 11861 final String packageName = info.getPackageName(); 11862 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11863 if (savedInfo == null) { 11864 // package doesn't having ordering 11865 continue; 11866 } 11867 if (savedInfo.second == info) { 11868 // circled back to the highest ordered item; remove from order list 11869 mOrderResult.remove(savedInfo); 11870 if (mOrderResult.size() == 0) { 11871 // no more ordered items 11872 break; 11873 } 11874 continue; 11875 } 11876 // item has a worse order, remove it from the result list 11877 results.remove(i); 11878 resultSize--; 11879 i--; 11880 } 11881 } 11882 } 11883 11884 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11885 new Comparator<ResolveInfo>() { 11886 public int compare(ResolveInfo r1, ResolveInfo r2) { 11887 int v1 = r1.priority; 11888 int v2 = r2.priority; 11889 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11890 if (v1 != v2) { 11891 return (v1 > v2) ? -1 : 1; 11892 } 11893 v1 = r1.preferredOrder; 11894 v2 = r2.preferredOrder; 11895 if (v1 != v2) { 11896 return (v1 > v2) ? -1 : 1; 11897 } 11898 if (r1.isDefault != r2.isDefault) { 11899 return r1.isDefault ? -1 : 1; 11900 } 11901 v1 = r1.match; 11902 v2 = r2.match; 11903 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11904 if (v1 != v2) { 11905 return (v1 > v2) ? -1 : 1; 11906 } 11907 if (r1.system != r2.system) { 11908 return r1.system ? -1 : 1; 11909 } 11910 if (r1.activityInfo != null) { 11911 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11912 } 11913 if (r1.serviceInfo != null) { 11914 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11915 } 11916 if (r1.providerInfo != null) { 11917 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11918 } 11919 return 0; 11920 } 11921 }; 11922 11923 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11924 new Comparator<ProviderInfo>() { 11925 public int compare(ProviderInfo p1, ProviderInfo p2) { 11926 final int v1 = p1.initOrder; 11927 final int v2 = p2.initOrder; 11928 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11929 } 11930 }; 11931 11932 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11933 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11934 final int[] userIds) { 11935 mHandler.post(new Runnable() { 11936 @Override 11937 public void run() { 11938 try { 11939 final IActivityManager am = ActivityManager.getService(); 11940 if (am == null) return; 11941 final int[] resolvedUserIds; 11942 if (userIds == null) { 11943 resolvedUserIds = am.getRunningUserIds(); 11944 } else { 11945 resolvedUserIds = userIds; 11946 } 11947 for (int id : resolvedUserIds) { 11948 final Intent intent = new Intent(action, 11949 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11950 if (extras != null) { 11951 intent.putExtras(extras); 11952 } 11953 if (targetPkg != null) { 11954 intent.setPackage(targetPkg); 11955 } 11956 // Modify the UID when posting to other users 11957 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11958 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11959 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11960 intent.putExtra(Intent.EXTRA_UID, uid); 11961 } 11962 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11963 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11964 if (DEBUG_BROADCASTS) { 11965 RuntimeException here = new RuntimeException("here"); 11966 here.fillInStackTrace(); 11967 Slog.d(TAG, "Sending to user " + id + ": " 11968 + intent.toShortString(false, true, false, false) 11969 + " " + intent.getExtras(), here); 11970 } 11971 am.broadcastIntent(null, intent, null, finishedReceiver, 11972 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11973 null, finishedReceiver != null, false, id); 11974 } 11975 } catch (RemoteException ex) { 11976 } 11977 } 11978 }); 11979 } 11980 11981 /** 11982 * Check if the external storage media is available. This is true if there 11983 * is a mounted external storage medium or if the external storage is 11984 * emulated. 11985 */ 11986 private boolean isExternalMediaAvailable() { 11987 return mMediaMounted || Environment.isExternalStorageEmulated(); 11988 } 11989 11990 @Override 11991 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11992 // writer 11993 synchronized (mPackages) { 11994 if (!isExternalMediaAvailable()) { 11995 // If the external storage is no longer mounted at this point, 11996 // the caller may not have been able to delete all of this 11997 // packages files and can not delete any more. Bail. 11998 return null; 11999 } 12000 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12001 if (lastPackage != null) { 12002 pkgs.remove(lastPackage); 12003 } 12004 if (pkgs.size() > 0) { 12005 return pkgs.get(0); 12006 } 12007 } 12008 return null; 12009 } 12010 12011 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12012 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12013 userId, andCode ? 1 : 0, packageName); 12014 if (mSystemReady) { 12015 msg.sendToTarget(); 12016 } else { 12017 if (mPostSystemReadyMessages == null) { 12018 mPostSystemReadyMessages = new ArrayList<>(); 12019 } 12020 mPostSystemReadyMessages.add(msg); 12021 } 12022 } 12023 12024 void startCleaningPackages() { 12025 // reader 12026 if (!isExternalMediaAvailable()) { 12027 return; 12028 } 12029 synchronized (mPackages) { 12030 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12031 return; 12032 } 12033 } 12034 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12035 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12036 IActivityManager am = ActivityManager.getService(); 12037 if (am != null) { 12038 try { 12039 am.startService(null, intent, null, mContext.getOpPackageName(), 12040 UserHandle.USER_SYSTEM); 12041 } catch (RemoteException e) { 12042 } 12043 } 12044 } 12045 12046 @Override 12047 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12048 int installFlags, String installerPackageName, int userId) { 12049 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12050 12051 final int callingUid = Binder.getCallingUid(); 12052 enforceCrossUserPermission(callingUid, userId, 12053 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12054 12055 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12056 try { 12057 if (observer != null) { 12058 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12059 } 12060 } catch (RemoteException re) { 12061 } 12062 return; 12063 } 12064 12065 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 12066 installFlags |= PackageManager.INSTALL_FROM_ADB; 12067 12068 } else { 12069 // Caller holds INSTALL_PACKAGES permission, so we're less strict 12070 // about installerPackageName. 12071 12072 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 12073 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 12074 } 12075 12076 UserHandle user; 12077 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 12078 user = UserHandle.ALL; 12079 } else { 12080 user = new UserHandle(userId); 12081 } 12082 12083 // Only system components can circumvent runtime permissions when installing. 12084 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 12085 && mContext.checkCallingOrSelfPermission(Manifest.permission 12086 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 12087 throw new SecurityException("You need the " 12088 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 12089 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 12090 } 12091 12092 final File originFile = new File(originPath); 12093 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 12094 12095 final Message msg = mHandler.obtainMessage(INIT_COPY); 12096 final VerificationInfo verificationInfo = new VerificationInfo( 12097 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 12098 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 12099 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 12100 null /*packageAbiOverride*/, null /*grantedPermissions*/, 12101 null /*certificates*/); 12102 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 12103 msg.obj = params; 12104 12105 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 12106 System.identityHashCode(msg.obj)); 12107 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12108 System.identityHashCode(msg.obj)); 12109 12110 mHandler.sendMessage(msg); 12111 } 12112 12113 void installStage(String packageName, File stagedDir, String stagedCid, 12114 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 12115 String installerPackageName, int installerUid, UserHandle user, 12116 Certificate[][] certificates) { 12117 if (DEBUG_EPHEMERAL) { 12118 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12119 Slog.d(TAG, "Ephemeral install of " + packageName); 12120 } 12121 } 12122 final VerificationInfo verificationInfo = new VerificationInfo( 12123 sessionParams.originatingUri, sessionParams.referrerUri, 12124 sessionParams.originatingUid, installerUid); 12125 12126 final OriginInfo origin; 12127 if (stagedDir != null) { 12128 origin = OriginInfo.fromStagedFile(stagedDir); 12129 } else { 12130 origin = OriginInfo.fromStagedContainer(stagedCid); 12131 } 12132 12133 final Message msg = mHandler.obtainMessage(INIT_COPY); 12134 final InstallParams params = new InstallParams(origin, null, observer, 12135 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 12136 verificationInfo, user, sessionParams.abiOverride, 12137 sessionParams.grantedRuntimePermissions, certificates); 12138 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 12139 msg.obj = params; 12140 12141 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 12142 System.identityHashCode(msg.obj)); 12143 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12144 System.identityHashCode(msg.obj)); 12145 12146 mHandler.sendMessage(msg); 12147 } 12148 12149 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 12150 int userId) { 12151 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 12152 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 12153 } 12154 12155 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 12156 int appId, int... userIds) { 12157 if (ArrayUtils.isEmpty(userIds)) { 12158 return; 12159 } 12160 Bundle extras = new Bundle(1); 12161 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 12162 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 12163 12164 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 12165 packageName, extras, 0, null, null, userIds); 12166 if (isSystem) { 12167 mHandler.post(() -> { 12168 for (int userId : userIds) { 12169 sendBootCompletedBroadcastToSystemApp(packageName, userId); 12170 } 12171 } 12172 ); 12173 } 12174 } 12175 12176 /** 12177 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 12178 * automatically without needing an explicit launch. 12179 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 12180 */ 12181 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 12182 // If user is not running, the app didn't miss any broadcast 12183 if (!mUserManagerInternal.isUserRunning(userId)) { 12184 return; 12185 } 12186 final IActivityManager am = ActivityManager.getService(); 12187 try { 12188 // Deliver LOCKED_BOOT_COMPLETED first 12189 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 12190 .setPackage(packageName); 12191 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 12192 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 12193 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 12194 12195 // Deliver BOOT_COMPLETED only if user is unlocked 12196 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 12197 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 12198 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 12199 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 12200 } 12201 } catch (RemoteException e) { 12202 throw e.rethrowFromSystemServer(); 12203 } 12204 } 12205 12206 @Override 12207 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 12208 int userId) { 12209 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12210 PackageSetting pkgSetting; 12211 final int uid = Binder.getCallingUid(); 12212 enforceCrossUserPermission(uid, userId, 12213 true /* requireFullPermission */, true /* checkShell */, 12214 "setApplicationHiddenSetting for user " + userId); 12215 12216 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 12217 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 12218 return false; 12219 } 12220 12221 long callingId = Binder.clearCallingIdentity(); 12222 try { 12223 boolean sendAdded = false; 12224 boolean sendRemoved = false; 12225 // writer 12226 synchronized (mPackages) { 12227 pkgSetting = mSettings.mPackages.get(packageName); 12228 if (pkgSetting == null) { 12229 return false; 12230 } 12231 // Do not allow "android" is being disabled 12232 if ("android".equals(packageName)) { 12233 Slog.w(TAG, "Cannot hide package: android"); 12234 return false; 12235 } 12236 // Only allow protected packages to hide themselves. 12237 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 12238 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12239 Slog.w(TAG, "Not hiding protected package: " + packageName); 12240 return false; 12241 } 12242 12243 if (pkgSetting.getHidden(userId) != hidden) { 12244 pkgSetting.setHidden(hidden, userId); 12245 mSettings.writePackageRestrictionsLPr(userId); 12246 if (hidden) { 12247 sendRemoved = true; 12248 } else { 12249 sendAdded = true; 12250 } 12251 } 12252 } 12253 if (sendAdded) { 12254 sendPackageAddedForUser(packageName, pkgSetting, userId); 12255 return true; 12256 } 12257 if (sendRemoved) { 12258 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 12259 "hiding pkg"); 12260 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 12261 return true; 12262 } 12263 } finally { 12264 Binder.restoreCallingIdentity(callingId); 12265 } 12266 return false; 12267 } 12268 12269 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 12270 int userId) { 12271 final PackageRemovedInfo info = new PackageRemovedInfo(); 12272 info.removedPackage = packageName; 12273 info.removedUsers = new int[] {userId}; 12274 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 12275 info.sendPackageRemovedBroadcasts(true /*killApp*/); 12276 } 12277 12278 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 12279 if (pkgList.length > 0) { 12280 Bundle extras = new Bundle(1); 12281 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 12282 12283 sendPackageBroadcast( 12284 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 12285 : Intent.ACTION_PACKAGES_UNSUSPENDED, 12286 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 12287 new int[] {userId}); 12288 } 12289 } 12290 12291 /** 12292 * Returns true if application is not found or there was an error. Otherwise it returns 12293 * the hidden state of the package for the given user. 12294 */ 12295 @Override 12296 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 12297 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12298 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12299 true /* requireFullPermission */, false /* checkShell */, 12300 "getApplicationHidden for user " + userId); 12301 PackageSetting pkgSetting; 12302 long callingId = Binder.clearCallingIdentity(); 12303 try { 12304 // writer 12305 synchronized (mPackages) { 12306 pkgSetting = mSettings.mPackages.get(packageName); 12307 if (pkgSetting == null) { 12308 return true; 12309 } 12310 return pkgSetting.getHidden(userId); 12311 } 12312 } finally { 12313 Binder.restoreCallingIdentity(callingId); 12314 } 12315 } 12316 12317 /** 12318 * @hide 12319 */ 12320 @Override 12321 public int installExistingPackageAsUser(String packageName, int userId) { 12322 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 12323 null); 12324 PackageSetting pkgSetting; 12325 final int uid = Binder.getCallingUid(); 12326 enforceCrossUserPermission(uid, userId, 12327 true /* requireFullPermission */, true /* checkShell */, 12328 "installExistingPackage for user " + userId); 12329 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12330 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 12331 } 12332 12333 long callingId = Binder.clearCallingIdentity(); 12334 try { 12335 boolean installed = false; 12336 12337 // writer 12338 synchronized (mPackages) { 12339 pkgSetting = mSettings.mPackages.get(packageName); 12340 if (pkgSetting == null) { 12341 return PackageManager.INSTALL_FAILED_INVALID_URI; 12342 } 12343 if (!pkgSetting.getInstalled(userId)) { 12344 pkgSetting.setInstalled(true, userId); 12345 pkgSetting.setHidden(false, userId); 12346 mSettings.writePackageRestrictionsLPr(userId); 12347 installed = true; 12348 } 12349 } 12350 12351 if (installed) { 12352 if (pkgSetting.pkg != null) { 12353 synchronized (mInstallLock) { 12354 // We don't need to freeze for a brand new install 12355 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 12356 } 12357 } 12358 sendPackageAddedForUser(packageName, pkgSetting, userId); 12359 } 12360 } finally { 12361 Binder.restoreCallingIdentity(callingId); 12362 } 12363 12364 return PackageManager.INSTALL_SUCCEEDED; 12365 } 12366 12367 boolean isUserRestricted(int userId, String restrictionKey) { 12368 Bundle restrictions = sUserManager.getUserRestrictions(userId); 12369 if (restrictions.getBoolean(restrictionKey, false)) { 12370 Log.w(TAG, "User is restricted: " + restrictionKey); 12371 return true; 12372 } 12373 return false; 12374 } 12375 12376 @Override 12377 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 12378 int userId) { 12379 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12380 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12381 true /* requireFullPermission */, true /* checkShell */, 12382 "setPackagesSuspended for user " + userId); 12383 12384 if (ArrayUtils.isEmpty(packageNames)) { 12385 return packageNames; 12386 } 12387 12388 // List of package names for whom the suspended state has changed. 12389 List<String> changedPackages = new ArrayList<>(packageNames.length); 12390 // List of package names for whom the suspended state is not set as requested in this 12391 // method. 12392 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 12393 long callingId = Binder.clearCallingIdentity(); 12394 try { 12395 for (int i = 0; i < packageNames.length; i++) { 12396 String packageName = packageNames[i]; 12397 boolean changed = false; 12398 final int appId; 12399 synchronized (mPackages) { 12400 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12401 if (pkgSetting == null) { 12402 Slog.w(TAG, "Could not find package setting for package \"" + packageName 12403 + "\". Skipping suspending/un-suspending."); 12404 unactionedPackages.add(packageName); 12405 continue; 12406 } 12407 appId = pkgSetting.appId; 12408 if (pkgSetting.getSuspended(userId) != suspended) { 12409 if (!canSuspendPackageForUserLocked(packageName, userId)) { 12410 unactionedPackages.add(packageName); 12411 continue; 12412 } 12413 pkgSetting.setSuspended(suspended, userId); 12414 mSettings.writePackageRestrictionsLPr(userId); 12415 changed = true; 12416 changedPackages.add(packageName); 12417 } 12418 } 12419 12420 if (changed && suspended) { 12421 killApplication(packageName, UserHandle.getUid(userId, appId), 12422 "suspending package"); 12423 } 12424 } 12425 } finally { 12426 Binder.restoreCallingIdentity(callingId); 12427 } 12428 12429 if (!changedPackages.isEmpty()) { 12430 sendPackagesSuspendedForUser(changedPackages.toArray( 12431 new String[changedPackages.size()]), userId, suspended); 12432 } 12433 12434 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 12435 } 12436 12437 @Override 12438 public boolean isPackageSuspendedForUser(String packageName, int userId) { 12439 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12440 true /* requireFullPermission */, false /* checkShell */, 12441 "isPackageSuspendedForUser for user " + userId); 12442 synchronized (mPackages) { 12443 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12444 if (pkgSetting == null) { 12445 throw new IllegalArgumentException("Unknown target package: " + packageName); 12446 } 12447 return pkgSetting.getSuspended(userId); 12448 } 12449 } 12450 12451 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 12452 if (isPackageDeviceAdmin(packageName, userId)) { 12453 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12454 + "\": has an active device admin"); 12455 return false; 12456 } 12457 12458 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 12459 if (packageName.equals(activeLauncherPackageName)) { 12460 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12461 + "\": contains the active launcher"); 12462 return false; 12463 } 12464 12465 if (packageName.equals(mRequiredInstallerPackage)) { 12466 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12467 + "\": required for package installation"); 12468 return false; 12469 } 12470 12471 if (packageName.equals(mRequiredUninstallerPackage)) { 12472 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12473 + "\": required for package uninstallation"); 12474 return false; 12475 } 12476 12477 if (packageName.equals(mRequiredVerifierPackage)) { 12478 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12479 + "\": required for package verification"); 12480 return false; 12481 } 12482 12483 if (packageName.equals(getDefaultDialerPackageName(userId))) { 12484 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12485 + "\": is the default dialer"); 12486 return false; 12487 } 12488 12489 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12490 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12491 + "\": protected package"); 12492 return false; 12493 } 12494 12495 return true; 12496 } 12497 12498 private String getActiveLauncherPackageName(int userId) { 12499 Intent intent = new Intent(Intent.ACTION_MAIN); 12500 intent.addCategory(Intent.CATEGORY_HOME); 12501 ResolveInfo resolveInfo = resolveIntent( 12502 intent, 12503 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 12504 PackageManager.MATCH_DEFAULT_ONLY, 12505 userId); 12506 12507 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 12508 } 12509 12510 private String getDefaultDialerPackageName(int userId) { 12511 synchronized (mPackages) { 12512 return mSettings.getDefaultDialerPackageNameLPw(userId); 12513 } 12514 } 12515 12516 @Override 12517 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 12518 mContext.enforceCallingOrSelfPermission( 12519 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12520 "Only package verification agents can verify applications"); 12521 12522 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12523 final PackageVerificationResponse response = new PackageVerificationResponse( 12524 verificationCode, Binder.getCallingUid()); 12525 msg.arg1 = id; 12526 msg.obj = response; 12527 mHandler.sendMessage(msg); 12528 } 12529 12530 @Override 12531 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12532 long millisecondsToDelay) { 12533 mContext.enforceCallingOrSelfPermission( 12534 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12535 "Only package verification agents can extend verification timeouts"); 12536 12537 final PackageVerificationState state = mPendingVerification.get(id); 12538 final PackageVerificationResponse response = new PackageVerificationResponse( 12539 verificationCodeAtTimeout, Binder.getCallingUid()); 12540 12541 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12542 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12543 } 12544 if (millisecondsToDelay < 0) { 12545 millisecondsToDelay = 0; 12546 } 12547 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12548 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12549 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12550 } 12551 12552 if ((state != null) && !state.timeoutExtended()) { 12553 state.extendTimeout(); 12554 12555 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12556 msg.arg1 = id; 12557 msg.obj = response; 12558 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12559 } 12560 } 12561 12562 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12563 int verificationCode, UserHandle user) { 12564 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12565 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12566 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12567 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12568 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12569 12570 mContext.sendBroadcastAsUser(intent, user, 12571 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12572 } 12573 12574 private ComponentName matchComponentForVerifier(String packageName, 12575 List<ResolveInfo> receivers) { 12576 ActivityInfo targetReceiver = null; 12577 12578 final int NR = receivers.size(); 12579 for (int i = 0; i < NR; i++) { 12580 final ResolveInfo info = receivers.get(i); 12581 if (info.activityInfo == null) { 12582 continue; 12583 } 12584 12585 if (packageName.equals(info.activityInfo.packageName)) { 12586 targetReceiver = info.activityInfo; 12587 break; 12588 } 12589 } 12590 12591 if (targetReceiver == null) { 12592 return null; 12593 } 12594 12595 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12596 } 12597 12598 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12599 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12600 if (pkgInfo.verifiers.length == 0) { 12601 return null; 12602 } 12603 12604 final int N = pkgInfo.verifiers.length; 12605 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12606 for (int i = 0; i < N; i++) { 12607 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12608 12609 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12610 receivers); 12611 if (comp == null) { 12612 continue; 12613 } 12614 12615 final int verifierUid = getUidForVerifier(verifierInfo); 12616 if (verifierUid == -1) { 12617 continue; 12618 } 12619 12620 if (DEBUG_VERIFY) { 12621 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12622 + " with the correct signature"); 12623 } 12624 sufficientVerifiers.add(comp); 12625 verificationState.addSufficientVerifier(verifierUid); 12626 } 12627 12628 return sufficientVerifiers; 12629 } 12630 12631 private int getUidForVerifier(VerifierInfo verifierInfo) { 12632 synchronized (mPackages) { 12633 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12634 if (pkg == null) { 12635 return -1; 12636 } else if (pkg.mSignatures.length != 1) { 12637 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12638 + " has more than one signature; ignoring"); 12639 return -1; 12640 } 12641 12642 /* 12643 * If the public key of the package's signature does not match 12644 * our expected public key, then this is a different package and 12645 * we should skip. 12646 */ 12647 12648 final byte[] expectedPublicKey; 12649 try { 12650 final Signature verifierSig = pkg.mSignatures[0]; 12651 final PublicKey publicKey = verifierSig.getPublicKey(); 12652 expectedPublicKey = publicKey.getEncoded(); 12653 } catch (CertificateException e) { 12654 return -1; 12655 } 12656 12657 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12658 12659 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12660 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12661 + " does not have the expected public key; ignoring"); 12662 return -1; 12663 } 12664 12665 return pkg.applicationInfo.uid; 12666 } 12667 } 12668 12669 @Override 12670 public void finishPackageInstall(int token, boolean didLaunch) { 12671 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12672 12673 if (DEBUG_INSTALL) { 12674 Slog.v(TAG, "BM finishing package install for " + token); 12675 } 12676 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12677 12678 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12679 mHandler.sendMessage(msg); 12680 } 12681 12682 /** 12683 * Get the verification agent timeout. 12684 * 12685 * @return verification timeout in milliseconds 12686 */ 12687 private long getVerificationTimeout() { 12688 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12689 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12690 DEFAULT_VERIFICATION_TIMEOUT); 12691 } 12692 12693 /** 12694 * Get the default verification agent response code. 12695 * 12696 * @return default verification response code 12697 */ 12698 private int getDefaultVerificationResponse() { 12699 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12700 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12701 DEFAULT_VERIFICATION_RESPONSE); 12702 } 12703 12704 /** 12705 * Check whether or not package verification has been enabled. 12706 * 12707 * @return true if verification should be performed 12708 */ 12709 private boolean isVerificationEnabled(int userId, int installFlags) { 12710 if (!DEFAULT_VERIFY_ENABLE) { 12711 return false; 12712 } 12713 // Ephemeral apps don't get the full verification treatment 12714 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12715 if (DEBUG_EPHEMERAL) { 12716 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12717 } 12718 return false; 12719 } 12720 12721 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12722 12723 // Check if installing from ADB 12724 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12725 // Do not run verification in a test harness environment 12726 if (ActivityManager.isRunningInTestHarness()) { 12727 return false; 12728 } 12729 if (ensureVerifyAppsEnabled) { 12730 return true; 12731 } 12732 // Check if the developer does not want package verification for ADB installs 12733 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12734 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12735 return false; 12736 } 12737 } 12738 12739 if (ensureVerifyAppsEnabled) { 12740 return true; 12741 } 12742 12743 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12744 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12745 } 12746 12747 @Override 12748 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12749 throws RemoteException { 12750 mContext.enforceCallingOrSelfPermission( 12751 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12752 "Only intentfilter verification agents can verify applications"); 12753 12754 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12755 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12756 Binder.getCallingUid(), verificationCode, failedDomains); 12757 msg.arg1 = id; 12758 msg.obj = response; 12759 mHandler.sendMessage(msg); 12760 } 12761 12762 @Override 12763 public int getIntentVerificationStatus(String packageName, int userId) { 12764 synchronized (mPackages) { 12765 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12766 } 12767 } 12768 12769 @Override 12770 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12771 mContext.enforceCallingOrSelfPermission( 12772 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12773 12774 boolean result = false; 12775 synchronized (mPackages) { 12776 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12777 } 12778 if (result) { 12779 scheduleWritePackageRestrictionsLocked(userId); 12780 } 12781 return result; 12782 } 12783 12784 @Override 12785 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12786 String packageName) { 12787 synchronized (mPackages) { 12788 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12789 } 12790 } 12791 12792 @Override 12793 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12794 if (TextUtils.isEmpty(packageName)) { 12795 return ParceledListSlice.emptyList(); 12796 } 12797 synchronized (mPackages) { 12798 PackageParser.Package pkg = mPackages.get(packageName); 12799 if (pkg == null || pkg.activities == null) { 12800 return ParceledListSlice.emptyList(); 12801 } 12802 final int count = pkg.activities.size(); 12803 ArrayList<IntentFilter> result = new ArrayList<>(); 12804 for (int n=0; n<count; n++) { 12805 PackageParser.Activity activity = pkg.activities.get(n); 12806 if (activity.intents != null && activity.intents.size() > 0) { 12807 result.addAll(activity.intents); 12808 } 12809 } 12810 return new ParceledListSlice<>(result); 12811 } 12812 } 12813 12814 @Override 12815 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12816 mContext.enforceCallingOrSelfPermission( 12817 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12818 12819 synchronized (mPackages) { 12820 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12821 if (packageName != null) { 12822 result |= updateIntentVerificationStatus(packageName, 12823 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12824 userId); 12825 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12826 packageName, userId); 12827 } 12828 return result; 12829 } 12830 } 12831 12832 @Override 12833 public String getDefaultBrowserPackageName(int userId) { 12834 synchronized (mPackages) { 12835 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12836 } 12837 } 12838 12839 /** 12840 * Get the "allow unknown sources" setting. 12841 * 12842 * @return the current "allow unknown sources" setting 12843 */ 12844 private int getUnknownSourcesSettings() { 12845 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12846 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12847 -1); 12848 } 12849 12850 @Override 12851 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12852 final int uid = Binder.getCallingUid(); 12853 // writer 12854 synchronized (mPackages) { 12855 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12856 if (targetPackageSetting == null) { 12857 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12858 } 12859 12860 PackageSetting installerPackageSetting; 12861 if (installerPackageName != null) { 12862 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12863 if (installerPackageSetting == null) { 12864 throw new IllegalArgumentException("Unknown installer package: " 12865 + installerPackageName); 12866 } 12867 } else { 12868 installerPackageSetting = null; 12869 } 12870 12871 Signature[] callerSignature; 12872 Object obj = mSettings.getUserIdLPr(uid); 12873 if (obj != null) { 12874 if (obj instanceof SharedUserSetting) { 12875 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12876 } else if (obj instanceof PackageSetting) { 12877 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12878 } else { 12879 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12880 } 12881 } else { 12882 throw new SecurityException("Unknown calling UID: " + uid); 12883 } 12884 12885 // Verify: can't set installerPackageName to a package that is 12886 // not signed with the same cert as the caller. 12887 if (installerPackageSetting != null) { 12888 if (compareSignatures(callerSignature, 12889 installerPackageSetting.signatures.mSignatures) 12890 != PackageManager.SIGNATURE_MATCH) { 12891 throw new SecurityException( 12892 "Caller does not have same cert as new installer package " 12893 + installerPackageName); 12894 } 12895 } 12896 12897 // Verify: if target already has an installer package, it must 12898 // be signed with the same cert as the caller. 12899 if (targetPackageSetting.installerPackageName != null) { 12900 PackageSetting setting = mSettings.mPackages.get( 12901 targetPackageSetting.installerPackageName); 12902 // If the currently set package isn't valid, then it's always 12903 // okay to change it. 12904 if (setting != null) { 12905 if (compareSignatures(callerSignature, 12906 setting.signatures.mSignatures) 12907 != PackageManager.SIGNATURE_MATCH) { 12908 throw new SecurityException( 12909 "Caller does not have same cert as old installer package " 12910 + targetPackageSetting.installerPackageName); 12911 } 12912 } 12913 } 12914 12915 // Okay! 12916 targetPackageSetting.installerPackageName = installerPackageName; 12917 if (installerPackageName != null) { 12918 mSettings.mInstallerPackages.add(installerPackageName); 12919 } 12920 scheduleWriteSettingsLocked(); 12921 } 12922 } 12923 12924 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12925 // Queue up an async operation since the package installation may take a little while. 12926 mHandler.post(new Runnable() { 12927 public void run() { 12928 mHandler.removeCallbacks(this); 12929 // Result object to be returned 12930 PackageInstalledInfo res = new PackageInstalledInfo(); 12931 res.setReturnCode(currentStatus); 12932 res.uid = -1; 12933 res.pkg = null; 12934 res.removedInfo = null; 12935 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12936 args.doPreInstall(res.returnCode); 12937 synchronized (mInstallLock) { 12938 installPackageTracedLI(args, res); 12939 } 12940 args.doPostInstall(res.returnCode, res.uid); 12941 } 12942 12943 // A restore should be performed at this point if (a) the install 12944 // succeeded, (b) the operation is not an update, and (c) the new 12945 // package has not opted out of backup participation. 12946 final boolean update = res.removedInfo != null 12947 && res.removedInfo.removedPackage != null; 12948 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12949 boolean doRestore = !update 12950 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12951 12952 // Set up the post-install work request bookkeeping. This will be used 12953 // and cleaned up by the post-install event handling regardless of whether 12954 // there's a restore pass performed. Token values are >= 1. 12955 int token; 12956 if (mNextInstallToken < 0) mNextInstallToken = 1; 12957 token = mNextInstallToken++; 12958 12959 PostInstallData data = new PostInstallData(args, res); 12960 mRunningInstalls.put(token, data); 12961 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12962 12963 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12964 // Pass responsibility to the Backup Manager. It will perform a 12965 // restore if appropriate, then pass responsibility back to the 12966 // Package Manager to run the post-install observer callbacks 12967 // and broadcasts. 12968 IBackupManager bm = IBackupManager.Stub.asInterface( 12969 ServiceManager.getService(Context.BACKUP_SERVICE)); 12970 if (bm != null) { 12971 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12972 + " to BM for possible restore"); 12973 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12974 try { 12975 // TODO: http://b/22388012 12976 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12977 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12978 } else { 12979 doRestore = false; 12980 } 12981 } catch (RemoteException e) { 12982 // can't happen; the backup manager is local 12983 } catch (Exception e) { 12984 Slog.e(TAG, "Exception trying to enqueue restore", e); 12985 doRestore = false; 12986 } 12987 } else { 12988 Slog.e(TAG, "Backup Manager not found!"); 12989 doRestore = false; 12990 } 12991 } 12992 12993 if (!doRestore) { 12994 // No restore possible, or the Backup Manager was mysteriously not 12995 // available -- just fire the post-install work request directly. 12996 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12997 12998 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12999 13000 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 13001 mHandler.sendMessage(msg); 13002 } 13003 } 13004 }); 13005 } 13006 13007 /** 13008 * Callback from PackageSettings whenever an app is first transitioned out of the 13009 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 13010 * the app was "launched" for a restoreAtInstall operation. Therefore we check 13011 * here whether the app is the target of an ongoing install, and only send the 13012 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 13013 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 13014 * handling. 13015 */ 13016 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 13017 // Serialize this with the rest of the install-process message chain. In the 13018 // restore-at-install case, this Runnable will necessarily run before the 13019 // POST_INSTALL message is processed, so the contents of mRunningInstalls 13020 // are coherent. In the non-restore case, the app has already completed install 13021 // and been launched through some other means, so it is not in a problematic 13022 // state for observers to see the FIRST_LAUNCH signal. 13023 mHandler.post(new Runnable() { 13024 @Override 13025 public void run() { 13026 for (int i = 0; i < mRunningInstalls.size(); i++) { 13027 final PostInstallData data = mRunningInstalls.valueAt(i); 13028 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13029 continue; 13030 } 13031 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 13032 // right package; but is it for the right user? 13033 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 13034 if (userId == data.res.newUsers[uIndex]) { 13035 if (DEBUG_BACKUP) { 13036 Slog.i(TAG, "Package " + pkgName 13037 + " being restored so deferring FIRST_LAUNCH"); 13038 } 13039 return; 13040 } 13041 } 13042 } 13043 } 13044 // didn't find it, so not being restored 13045 if (DEBUG_BACKUP) { 13046 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 13047 } 13048 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 13049 } 13050 }); 13051 } 13052 13053 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 13054 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 13055 installerPkg, null, userIds); 13056 } 13057 13058 private abstract class HandlerParams { 13059 private static final int MAX_RETRIES = 4; 13060 13061 /** 13062 * Number of times startCopy() has been attempted and had a non-fatal 13063 * error. 13064 */ 13065 private int mRetries = 0; 13066 13067 /** User handle for the user requesting the information or installation. */ 13068 private final UserHandle mUser; 13069 String traceMethod; 13070 int traceCookie; 13071 13072 HandlerParams(UserHandle user) { 13073 mUser = user; 13074 } 13075 13076 UserHandle getUser() { 13077 return mUser; 13078 } 13079 13080 HandlerParams setTraceMethod(String traceMethod) { 13081 this.traceMethod = traceMethod; 13082 return this; 13083 } 13084 13085 HandlerParams setTraceCookie(int traceCookie) { 13086 this.traceCookie = traceCookie; 13087 return this; 13088 } 13089 13090 final boolean startCopy() { 13091 boolean res; 13092 try { 13093 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 13094 13095 if (++mRetries > MAX_RETRIES) { 13096 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 13097 mHandler.sendEmptyMessage(MCS_GIVE_UP); 13098 handleServiceError(); 13099 return false; 13100 } else { 13101 handleStartCopy(); 13102 res = true; 13103 } 13104 } catch (RemoteException e) { 13105 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 13106 mHandler.sendEmptyMessage(MCS_RECONNECT); 13107 res = false; 13108 } 13109 handleReturnCode(); 13110 return res; 13111 } 13112 13113 final void serviceError() { 13114 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 13115 handleServiceError(); 13116 handleReturnCode(); 13117 } 13118 13119 abstract void handleStartCopy() throws RemoteException; 13120 abstract void handleServiceError(); 13121 abstract void handleReturnCode(); 13122 } 13123 13124 class MeasureParams extends HandlerParams { 13125 private final PackageStats mStats; 13126 private boolean mSuccess; 13127 13128 private final IPackageStatsObserver mObserver; 13129 13130 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 13131 super(new UserHandle(stats.userHandle)); 13132 mObserver = observer; 13133 mStats = stats; 13134 } 13135 13136 @Override 13137 public String toString() { 13138 return "MeasureParams{" 13139 + Integer.toHexString(System.identityHashCode(this)) 13140 + " " + mStats.packageName + "}"; 13141 } 13142 13143 @Override 13144 void handleStartCopy() throws RemoteException { 13145 synchronized (mInstallLock) { 13146 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 13147 } 13148 13149 if (mSuccess) { 13150 boolean mounted = false; 13151 try { 13152 final String status = Environment.getExternalStorageState(); 13153 mounted = (Environment.MEDIA_MOUNTED.equals(status) 13154 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 13155 } catch (Exception e) { 13156 } 13157 13158 if (mounted) { 13159 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 13160 13161 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 13162 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 13163 13164 mStats.externalDataSize = calculateDirectorySize(mContainerService, 13165 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 13166 13167 // Always subtract cache size, since it's a subdirectory 13168 mStats.externalDataSize -= mStats.externalCacheSize; 13169 13170 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 13171 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 13172 13173 mStats.externalObbSize = calculateDirectorySize(mContainerService, 13174 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 13175 } 13176 } 13177 } 13178 13179 @Override 13180 void handleReturnCode() { 13181 if (mObserver != null) { 13182 try { 13183 mObserver.onGetStatsCompleted(mStats, mSuccess); 13184 } catch (RemoteException e) { 13185 Slog.i(TAG, "Observer no longer exists."); 13186 } 13187 } 13188 } 13189 13190 @Override 13191 void handleServiceError() { 13192 Slog.e(TAG, "Could not measure application " + mStats.packageName 13193 + " external storage"); 13194 } 13195 } 13196 13197 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 13198 throws RemoteException { 13199 long result = 0; 13200 for (File path : paths) { 13201 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 13202 } 13203 return result; 13204 } 13205 13206 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 13207 for (File path : paths) { 13208 try { 13209 mcs.clearDirectory(path.getAbsolutePath()); 13210 } catch (RemoteException e) { 13211 } 13212 } 13213 } 13214 13215 static class OriginInfo { 13216 /** 13217 * Location where install is coming from, before it has been 13218 * copied/renamed into place. This could be a single monolithic APK 13219 * file, or a cluster directory. This location may be untrusted. 13220 */ 13221 final File file; 13222 final String cid; 13223 13224 /** 13225 * Flag indicating that {@link #file} or {@link #cid} has already been 13226 * staged, meaning downstream users don't need to defensively copy the 13227 * contents. 13228 */ 13229 final boolean staged; 13230 13231 /** 13232 * Flag indicating that {@link #file} or {@link #cid} is an already 13233 * installed app that is being moved. 13234 */ 13235 final boolean existing; 13236 13237 final String resolvedPath; 13238 final File resolvedFile; 13239 13240 static OriginInfo fromNothing() { 13241 return new OriginInfo(null, null, false, false); 13242 } 13243 13244 static OriginInfo fromUntrustedFile(File file) { 13245 return new OriginInfo(file, null, false, false); 13246 } 13247 13248 static OriginInfo fromExistingFile(File file) { 13249 return new OriginInfo(file, null, false, true); 13250 } 13251 13252 static OriginInfo fromStagedFile(File file) { 13253 return new OriginInfo(file, null, true, false); 13254 } 13255 13256 static OriginInfo fromStagedContainer(String cid) { 13257 return new OriginInfo(null, cid, true, false); 13258 } 13259 13260 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 13261 this.file = file; 13262 this.cid = cid; 13263 this.staged = staged; 13264 this.existing = existing; 13265 13266 if (cid != null) { 13267 resolvedPath = PackageHelper.getSdDir(cid); 13268 resolvedFile = new File(resolvedPath); 13269 } else if (file != null) { 13270 resolvedPath = file.getAbsolutePath(); 13271 resolvedFile = file; 13272 } else { 13273 resolvedPath = null; 13274 resolvedFile = null; 13275 } 13276 } 13277 } 13278 13279 static class MoveInfo { 13280 final int moveId; 13281 final String fromUuid; 13282 final String toUuid; 13283 final String packageName; 13284 final String dataAppName; 13285 final int appId; 13286 final String seinfo; 13287 final int targetSdkVersion; 13288 13289 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 13290 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 13291 this.moveId = moveId; 13292 this.fromUuid = fromUuid; 13293 this.toUuid = toUuid; 13294 this.packageName = packageName; 13295 this.dataAppName = dataAppName; 13296 this.appId = appId; 13297 this.seinfo = seinfo; 13298 this.targetSdkVersion = targetSdkVersion; 13299 } 13300 } 13301 13302 static class VerificationInfo { 13303 /** A constant used to indicate that a uid value is not present. */ 13304 public static final int NO_UID = -1; 13305 13306 /** URI referencing where the package was downloaded from. */ 13307 final Uri originatingUri; 13308 13309 /** HTTP referrer URI associated with the originatingURI. */ 13310 final Uri referrer; 13311 13312 /** UID of the application that the install request originated from. */ 13313 final int originatingUid; 13314 13315 /** UID of application requesting the install */ 13316 final int installerUid; 13317 13318 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 13319 this.originatingUri = originatingUri; 13320 this.referrer = referrer; 13321 this.originatingUid = originatingUid; 13322 this.installerUid = installerUid; 13323 } 13324 } 13325 13326 class InstallParams extends HandlerParams { 13327 final OriginInfo origin; 13328 final MoveInfo move; 13329 final IPackageInstallObserver2 observer; 13330 int installFlags; 13331 final String installerPackageName; 13332 final String volumeUuid; 13333 private InstallArgs mArgs; 13334 private int mRet; 13335 final String packageAbiOverride; 13336 final String[] grantedRuntimePermissions; 13337 final VerificationInfo verificationInfo; 13338 final Certificate[][] certificates; 13339 13340 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13341 int installFlags, String installerPackageName, String volumeUuid, 13342 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 13343 String[] grantedPermissions, Certificate[][] certificates) { 13344 super(user); 13345 this.origin = origin; 13346 this.move = move; 13347 this.observer = observer; 13348 this.installFlags = installFlags; 13349 this.installerPackageName = installerPackageName; 13350 this.volumeUuid = volumeUuid; 13351 this.verificationInfo = verificationInfo; 13352 this.packageAbiOverride = packageAbiOverride; 13353 this.grantedRuntimePermissions = grantedPermissions; 13354 this.certificates = certificates; 13355 } 13356 13357 @Override 13358 public String toString() { 13359 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 13360 + " file=" + origin.file + " cid=" + origin.cid + "}"; 13361 } 13362 13363 private int installLocationPolicy(PackageInfoLite pkgLite) { 13364 String packageName = pkgLite.packageName; 13365 int installLocation = pkgLite.installLocation; 13366 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13367 // reader 13368 synchronized (mPackages) { 13369 // Currently installed package which the new package is attempting to replace or 13370 // null if no such package is installed. 13371 PackageParser.Package installedPkg = mPackages.get(packageName); 13372 // Package which currently owns the data which the new package will own if installed. 13373 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 13374 // will be null whereas dataOwnerPkg will contain information about the package 13375 // which was uninstalled while keeping its data. 13376 PackageParser.Package dataOwnerPkg = installedPkg; 13377 if (dataOwnerPkg == null) { 13378 PackageSetting ps = mSettings.mPackages.get(packageName); 13379 if (ps != null) { 13380 dataOwnerPkg = ps.pkg; 13381 } 13382 } 13383 13384 if (dataOwnerPkg != null) { 13385 // If installed, the package will get access to data left on the device by its 13386 // predecessor. As a security measure, this is permited only if this is not a 13387 // version downgrade or if the predecessor package is marked as debuggable and 13388 // a downgrade is explicitly requested. 13389 // 13390 // On debuggable platform builds, downgrades are permitted even for 13391 // non-debuggable packages to make testing easier. Debuggable platform builds do 13392 // not offer security guarantees and thus it's OK to disable some security 13393 // mechanisms to make debugging/testing easier on those builds. However, even on 13394 // debuggable builds downgrades of packages are permitted only if requested via 13395 // installFlags. This is because we aim to keep the behavior of debuggable 13396 // platform builds as close as possible to the behavior of non-debuggable 13397 // platform builds. 13398 final boolean downgradeRequested = 13399 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 13400 final boolean packageDebuggable = 13401 (dataOwnerPkg.applicationInfo.flags 13402 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 13403 final boolean downgradePermitted = 13404 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 13405 if (!downgradePermitted) { 13406 try { 13407 checkDowngrade(dataOwnerPkg, pkgLite); 13408 } catch (PackageManagerException e) { 13409 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 13410 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 13411 } 13412 } 13413 } 13414 13415 if (installedPkg != null) { 13416 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13417 // Check for updated system application. 13418 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13419 if (onSd) { 13420 Slog.w(TAG, "Cannot install update to system app on sdcard"); 13421 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 13422 } 13423 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13424 } else { 13425 if (onSd) { 13426 // Install flag overrides everything. 13427 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13428 } 13429 // If current upgrade specifies particular preference 13430 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 13431 // Application explicitly specified internal. 13432 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13433 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 13434 // App explictly prefers external. Let policy decide 13435 } else { 13436 // Prefer previous location 13437 if (isExternal(installedPkg)) { 13438 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13439 } 13440 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13441 } 13442 } 13443 } else { 13444 // Invalid install. Return error code 13445 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 13446 } 13447 } 13448 } 13449 // All the special cases have been taken care of. 13450 // Return result based on recommended install location. 13451 if (onSd) { 13452 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13453 } 13454 return pkgLite.recommendedInstallLocation; 13455 } 13456 13457 /* 13458 * Invoke remote method to get package information and install 13459 * location values. Override install location based on default 13460 * policy if needed and then create install arguments based 13461 * on the install location. 13462 */ 13463 public void handleStartCopy() throws RemoteException { 13464 int ret = PackageManager.INSTALL_SUCCEEDED; 13465 13466 // If we're already staged, we've firmly committed to an install location 13467 if (origin.staged) { 13468 if (origin.file != null) { 13469 installFlags |= PackageManager.INSTALL_INTERNAL; 13470 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13471 } else if (origin.cid != null) { 13472 installFlags |= PackageManager.INSTALL_EXTERNAL; 13473 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13474 } else { 13475 throw new IllegalStateException("Invalid stage location"); 13476 } 13477 } 13478 13479 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13480 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 13481 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13482 PackageInfoLite pkgLite = null; 13483 13484 if (onInt && onSd) { 13485 // Check if both bits are set. 13486 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 13487 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13488 } else if (onSd && ephemeral) { 13489 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 13490 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13491 } else { 13492 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 13493 packageAbiOverride); 13494 13495 if (DEBUG_EPHEMERAL && ephemeral) { 13496 Slog.v(TAG, "pkgLite for install: " + pkgLite); 13497 } 13498 13499 /* 13500 * If we have too little free space, try to free cache 13501 * before giving up. 13502 */ 13503 if (!origin.staged && pkgLite.recommendedInstallLocation 13504 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13505 // TODO: focus freeing disk space on the target device 13506 final StorageManager storage = StorageManager.from(mContext); 13507 final long lowThreshold = storage.getStorageLowBytes( 13508 Environment.getDataDirectory()); 13509 13510 final long sizeBytes = mContainerService.calculateInstalledSize( 13511 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 13512 13513 try { 13514 mInstaller.freeCache(null, sizeBytes + lowThreshold); 13515 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 13516 installFlags, packageAbiOverride); 13517 } catch (InstallerException e) { 13518 Slog.w(TAG, "Failed to free cache", e); 13519 } 13520 13521 /* 13522 * The cache free must have deleted the file we 13523 * downloaded to install. 13524 * 13525 * TODO: fix the "freeCache" call to not delete 13526 * the file we care about. 13527 */ 13528 if (pkgLite.recommendedInstallLocation 13529 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13530 pkgLite.recommendedInstallLocation 13531 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 13532 } 13533 } 13534 } 13535 13536 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13537 int loc = pkgLite.recommendedInstallLocation; 13538 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13539 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13540 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13541 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13542 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13543 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13544 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13545 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13546 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13547 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13548 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13549 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13550 } else { 13551 // Override with defaults if needed. 13552 loc = installLocationPolicy(pkgLite); 13553 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13554 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13555 } else if (!onSd && !onInt) { 13556 // Override install location with flags 13557 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13558 // Set the flag to install on external media. 13559 installFlags |= PackageManager.INSTALL_EXTERNAL; 13560 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13561 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13562 if (DEBUG_EPHEMERAL) { 13563 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13564 } 13565 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13566 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13567 |PackageManager.INSTALL_INTERNAL); 13568 } else { 13569 // Make sure the flag for installing on external 13570 // media is unset 13571 installFlags |= PackageManager.INSTALL_INTERNAL; 13572 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13573 } 13574 } 13575 } 13576 } 13577 13578 final InstallArgs args = createInstallArgs(this); 13579 mArgs = args; 13580 13581 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13582 // TODO: http://b/22976637 13583 // Apps installed for "all" users use the device owner to verify the app 13584 UserHandle verifierUser = getUser(); 13585 if (verifierUser == UserHandle.ALL) { 13586 verifierUser = UserHandle.SYSTEM; 13587 } 13588 13589 /* 13590 * Determine if we have any installed package verifiers. If we 13591 * do, then we'll defer to them to verify the packages. 13592 */ 13593 final int requiredUid = mRequiredVerifierPackage == null ? -1 13594 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13595 verifierUser.getIdentifier()); 13596 if (!origin.existing && requiredUid != -1 13597 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13598 final Intent verification = new Intent( 13599 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13600 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13601 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13602 PACKAGE_MIME_TYPE); 13603 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13604 13605 // Query all live verifiers based on current user state 13606 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13607 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13608 13609 if (DEBUG_VERIFY) { 13610 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13611 + verification.toString() + " with " + pkgLite.verifiers.length 13612 + " optional verifiers"); 13613 } 13614 13615 final int verificationId = mPendingVerificationToken++; 13616 13617 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13618 13619 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13620 installerPackageName); 13621 13622 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13623 installFlags); 13624 13625 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13626 pkgLite.packageName); 13627 13628 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13629 pkgLite.versionCode); 13630 13631 if (verificationInfo != null) { 13632 if (verificationInfo.originatingUri != null) { 13633 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13634 verificationInfo.originatingUri); 13635 } 13636 if (verificationInfo.referrer != null) { 13637 verification.putExtra(Intent.EXTRA_REFERRER, 13638 verificationInfo.referrer); 13639 } 13640 if (verificationInfo.originatingUid >= 0) { 13641 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13642 verificationInfo.originatingUid); 13643 } 13644 if (verificationInfo.installerUid >= 0) { 13645 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13646 verificationInfo.installerUid); 13647 } 13648 } 13649 13650 final PackageVerificationState verificationState = new PackageVerificationState( 13651 requiredUid, args); 13652 13653 mPendingVerification.append(verificationId, verificationState); 13654 13655 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13656 receivers, verificationState); 13657 13658 /* 13659 * If any sufficient verifiers were listed in the package 13660 * manifest, attempt to ask them. 13661 */ 13662 if (sufficientVerifiers != null) { 13663 final int N = sufficientVerifiers.size(); 13664 if (N == 0) { 13665 Slog.i(TAG, "Additional verifiers required, but none installed."); 13666 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13667 } else { 13668 for (int i = 0; i < N; i++) { 13669 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13670 13671 final Intent sufficientIntent = new Intent(verification); 13672 sufficientIntent.setComponent(verifierComponent); 13673 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13674 } 13675 } 13676 } 13677 13678 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13679 mRequiredVerifierPackage, receivers); 13680 if (ret == PackageManager.INSTALL_SUCCEEDED 13681 && mRequiredVerifierPackage != null) { 13682 Trace.asyncTraceBegin( 13683 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13684 /* 13685 * Send the intent to the required verification agent, 13686 * but only start the verification timeout after the 13687 * target BroadcastReceivers have run. 13688 */ 13689 verification.setComponent(requiredVerifierComponent); 13690 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13691 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13692 new BroadcastReceiver() { 13693 @Override 13694 public void onReceive(Context context, Intent intent) { 13695 final Message msg = mHandler 13696 .obtainMessage(CHECK_PENDING_VERIFICATION); 13697 msg.arg1 = verificationId; 13698 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13699 } 13700 }, null, 0, null, null); 13701 13702 /* 13703 * We don't want the copy to proceed until verification 13704 * succeeds, so null out this field. 13705 */ 13706 mArgs = null; 13707 } 13708 } else { 13709 /* 13710 * No package verification is enabled, so immediately start 13711 * the remote call to initiate copy using temporary file. 13712 */ 13713 ret = args.copyApk(mContainerService, true); 13714 } 13715 } 13716 13717 mRet = ret; 13718 } 13719 13720 @Override 13721 void handleReturnCode() { 13722 // If mArgs is null, then MCS couldn't be reached. When it 13723 // reconnects, it will try again to install. At that point, this 13724 // will succeed. 13725 if (mArgs != null) { 13726 processPendingInstall(mArgs, mRet); 13727 } 13728 } 13729 13730 @Override 13731 void handleServiceError() { 13732 mArgs = createInstallArgs(this); 13733 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13734 } 13735 13736 public boolean isForwardLocked() { 13737 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13738 } 13739 } 13740 13741 /** 13742 * Used during creation of InstallArgs 13743 * 13744 * @param installFlags package installation flags 13745 * @return true if should be installed on external storage 13746 */ 13747 private static boolean installOnExternalAsec(int installFlags) { 13748 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13749 return false; 13750 } 13751 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13752 return true; 13753 } 13754 return false; 13755 } 13756 13757 /** 13758 * Used during creation of InstallArgs 13759 * 13760 * @param installFlags package installation flags 13761 * @return true if should be installed as forward locked 13762 */ 13763 private static boolean installForwardLocked(int installFlags) { 13764 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13765 } 13766 13767 private InstallArgs createInstallArgs(InstallParams params) { 13768 if (params.move != null) { 13769 return new MoveInstallArgs(params); 13770 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13771 return new AsecInstallArgs(params); 13772 } else { 13773 return new FileInstallArgs(params); 13774 } 13775 } 13776 13777 /** 13778 * Create args that describe an existing installed package. Typically used 13779 * when cleaning up old installs, or used as a move source. 13780 */ 13781 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13782 String resourcePath, String[] instructionSets) { 13783 final boolean isInAsec; 13784 if (installOnExternalAsec(installFlags)) { 13785 /* Apps on SD card are always in ASEC containers. */ 13786 isInAsec = true; 13787 } else if (installForwardLocked(installFlags) 13788 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13789 /* 13790 * Forward-locked apps are only in ASEC containers if they're the 13791 * new style 13792 */ 13793 isInAsec = true; 13794 } else { 13795 isInAsec = false; 13796 } 13797 13798 if (isInAsec) { 13799 return new AsecInstallArgs(codePath, instructionSets, 13800 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13801 } else { 13802 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13803 } 13804 } 13805 13806 static abstract class InstallArgs { 13807 /** @see InstallParams#origin */ 13808 final OriginInfo origin; 13809 /** @see InstallParams#move */ 13810 final MoveInfo move; 13811 13812 final IPackageInstallObserver2 observer; 13813 // Always refers to PackageManager flags only 13814 final int installFlags; 13815 final String installerPackageName; 13816 final String volumeUuid; 13817 final UserHandle user; 13818 final String abiOverride; 13819 final String[] installGrantPermissions; 13820 /** If non-null, drop an async trace when the install completes */ 13821 final String traceMethod; 13822 final int traceCookie; 13823 final Certificate[][] certificates; 13824 13825 // The list of instruction sets supported by this app. This is currently 13826 // only used during the rmdex() phase to clean up resources. We can get rid of this 13827 // if we move dex files under the common app path. 13828 /* nullable */ String[] instructionSets; 13829 13830 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13831 int installFlags, String installerPackageName, String volumeUuid, 13832 UserHandle user, String[] instructionSets, 13833 String abiOverride, String[] installGrantPermissions, 13834 String traceMethod, int traceCookie, Certificate[][] certificates) { 13835 this.origin = origin; 13836 this.move = move; 13837 this.installFlags = installFlags; 13838 this.observer = observer; 13839 this.installerPackageName = installerPackageName; 13840 this.volumeUuid = volumeUuid; 13841 this.user = user; 13842 this.instructionSets = instructionSets; 13843 this.abiOverride = abiOverride; 13844 this.installGrantPermissions = installGrantPermissions; 13845 this.traceMethod = traceMethod; 13846 this.traceCookie = traceCookie; 13847 this.certificates = certificates; 13848 } 13849 13850 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13851 abstract int doPreInstall(int status); 13852 13853 /** 13854 * Rename package into final resting place. All paths on the given 13855 * scanned package should be updated to reflect the rename. 13856 */ 13857 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13858 abstract int doPostInstall(int status, int uid); 13859 13860 /** @see PackageSettingBase#codePathString */ 13861 abstract String getCodePath(); 13862 /** @see PackageSettingBase#resourcePathString */ 13863 abstract String getResourcePath(); 13864 13865 // Need installer lock especially for dex file removal. 13866 abstract void cleanUpResourcesLI(); 13867 abstract boolean doPostDeleteLI(boolean delete); 13868 13869 /** 13870 * Called before the source arguments are copied. This is used mostly 13871 * for MoveParams when it needs to read the source file to put it in the 13872 * destination. 13873 */ 13874 int doPreCopy() { 13875 return PackageManager.INSTALL_SUCCEEDED; 13876 } 13877 13878 /** 13879 * Called after the source arguments are copied. This is used mostly for 13880 * MoveParams when it needs to read the source file to put it in the 13881 * destination. 13882 */ 13883 int doPostCopy(int uid) { 13884 return PackageManager.INSTALL_SUCCEEDED; 13885 } 13886 13887 protected boolean isFwdLocked() { 13888 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13889 } 13890 13891 protected boolean isExternalAsec() { 13892 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13893 } 13894 13895 protected boolean isEphemeral() { 13896 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13897 } 13898 13899 UserHandle getUser() { 13900 return user; 13901 } 13902 } 13903 13904 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13905 if (!allCodePaths.isEmpty()) { 13906 if (instructionSets == null) { 13907 throw new IllegalStateException("instructionSet == null"); 13908 } 13909 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13910 for (String codePath : allCodePaths) { 13911 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13912 try { 13913 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13914 } catch (InstallerException ignored) { 13915 } 13916 } 13917 } 13918 } 13919 } 13920 13921 /** 13922 * Logic to handle installation of non-ASEC applications, including copying 13923 * and renaming logic. 13924 */ 13925 class FileInstallArgs extends InstallArgs { 13926 private File codeFile; 13927 private File resourceFile; 13928 13929 // Example topology: 13930 // /data/app/com.example/base.apk 13931 // /data/app/com.example/split_foo.apk 13932 // /data/app/com.example/lib/arm/libfoo.so 13933 // /data/app/com.example/lib/arm64/libfoo.so 13934 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13935 13936 /** New install */ 13937 FileInstallArgs(InstallParams params) { 13938 super(params.origin, params.move, params.observer, params.installFlags, 13939 params.installerPackageName, params.volumeUuid, 13940 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13941 params.grantedRuntimePermissions, 13942 params.traceMethod, params.traceCookie, params.certificates); 13943 if (isFwdLocked()) { 13944 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13945 } 13946 } 13947 13948 /** Existing install */ 13949 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13950 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13951 null, null, null, 0, null /*certificates*/); 13952 this.codeFile = (codePath != null) ? new File(codePath) : null; 13953 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13954 } 13955 13956 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13957 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13958 try { 13959 return doCopyApk(imcs, temp); 13960 } finally { 13961 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13962 } 13963 } 13964 13965 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13966 if (origin.staged) { 13967 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13968 codeFile = origin.file; 13969 resourceFile = origin.file; 13970 return PackageManager.INSTALL_SUCCEEDED; 13971 } 13972 13973 try { 13974 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13975 final File tempDir = 13976 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13977 codeFile = tempDir; 13978 resourceFile = tempDir; 13979 } catch (IOException e) { 13980 Slog.w(TAG, "Failed to create copy file: " + e); 13981 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13982 } 13983 13984 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13985 @Override 13986 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13987 if (!FileUtils.isValidExtFilename(name)) { 13988 throw new IllegalArgumentException("Invalid filename: " + name); 13989 } 13990 try { 13991 final File file = new File(codeFile, name); 13992 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13993 O_RDWR | O_CREAT, 0644); 13994 Os.chmod(file.getAbsolutePath(), 0644); 13995 return new ParcelFileDescriptor(fd); 13996 } catch (ErrnoException e) { 13997 throw new RemoteException("Failed to open: " + e.getMessage()); 13998 } 13999 } 14000 }; 14001 14002 int ret = PackageManager.INSTALL_SUCCEEDED; 14003 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 14004 if (ret != PackageManager.INSTALL_SUCCEEDED) { 14005 Slog.e(TAG, "Failed to copy package"); 14006 return ret; 14007 } 14008 14009 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 14010 NativeLibraryHelper.Handle handle = null; 14011 try { 14012 handle = NativeLibraryHelper.Handle.create(codeFile); 14013 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 14014 abiOverride); 14015 } catch (IOException e) { 14016 Slog.e(TAG, "Copying native libraries failed", e); 14017 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14018 } finally { 14019 IoUtils.closeQuietly(handle); 14020 } 14021 14022 return ret; 14023 } 14024 14025 int doPreInstall(int status) { 14026 if (status != PackageManager.INSTALL_SUCCEEDED) { 14027 cleanUp(); 14028 } 14029 return status; 14030 } 14031 14032 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14033 if (status != PackageManager.INSTALL_SUCCEEDED) { 14034 cleanUp(); 14035 return false; 14036 } 14037 14038 final File targetDir = codeFile.getParentFile(); 14039 final File beforeCodeFile = codeFile; 14040 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 14041 14042 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 14043 try { 14044 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 14045 } catch (ErrnoException e) { 14046 Slog.w(TAG, "Failed to rename", e); 14047 return false; 14048 } 14049 14050 if (!SELinux.restoreconRecursive(afterCodeFile)) { 14051 Slog.w(TAG, "Failed to restorecon"); 14052 return false; 14053 } 14054 14055 // Reflect the rename internally 14056 codeFile = afterCodeFile; 14057 resourceFile = afterCodeFile; 14058 14059 // Reflect the rename in scanned details 14060 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14061 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14062 afterCodeFile, pkg.baseCodePath)); 14063 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14064 afterCodeFile, pkg.splitCodePaths)); 14065 14066 // Reflect the rename in app info 14067 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14068 pkg.setApplicationInfoCodePath(pkg.codePath); 14069 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14070 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14071 pkg.setApplicationInfoResourcePath(pkg.codePath); 14072 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14073 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14074 14075 return true; 14076 } 14077 14078 int doPostInstall(int status, int uid) { 14079 if (status != PackageManager.INSTALL_SUCCEEDED) { 14080 cleanUp(); 14081 } 14082 return status; 14083 } 14084 14085 @Override 14086 String getCodePath() { 14087 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14088 } 14089 14090 @Override 14091 String getResourcePath() { 14092 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14093 } 14094 14095 private boolean cleanUp() { 14096 if (codeFile == null || !codeFile.exists()) { 14097 return false; 14098 } 14099 14100 removeCodePathLI(codeFile); 14101 14102 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 14103 resourceFile.delete(); 14104 } 14105 14106 return true; 14107 } 14108 14109 void cleanUpResourcesLI() { 14110 // Try enumerating all code paths before deleting 14111 List<String> allCodePaths = Collections.EMPTY_LIST; 14112 if (codeFile != null && codeFile.exists()) { 14113 try { 14114 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14115 allCodePaths = pkg.getAllCodePaths(); 14116 } catch (PackageParserException e) { 14117 // Ignored; we tried our best 14118 } 14119 } 14120 14121 cleanUp(); 14122 removeDexFiles(allCodePaths, instructionSets); 14123 } 14124 14125 boolean doPostDeleteLI(boolean delete) { 14126 // XXX err, shouldn't we respect the delete flag? 14127 cleanUpResourcesLI(); 14128 return true; 14129 } 14130 } 14131 14132 private boolean isAsecExternal(String cid) { 14133 final String asecPath = PackageHelper.getSdFilesystem(cid); 14134 return !asecPath.startsWith(mAsecInternalPath); 14135 } 14136 14137 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 14138 PackageManagerException { 14139 if (copyRet < 0) { 14140 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 14141 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 14142 throw new PackageManagerException(copyRet, message); 14143 } 14144 } 14145 } 14146 14147 /** 14148 * Extract the StorageManagerService "container ID" from the full code path of an 14149 * .apk. 14150 */ 14151 static String cidFromCodePath(String fullCodePath) { 14152 int eidx = fullCodePath.lastIndexOf("/"); 14153 String subStr1 = fullCodePath.substring(0, eidx); 14154 int sidx = subStr1.lastIndexOf("/"); 14155 return subStr1.substring(sidx+1, eidx); 14156 } 14157 14158 /** 14159 * Logic to handle installation of ASEC applications, including copying and 14160 * renaming logic. 14161 */ 14162 class AsecInstallArgs extends InstallArgs { 14163 static final String RES_FILE_NAME = "pkg.apk"; 14164 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 14165 14166 String cid; 14167 String packagePath; 14168 String resourcePath; 14169 14170 /** New install */ 14171 AsecInstallArgs(InstallParams params) { 14172 super(params.origin, params.move, params.observer, params.installFlags, 14173 params.installerPackageName, params.volumeUuid, 14174 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14175 params.grantedRuntimePermissions, 14176 params.traceMethod, params.traceCookie, params.certificates); 14177 } 14178 14179 /** Existing install */ 14180 AsecInstallArgs(String fullCodePath, String[] instructionSets, 14181 boolean isExternal, boolean isForwardLocked) { 14182 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 14183 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 14184 instructionSets, null, null, null, 0, null /*certificates*/); 14185 // Hackily pretend we're still looking at a full code path 14186 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 14187 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 14188 } 14189 14190 // Extract cid from fullCodePath 14191 int eidx = fullCodePath.lastIndexOf("/"); 14192 String subStr1 = fullCodePath.substring(0, eidx); 14193 int sidx = subStr1.lastIndexOf("/"); 14194 cid = subStr1.substring(sidx+1, eidx); 14195 setMountPath(subStr1); 14196 } 14197 14198 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 14199 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 14200 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 14201 instructionSets, null, null, null, 0, null /*certificates*/); 14202 this.cid = cid; 14203 setMountPath(PackageHelper.getSdDir(cid)); 14204 } 14205 14206 void createCopyFile() { 14207 cid = mInstallerService.allocateExternalStageCidLegacy(); 14208 } 14209 14210 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14211 if (origin.staged && origin.cid != null) { 14212 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 14213 cid = origin.cid; 14214 setMountPath(PackageHelper.getSdDir(cid)); 14215 return PackageManager.INSTALL_SUCCEEDED; 14216 } 14217 14218 if (temp) { 14219 createCopyFile(); 14220 } else { 14221 /* 14222 * Pre-emptively destroy the container since it's destroyed if 14223 * copying fails due to it existing anyway. 14224 */ 14225 PackageHelper.destroySdDir(cid); 14226 } 14227 14228 final String newMountPath = imcs.copyPackageToContainer( 14229 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 14230 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 14231 14232 if (newMountPath != null) { 14233 setMountPath(newMountPath); 14234 return PackageManager.INSTALL_SUCCEEDED; 14235 } else { 14236 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14237 } 14238 } 14239 14240 @Override 14241 String getCodePath() { 14242 return packagePath; 14243 } 14244 14245 @Override 14246 String getResourcePath() { 14247 return resourcePath; 14248 } 14249 14250 int doPreInstall(int status) { 14251 if (status != PackageManager.INSTALL_SUCCEEDED) { 14252 // Destroy container 14253 PackageHelper.destroySdDir(cid); 14254 } else { 14255 boolean mounted = PackageHelper.isContainerMounted(cid); 14256 if (!mounted) { 14257 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 14258 Process.SYSTEM_UID); 14259 if (newMountPath != null) { 14260 setMountPath(newMountPath); 14261 } else { 14262 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14263 } 14264 } 14265 } 14266 return status; 14267 } 14268 14269 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14270 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 14271 String newMountPath = null; 14272 if (PackageHelper.isContainerMounted(cid)) { 14273 // Unmount the container 14274 if (!PackageHelper.unMountSdDir(cid)) { 14275 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 14276 return false; 14277 } 14278 } 14279 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 14280 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 14281 " which might be stale. Will try to clean up."); 14282 // Clean up the stale container and proceed to recreate. 14283 if (!PackageHelper.destroySdDir(newCacheId)) { 14284 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 14285 return false; 14286 } 14287 // Successfully cleaned up stale container. Try to rename again. 14288 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 14289 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 14290 + " inspite of cleaning it up."); 14291 return false; 14292 } 14293 } 14294 if (!PackageHelper.isContainerMounted(newCacheId)) { 14295 Slog.w(TAG, "Mounting container " + newCacheId); 14296 newMountPath = PackageHelper.mountSdDir(newCacheId, 14297 getEncryptKey(), Process.SYSTEM_UID); 14298 } else { 14299 newMountPath = PackageHelper.getSdDir(newCacheId); 14300 } 14301 if (newMountPath == null) { 14302 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 14303 return false; 14304 } 14305 Log.i(TAG, "Succesfully renamed " + cid + 14306 " to " + newCacheId + 14307 " at new path: " + newMountPath); 14308 cid = newCacheId; 14309 14310 final File beforeCodeFile = new File(packagePath); 14311 setMountPath(newMountPath); 14312 final File afterCodeFile = new File(packagePath); 14313 14314 // Reflect the rename in scanned details 14315 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14316 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14317 afterCodeFile, pkg.baseCodePath)); 14318 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14319 afterCodeFile, pkg.splitCodePaths)); 14320 14321 // Reflect the rename in app info 14322 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14323 pkg.setApplicationInfoCodePath(pkg.codePath); 14324 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14325 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14326 pkg.setApplicationInfoResourcePath(pkg.codePath); 14327 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14328 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14329 14330 return true; 14331 } 14332 14333 private void setMountPath(String mountPath) { 14334 final File mountFile = new File(mountPath); 14335 14336 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 14337 if (monolithicFile.exists()) { 14338 packagePath = monolithicFile.getAbsolutePath(); 14339 if (isFwdLocked()) { 14340 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 14341 } else { 14342 resourcePath = packagePath; 14343 } 14344 } else { 14345 packagePath = mountFile.getAbsolutePath(); 14346 resourcePath = packagePath; 14347 } 14348 } 14349 14350 int doPostInstall(int status, int uid) { 14351 if (status != PackageManager.INSTALL_SUCCEEDED) { 14352 cleanUp(); 14353 } else { 14354 final int groupOwner; 14355 final String protectedFile; 14356 if (isFwdLocked()) { 14357 groupOwner = UserHandle.getSharedAppGid(uid); 14358 protectedFile = RES_FILE_NAME; 14359 } else { 14360 groupOwner = -1; 14361 protectedFile = null; 14362 } 14363 14364 if (uid < Process.FIRST_APPLICATION_UID 14365 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 14366 Slog.e(TAG, "Failed to finalize " + cid); 14367 PackageHelper.destroySdDir(cid); 14368 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14369 } 14370 14371 boolean mounted = PackageHelper.isContainerMounted(cid); 14372 if (!mounted) { 14373 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 14374 } 14375 } 14376 return status; 14377 } 14378 14379 private void cleanUp() { 14380 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 14381 14382 // Destroy secure container 14383 PackageHelper.destroySdDir(cid); 14384 } 14385 14386 private List<String> getAllCodePaths() { 14387 final File codeFile = new File(getCodePath()); 14388 if (codeFile != null && codeFile.exists()) { 14389 try { 14390 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14391 return pkg.getAllCodePaths(); 14392 } catch (PackageParserException e) { 14393 // Ignored; we tried our best 14394 } 14395 } 14396 return Collections.EMPTY_LIST; 14397 } 14398 14399 void cleanUpResourcesLI() { 14400 // Enumerate all code paths before deleting 14401 cleanUpResourcesLI(getAllCodePaths()); 14402 } 14403 14404 private void cleanUpResourcesLI(List<String> allCodePaths) { 14405 cleanUp(); 14406 removeDexFiles(allCodePaths, instructionSets); 14407 } 14408 14409 String getPackageName() { 14410 return getAsecPackageName(cid); 14411 } 14412 14413 boolean doPostDeleteLI(boolean delete) { 14414 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 14415 final List<String> allCodePaths = getAllCodePaths(); 14416 boolean mounted = PackageHelper.isContainerMounted(cid); 14417 if (mounted) { 14418 // Unmount first 14419 if (PackageHelper.unMountSdDir(cid)) { 14420 mounted = false; 14421 } 14422 } 14423 if (!mounted && delete) { 14424 cleanUpResourcesLI(allCodePaths); 14425 } 14426 return !mounted; 14427 } 14428 14429 @Override 14430 int doPreCopy() { 14431 if (isFwdLocked()) { 14432 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 14433 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 14434 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14435 } 14436 } 14437 14438 return PackageManager.INSTALL_SUCCEEDED; 14439 } 14440 14441 @Override 14442 int doPostCopy(int uid) { 14443 if (isFwdLocked()) { 14444 if (uid < Process.FIRST_APPLICATION_UID 14445 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 14446 RES_FILE_NAME)) { 14447 Slog.e(TAG, "Failed to finalize " + cid); 14448 PackageHelper.destroySdDir(cid); 14449 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14450 } 14451 } 14452 14453 return PackageManager.INSTALL_SUCCEEDED; 14454 } 14455 } 14456 14457 /** 14458 * Logic to handle movement of existing installed applications. 14459 */ 14460 class MoveInstallArgs extends InstallArgs { 14461 private File codeFile; 14462 private File resourceFile; 14463 14464 /** New install */ 14465 MoveInstallArgs(InstallParams params) { 14466 super(params.origin, params.move, params.observer, params.installFlags, 14467 params.installerPackageName, params.volumeUuid, 14468 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14469 params.grantedRuntimePermissions, 14470 params.traceMethod, params.traceCookie, params.certificates); 14471 } 14472 14473 int copyApk(IMediaContainerService imcs, boolean temp) { 14474 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 14475 + move.fromUuid + " to " + move.toUuid); 14476 synchronized (mInstaller) { 14477 try { 14478 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 14479 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 14480 } catch (InstallerException e) { 14481 Slog.w(TAG, "Failed to move app", e); 14482 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14483 } 14484 } 14485 14486 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 14487 resourceFile = codeFile; 14488 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 14489 14490 return PackageManager.INSTALL_SUCCEEDED; 14491 } 14492 14493 int doPreInstall(int status) { 14494 if (status != PackageManager.INSTALL_SUCCEEDED) { 14495 cleanUp(move.toUuid); 14496 } 14497 return status; 14498 } 14499 14500 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14501 if (status != PackageManager.INSTALL_SUCCEEDED) { 14502 cleanUp(move.toUuid); 14503 return false; 14504 } 14505 14506 // Reflect the move in app info 14507 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14508 pkg.setApplicationInfoCodePath(pkg.codePath); 14509 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14510 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14511 pkg.setApplicationInfoResourcePath(pkg.codePath); 14512 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14513 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14514 14515 return true; 14516 } 14517 14518 int doPostInstall(int status, int uid) { 14519 if (status == PackageManager.INSTALL_SUCCEEDED) { 14520 cleanUp(move.fromUuid); 14521 } else { 14522 cleanUp(move.toUuid); 14523 } 14524 return status; 14525 } 14526 14527 @Override 14528 String getCodePath() { 14529 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14530 } 14531 14532 @Override 14533 String getResourcePath() { 14534 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14535 } 14536 14537 private boolean cleanUp(String volumeUuid) { 14538 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14539 move.dataAppName); 14540 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14541 final int[] userIds = sUserManager.getUserIds(); 14542 synchronized (mInstallLock) { 14543 // Clean up both app data and code 14544 // All package moves are frozen until finished 14545 for (int userId : userIds) { 14546 try { 14547 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14548 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14549 } catch (InstallerException e) { 14550 Slog.w(TAG, String.valueOf(e)); 14551 } 14552 } 14553 removeCodePathLI(codeFile); 14554 } 14555 return true; 14556 } 14557 14558 void cleanUpResourcesLI() { 14559 throw new UnsupportedOperationException(); 14560 } 14561 14562 boolean doPostDeleteLI(boolean delete) { 14563 throw new UnsupportedOperationException(); 14564 } 14565 } 14566 14567 static String getAsecPackageName(String packageCid) { 14568 int idx = packageCid.lastIndexOf("-"); 14569 if (idx == -1) { 14570 return packageCid; 14571 } 14572 return packageCid.substring(0, idx); 14573 } 14574 14575 // Utility method used to create code paths based on package name and available index. 14576 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14577 String idxStr = ""; 14578 int idx = 1; 14579 // Fall back to default value of idx=1 if prefix is not 14580 // part of oldCodePath 14581 if (oldCodePath != null) { 14582 String subStr = oldCodePath; 14583 // Drop the suffix right away 14584 if (suffix != null && subStr.endsWith(suffix)) { 14585 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14586 } 14587 // If oldCodePath already contains prefix find out the 14588 // ending index to either increment or decrement. 14589 int sidx = subStr.lastIndexOf(prefix); 14590 if (sidx != -1) { 14591 subStr = subStr.substring(sidx + prefix.length()); 14592 if (subStr != null) { 14593 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14594 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14595 } 14596 try { 14597 idx = Integer.parseInt(subStr); 14598 if (idx <= 1) { 14599 idx++; 14600 } else { 14601 idx--; 14602 } 14603 } catch(NumberFormatException e) { 14604 } 14605 } 14606 } 14607 } 14608 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14609 return prefix + idxStr; 14610 } 14611 14612 private File getNextCodePath(File targetDir, String packageName) { 14613 File result; 14614 SecureRandom random = new SecureRandom(); 14615 byte[] bytes = new byte[16]; 14616 do { 14617 random.nextBytes(bytes); 14618 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 14619 result = new File(targetDir, packageName + "-" + suffix); 14620 } while (result.exists()); 14621 return result; 14622 } 14623 14624 // Utility method that returns the relative package path with respect 14625 // to the installation directory. Like say for /data/data/com.test-1.apk 14626 // string com.test-1 is returned. 14627 static String deriveCodePathName(String codePath) { 14628 if (codePath == null) { 14629 return null; 14630 } 14631 final File codeFile = new File(codePath); 14632 final String name = codeFile.getName(); 14633 if (codeFile.isDirectory()) { 14634 return name; 14635 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14636 final int lastDot = name.lastIndexOf('.'); 14637 return name.substring(0, lastDot); 14638 } else { 14639 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14640 return null; 14641 } 14642 } 14643 14644 static class PackageInstalledInfo { 14645 String name; 14646 int uid; 14647 // The set of users that originally had this package installed. 14648 int[] origUsers; 14649 // The set of users that now have this package installed. 14650 int[] newUsers; 14651 PackageParser.Package pkg; 14652 int returnCode; 14653 String returnMsg; 14654 PackageRemovedInfo removedInfo; 14655 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14656 14657 public void setError(int code, String msg) { 14658 setReturnCode(code); 14659 setReturnMessage(msg); 14660 Slog.w(TAG, msg); 14661 } 14662 14663 public void setError(String msg, PackageParserException e) { 14664 setReturnCode(e.error); 14665 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14666 Slog.w(TAG, msg, e); 14667 } 14668 14669 public void setError(String msg, PackageManagerException e) { 14670 returnCode = e.error; 14671 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14672 Slog.w(TAG, msg, e); 14673 } 14674 14675 public void setReturnCode(int returnCode) { 14676 this.returnCode = returnCode; 14677 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14678 for (int i = 0; i < childCount; i++) { 14679 addedChildPackages.valueAt(i).returnCode = returnCode; 14680 } 14681 } 14682 14683 private void setReturnMessage(String returnMsg) { 14684 this.returnMsg = returnMsg; 14685 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14686 for (int i = 0; i < childCount; i++) { 14687 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14688 } 14689 } 14690 14691 // In some error cases we want to convey more info back to the observer 14692 String origPackage; 14693 String origPermission; 14694 } 14695 14696 /* 14697 * Install a non-existing package. 14698 */ 14699 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14700 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14701 PackageInstalledInfo res) { 14702 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14703 14704 // Remember this for later, in case we need to rollback this install 14705 String pkgName = pkg.packageName; 14706 14707 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14708 14709 synchronized(mPackages) { 14710 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 14711 if (renamedPackage != null) { 14712 // A package with the same name is already installed, though 14713 // it has been renamed to an older name. The package we 14714 // are trying to install should be installed as an update to 14715 // the existing one, but that has not been requested, so bail. 14716 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14717 + " without first uninstalling package running as " 14718 + renamedPackage); 14719 return; 14720 } 14721 if (mPackages.containsKey(pkgName)) { 14722 // Don't allow installation over an existing package with the same name. 14723 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14724 + " without first uninstalling."); 14725 return; 14726 } 14727 } 14728 14729 try { 14730 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14731 System.currentTimeMillis(), user); 14732 14733 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14734 14735 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14736 prepareAppDataAfterInstallLIF(newPackage); 14737 14738 } else { 14739 // Remove package from internal structures, but keep around any 14740 // data that might have already existed 14741 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14742 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14743 } 14744 } catch (PackageManagerException e) { 14745 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14746 } 14747 14748 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14749 } 14750 14751 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14752 // Can't rotate keys during boot or if sharedUser. 14753 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14754 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14755 return false; 14756 } 14757 // app is using upgradeKeySets; make sure all are valid 14758 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14759 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14760 for (int i = 0; i < upgradeKeySets.length; i++) { 14761 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14762 Slog.wtf(TAG, "Package " 14763 + (oldPs.name != null ? oldPs.name : "<null>") 14764 + " contains upgrade-key-set reference to unknown key-set: " 14765 + upgradeKeySets[i] 14766 + " reverting to signatures check."); 14767 return false; 14768 } 14769 } 14770 return true; 14771 } 14772 14773 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14774 // Upgrade keysets are being used. Determine if new package has a superset of the 14775 // required keys. 14776 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14777 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14778 for (int i = 0; i < upgradeKeySets.length; i++) { 14779 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14780 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14781 return true; 14782 } 14783 } 14784 return false; 14785 } 14786 14787 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14788 try (DigestInputStream digestStream = 14789 new DigestInputStream(new FileInputStream(file), digest)) { 14790 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14791 } 14792 } 14793 14794 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14795 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14796 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14797 14798 final PackageParser.Package oldPackage; 14799 final String pkgName = pkg.packageName; 14800 final int[] allUsers; 14801 final int[] installedUsers; 14802 14803 synchronized(mPackages) { 14804 oldPackage = mPackages.get(pkgName); 14805 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14806 14807 // don't allow upgrade to target a release SDK from a pre-release SDK 14808 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14809 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14810 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14811 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14812 if (oldTargetsPreRelease 14813 && !newTargetsPreRelease 14814 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14815 Slog.w(TAG, "Can't install package targeting released sdk"); 14816 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14817 return; 14818 } 14819 14820 // don't allow an upgrade from full to ephemeral 14821 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14822 if (isEphemeral && !oldIsEphemeral) { 14823 // can't downgrade from full to ephemeral 14824 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14825 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14826 return; 14827 } 14828 14829 // verify signatures are valid 14830 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14831 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14832 if (!checkUpgradeKeySetLP(ps, pkg)) { 14833 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14834 "New package not signed by keys specified by upgrade-keysets: " 14835 + pkgName); 14836 return; 14837 } 14838 } else { 14839 // default to original signature matching 14840 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14841 != PackageManager.SIGNATURE_MATCH) { 14842 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14843 "New package has a different signature: " + pkgName); 14844 return; 14845 } 14846 } 14847 14848 // don't allow a system upgrade unless the upgrade hash matches 14849 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14850 byte[] digestBytes = null; 14851 try { 14852 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14853 updateDigest(digest, new File(pkg.baseCodePath)); 14854 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14855 for (String path : pkg.splitCodePaths) { 14856 updateDigest(digest, new File(path)); 14857 } 14858 } 14859 digestBytes = digest.digest(); 14860 } catch (NoSuchAlgorithmException | IOException e) { 14861 res.setError(INSTALL_FAILED_INVALID_APK, 14862 "Could not compute hash: " + pkgName); 14863 return; 14864 } 14865 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14866 res.setError(INSTALL_FAILED_INVALID_APK, 14867 "New package fails restrict-update check: " + pkgName); 14868 return; 14869 } 14870 // retain upgrade restriction 14871 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14872 } 14873 14874 // Check for shared user id changes 14875 String invalidPackageName = 14876 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14877 if (invalidPackageName != null) { 14878 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14879 "Package " + invalidPackageName + " tried to change user " 14880 + oldPackage.mSharedUserId); 14881 return; 14882 } 14883 14884 // In case of rollback, remember per-user/profile install state 14885 allUsers = sUserManager.getUserIds(); 14886 installedUsers = ps.queryInstalledUsers(allUsers, true); 14887 } 14888 14889 // Update what is removed 14890 res.removedInfo = new PackageRemovedInfo(); 14891 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14892 res.removedInfo.removedPackage = oldPackage.packageName; 14893 res.removedInfo.isUpdate = true; 14894 res.removedInfo.origUsers = installedUsers; 14895 final int childCount = (oldPackage.childPackages != null) 14896 ? oldPackage.childPackages.size() : 0; 14897 for (int i = 0; i < childCount; i++) { 14898 boolean childPackageUpdated = false; 14899 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14900 if (res.addedChildPackages != null) { 14901 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14902 if (childRes != null) { 14903 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14904 childRes.removedInfo.removedPackage = childPkg.packageName; 14905 childRes.removedInfo.isUpdate = true; 14906 childPackageUpdated = true; 14907 } 14908 } 14909 if (!childPackageUpdated) { 14910 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14911 childRemovedRes.removedPackage = childPkg.packageName; 14912 childRemovedRes.isUpdate = false; 14913 childRemovedRes.dataRemoved = true; 14914 synchronized (mPackages) { 14915 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 14916 if (childPs != null) { 14917 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14918 } 14919 } 14920 if (res.removedInfo.removedChildPackages == null) { 14921 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14922 } 14923 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14924 } 14925 } 14926 14927 boolean sysPkg = (isSystemApp(oldPackage)); 14928 if (sysPkg) { 14929 // Set the system/privileged flags as needed 14930 final boolean privileged = 14931 (oldPackage.applicationInfo.privateFlags 14932 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14933 final int systemPolicyFlags = policyFlags 14934 | PackageParser.PARSE_IS_SYSTEM 14935 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14936 14937 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14938 user, allUsers, installerPackageName, res); 14939 } else { 14940 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14941 user, allUsers, installerPackageName, res); 14942 } 14943 } 14944 14945 public List<String> getPreviousCodePaths(String packageName) { 14946 final PackageSetting ps = mSettings.mPackages.get(packageName); 14947 final List<String> result = new ArrayList<String>(); 14948 if (ps != null && ps.oldCodePaths != null) { 14949 result.addAll(ps.oldCodePaths); 14950 } 14951 return result; 14952 } 14953 14954 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14955 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14956 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14957 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14958 + deletedPackage); 14959 14960 String pkgName = deletedPackage.packageName; 14961 boolean deletedPkg = true; 14962 boolean addedPkg = false; 14963 boolean updatedSettings = false; 14964 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14965 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14966 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14967 14968 final long origUpdateTime = (pkg.mExtras != null) 14969 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14970 14971 // First delete the existing package while retaining the data directory 14972 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14973 res.removedInfo, true, pkg)) { 14974 // If the existing package wasn't successfully deleted 14975 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14976 deletedPkg = false; 14977 } else { 14978 // Successfully deleted the old package; proceed with replace. 14979 14980 // If deleted package lived in a container, give users a chance to 14981 // relinquish resources before killing. 14982 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14983 if (DEBUG_INSTALL) { 14984 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14985 } 14986 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14987 final ArrayList<String> pkgList = new ArrayList<String>(1); 14988 pkgList.add(deletedPackage.applicationInfo.packageName); 14989 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14990 } 14991 14992 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14993 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14994 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14995 14996 try { 14997 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14998 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14999 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 15000 15001 // Update the in-memory copy of the previous code paths. 15002 PackageSetting ps = mSettings.mPackages.get(pkgName); 15003 if (!killApp) { 15004 if (ps.oldCodePaths == null) { 15005 ps.oldCodePaths = new ArraySet<>(); 15006 } 15007 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 15008 if (deletedPackage.splitCodePaths != null) { 15009 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 15010 } 15011 } else { 15012 ps.oldCodePaths = null; 15013 } 15014 if (ps.childPackageNames != null) { 15015 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 15016 final String childPkgName = ps.childPackageNames.get(i); 15017 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 15018 childPs.oldCodePaths = ps.oldCodePaths; 15019 } 15020 } 15021 prepareAppDataAfterInstallLIF(newPackage); 15022 addedPkg = true; 15023 } catch (PackageManagerException e) { 15024 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15025 } 15026 } 15027 15028 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15029 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 15030 15031 // Revert all internal state mutations and added folders for the failed install 15032 if (addedPkg) { 15033 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15034 res.removedInfo, true, null); 15035 } 15036 15037 // Restore the old package 15038 if (deletedPkg) { 15039 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 15040 File restoreFile = new File(deletedPackage.codePath); 15041 // Parse old package 15042 boolean oldExternal = isExternal(deletedPackage); 15043 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 15044 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 15045 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 15046 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 15047 try { 15048 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 15049 null); 15050 } catch (PackageManagerException e) { 15051 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 15052 + e.getMessage()); 15053 return; 15054 } 15055 15056 synchronized (mPackages) { 15057 // Ensure the installer package name up to date 15058 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15059 15060 // Update permissions for restored package 15061 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 15062 15063 mSettings.writeLPr(); 15064 } 15065 15066 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 15067 } 15068 } else { 15069 synchronized (mPackages) { 15070 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 15071 if (ps != null) { 15072 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15073 if (res.removedInfo.removedChildPackages != null) { 15074 final int childCount = res.removedInfo.removedChildPackages.size(); 15075 // Iterate in reverse as we may modify the collection 15076 for (int i = childCount - 1; i >= 0; i--) { 15077 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 15078 if (res.addedChildPackages.containsKey(childPackageName)) { 15079 res.removedInfo.removedChildPackages.removeAt(i); 15080 } else { 15081 PackageRemovedInfo childInfo = res.removedInfo 15082 .removedChildPackages.valueAt(i); 15083 childInfo.removedForAllUsers = mPackages.get( 15084 childInfo.removedPackage) == null; 15085 } 15086 } 15087 } 15088 } 15089 } 15090 } 15091 } 15092 15093 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 15094 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15095 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 15096 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 15097 + ", old=" + deletedPackage); 15098 15099 final boolean disabledSystem; 15100 15101 // Remove existing system package 15102 removePackageLI(deletedPackage, true); 15103 15104 synchronized (mPackages) { 15105 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 15106 } 15107 if (!disabledSystem) { 15108 // We didn't need to disable the .apk as a current system package, 15109 // which means we are replacing another update that is already 15110 // installed. We need to make sure to delete the older one's .apk. 15111 res.removedInfo.args = createInstallArgsForExisting(0, 15112 deletedPackage.applicationInfo.getCodePath(), 15113 deletedPackage.applicationInfo.getResourcePath(), 15114 getAppDexInstructionSets(deletedPackage.applicationInfo)); 15115 } else { 15116 res.removedInfo.args = null; 15117 } 15118 15119 // Successfully disabled the old package. Now proceed with re-installation 15120 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15121 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15122 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15123 15124 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15125 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 15126 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 15127 15128 PackageParser.Package newPackage = null; 15129 try { 15130 // Add the package to the internal data structures 15131 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 15132 15133 // Set the update and install times 15134 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 15135 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 15136 System.currentTimeMillis()); 15137 15138 // Update the package dynamic state if succeeded 15139 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15140 // Now that the install succeeded make sure we remove data 15141 // directories for any child package the update removed. 15142 final int deletedChildCount = (deletedPackage.childPackages != null) 15143 ? deletedPackage.childPackages.size() : 0; 15144 final int newChildCount = (newPackage.childPackages != null) 15145 ? newPackage.childPackages.size() : 0; 15146 for (int i = 0; i < deletedChildCount; i++) { 15147 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 15148 boolean childPackageDeleted = true; 15149 for (int j = 0; j < newChildCount; j++) { 15150 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 15151 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 15152 childPackageDeleted = false; 15153 break; 15154 } 15155 } 15156 if (childPackageDeleted) { 15157 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 15158 deletedChildPkg.packageName); 15159 if (ps != null && res.removedInfo.removedChildPackages != null) { 15160 PackageRemovedInfo removedChildRes = res.removedInfo 15161 .removedChildPackages.get(deletedChildPkg.packageName); 15162 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 15163 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 15164 } 15165 } 15166 } 15167 15168 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 15169 prepareAppDataAfterInstallLIF(newPackage); 15170 } 15171 } catch (PackageManagerException e) { 15172 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 15173 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15174 } 15175 15176 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15177 // Re installation failed. Restore old information 15178 // Remove new pkg information 15179 if (newPackage != null) { 15180 removeInstalledPackageLI(newPackage, true); 15181 } 15182 // Add back the old system package 15183 try { 15184 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 15185 } catch (PackageManagerException e) { 15186 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 15187 } 15188 15189 synchronized (mPackages) { 15190 if (disabledSystem) { 15191 enableSystemPackageLPw(deletedPackage); 15192 } 15193 15194 // Ensure the installer package name up to date 15195 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15196 15197 // Update permissions for restored package 15198 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 15199 15200 mSettings.writeLPr(); 15201 } 15202 15203 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 15204 + " after failed upgrade"); 15205 } 15206 } 15207 15208 /** 15209 * Checks whether the parent or any of the child packages have a change shared 15210 * user. For a package to be a valid update the shred users of the parent and 15211 * the children should match. We may later support changing child shared users. 15212 * @param oldPkg The updated package. 15213 * @param newPkg The update package. 15214 * @return The shared user that change between the versions. 15215 */ 15216 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 15217 PackageParser.Package newPkg) { 15218 // Check parent shared user 15219 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 15220 return newPkg.packageName; 15221 } 15222 // Check child shared users 15223 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15224 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 15225 for (int i = 0; i < newChildCount; i++) { 15226 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 15227 // If this child was present, did it have the same shared user? 15228 for (int j = 0; j < oldChildCount; j++) { 15229 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 15230 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 15231 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 15232 return newChildPkg.packageName; 15233 } 15234 } 15235 } 15236 return null; 15237 } 15238 15239 private void removeNativeBinariesLI(PackageSetting ps) { 15240 // Remove the lib path for the parent package 15241 if (ps != null) { 15242 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 15243 // Remove the lib path for the child packages 15244 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15245 for (int i = 0; i < childCount; i++) { 15246 PackageSetting childPs = null; 15247 synchronized (mPackages) { 15248 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 15249 } 15250 if (childPs != null) { 15251 NativeLibraryHelper.removeNativeBinariesLI(childPs 15252 .legacyNativeLibraryPathString); 15253 } 15254 } 15255 } 15256 } 15257 15258 private void enableSystemPackageLPw(PackageParser.Package pkg) { 15259 // Enable the parent package 15260 mSettings.enableSystemPackageLPw(pkg.packageName); 15261 // Enable the child packages 15262 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15263 for (int i = 0; i < childCount; i++) { 15264 PackageParser.Package childPkg = pkg.childPackages.get(i); 15265 mSettings.enableSystemPackageLPw(childPkg.packageName); 15266 } 15267 } 15268 15269 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 15270 PackageParser.Package newPkg) { 15271 // Disable the parent package (parent always replaced) 15272 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 15273 // Disable the child packages 15274 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15275 for (int i = 0; i < childCount; i++) { 15276 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 15277 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 15278 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 15279 } 15280 return disabled; 15281 } 15282 15283 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 15284 String installerPackageName) { 15285 // Enable the parent package 15286 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 15287 // Enable the child packages 15288 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15289 for (int i = 0; i < childCount; i++) { 15290 PackageParser.Package childPkg = pkg.childPackages.get(i); 15291 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 15292 } 15293 } 15294 15295 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 15296 // Collect all used permissions in the UID 15297 ArraySet<String> usedPermissions = new ArraySet<>(); 15298 final int packageCount = su.packages.size(); 15299 for (int i = 0; i < packageCount; i++) { 15300 PackageSetting ps = su.packages.valueAt(i); 15301 if (ps.pkg == null) { 15302 continue; 15303 } 15304 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 15305 for (int j = 0; j < requestedPermCount; j++) { 15306 String permission = ps.pkg.requestedPermissions.get(j); 15307 BasePermission bp = mSettings.mPermissions.get(permission); 15308 if (bp != null) { 15309 usedPermissions.add(permission); 15310 } 15311 } 15312 } 15313 15314 PermissionsState permissionsState = su.getPermissionsState(); 15315 // Prune install permissions 15316 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 15317 final int installPermCount = installPermStates.size(); 15318 for (int i = installPermCount - 1; i >= 0; i--) { 15319 PermissionState permissionState = installPermStates.get(i); 15320 if (!usedPermissions.contains(permissionState.getName())) { 15321 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15322 if (bp != null) { 15323 permissionsState.revokeInstallPermission(bp); 15324 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 15325 PackageManager.MASK_PERMISSION_FLAGS, 0); 15326 } 15327 } 15328 } 15329 15330 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 15331 15332 // Prune runtime permissions 15333 for (int userId : allUserIds) { 15334 List<PermissionState> runtimePermStates = permissionsState 15335 .getRuntimePermissionStates(userId); 15336 final int runtimePermCount = runtimePermStates.size(); 15337 for (int i = runtimePermCount - 1; i >= 0; i--) { 15338 PermissionState permissionState = runtimePermStates.get(i); 15339 if (!usedPermissions.contains(permissionState.getName())) { 15340 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15341 if (bp != null) { 15342 permissionsState.revokeRuntimePermission(bp, userId); 15343 permissionsState.updatePermissionFlags(bp, userId, 15344 PackageManager.MASK_PERMISSION_FLAGS, 0); 15345 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 15346 runtimePermissionChangedUserIds, userId); 15347 } 15348 } 15349 } 15350 } 15351 15352 return runtimePermissionChangedUserIds; 15353 } 15354 15355 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 15356 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 15357 // Update the parent package setting 15358 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 15359 res, user); 15360 // Update the child packages setting 15361 final int childCount = (newPackage.childPackages != null) 15362 ? newPackage.childPackages.size() : 0; 15363 for (int i = 0; i < childCount; i++) { 15364 PackageParser.Package childPackage = newPackage.childPackages.get(i); 15365 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 15366 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 15367 childRes.origUsers, childRes, user); 15368 } 15369 } 15370 15371 private void updateSettingsInternalLI(PackageParser.Package newPackage, 15372 String installerPackageName, int[] allUsers, int[] installedForUsers, 15373 PackageInstalledInfo res, UserHandle user) { 15374 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 15375 15376 String pkgName = newPackage.packageName; 15377 synchronized (mPackages) { 15378 //write settings. the installStatus will be incomplete at this stage. 15379 //note that the new package setting would have already been 15380 //added to mPackages. It hasn't been persisted yet. 15381 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 15382 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15383 mSettings.writeLPr(); 15384 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15385 } 15386 15387 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 15388 synchronized (mPackages) { 15389 updatePermissionsLPw(newPackage.packageName, newPackage, 15390 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 15391 ? UPDATE_PERMISSIONS_ALL : 0)); 15392 // For system-bundled packages, we assume that installing an upgraded version 15393 // of the package implies that the user actually wants to run that new code, 15394 // so we enable the package. 15395 PackageSetting ps = mSettings.mPackages.get(pkgName); 15396 final int userId = user.getIdentifier(); 15397 if (ps != null) { 15398 if (isSystemApp(newPackage)) { 15399 if (DEBUG_INSTALL) { 15400 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 15401 } 15402 // Enable system package for requested users 15403 if (res.origUsers != null) { 15404 for (int origUserId : res.origUsers) { 15405 if (userId == UserHandle.USER_ALL || userId == origUserId) { 15406 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 15407 origUserId, installerPackageName); 15408 } 15409 } 15410 } 15411 // Also convey the prior install/uninstall state 15412 if (allUsers != null && installedForUsers != null) { 15413 for (int currentUserId : allUsers) { 15414 final boolean installed = ArrayUtils.contains( 15415 installedForUsers, currentUserId); 15416 if (DEBUG_INSTALL) { 15417 Slog.d(TAG, " user " + currentUserId + " => " + installed); 15418 } 15419 ps.setInstalled(installed, currentUserId); 15420 } 15421 // these install state changes will be persisted in the 15422 // upcoming call to mSettings.writeLPr(). 15423 } 15424 } 15425 // It's implied that when a user requests installation, they want the app to be 15426 // installed and enabled. 15427 if (userId != UserHandle.USER_ALL) { 15428 ps.setInstalled(true, userId); 15429 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 15430 } 15431 } 15432 res.name = pkgName; 15433 res.uid = newPackage.applicationInfo.uid; 15434 res.pkg = newPackage; 15435 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 15436 mSettings.setInstallerPackageName(pkgName, installerPackageName); 15437 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15438 //to update install status 15439 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15440 mSettings.writeLPr(); 15441 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15442 } 15443 15444 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15445 } 15446 15447 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 15448 try { 15449 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 15450 installPackageLI(args, res); 15451 } finally { 15452 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15453 } 15454 } 15455 15456 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 15457 final int installFlags = args.installFlags; 15458 final String installerPackageName = args.installerPackageName; 15459 final String volumeUuid = args.volumeUuid; 15460 final File tmpPackageFile = new File(args.getCodePath()); 15461 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 15462 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 15463 || (args.volumeUuid != null)); 15464 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 15465 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 15466 boolean replace = false; 15467 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 15468 if (args.move != null) { 15469 // moving a complete application; perform an initial scan on the new install location 15470 scanFlags |= SCAN_INITIAL; 15471 } 15472 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 15473 scanFlags |= SCAN_DONT_KILL_APP; 15474 } 15475 15476 // Result object to be returned 15477 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15478 15479 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 15480 15481 // Sanity check 15482 if (ephemeral && (forwardLocked || onExternal)) { 15483 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 15484 + " external=" + onExternal); 15485 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15486 return; 15487 } 15488 15489 // Retrieve PackageSettings and parse package 15490 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 15491 | PackageParser.PARSE_ENFORCE_CODE 15492 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 15493 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 15494 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 15495 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 15496 PackageParser pp = new PackageParser(); 15497 pp.setSeparateProcesses(mSeparateProcesses); 15498 pp.setDisplayMetrics(mMetrics); 15499 15500 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 15501 final PackageParser.Package pkg; 15502 try { 15503 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 15504 } catch (PackageParserException e) { 15505 res.setError("Failed parse during installPackageLI", e); 15506 return; 15507 } finally { 15508 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15509 } 15510 15511 // Ephemeral apps must have target SDK >= O. 15512 // TODO: Update conditional and error message when O gets locked down 15513 if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 15514 res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID, 15515 "Ephemeral apps must have target SDK version of at least O"); 15516 return; 15517 } 15518 15519 // If we are installing a clustered package add results for the children 15520 if (pkg.childPackages != null) { 15521 synchronized (mPackages) { 15522 final int childCount = pkg.childPackages.size(); 15523 for (int i = 0; i < childCount; i++) { 15524 PackageParser.Package childPkg = pkg.childPackages.get(i); 15525 PackageInstalledInfo childRes = new PackageInstalledInfo(); 15526 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15527 childRes.pkg = childPkg; 15528 childRes.name = childPkg.packageName; 15529 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15530 if (childPs != null) { 15531 childRes.origUsers = childPs.queryInstalledUsers( 15532 sUserManager.getUserIds(), true); 15533 } 15534 if ((mPackages.containsKey(childPkg.packageName))) { 15535 childRes.removedInfo = new PackageRemovedInfo(); 15536 childRes.removedInfo.removedPackage = childPkg.packageName; 15537 } 15538 if (res.addedChildPackages == null) { 15539 res.addedChildPackages = new ArrayMap<>(); 15540 } 15541 res.addedChildPackages.put(childPkg.packageName, childRes); 15542 } 15543 } 15544 } 15545 15546 // If package doesn't declare API override, mark that we have an install 15547 // time CPU ABI override. 15548 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15549 pkg.cpuAbiOverride = args.abiOverride; 15550 } 15551 15552 String pkgName = res.name = pkg.packageName; 15553 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15554 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15555 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15556 return; 15557 } 15558 } 15559 15560 try { 15561 // either use what we've been given or parse directly from the APK 15562 if (args.certificates != null) { 15563 try { 15564 PackageParser.populateCertificates(pkg, args.certificates); 15565 } catch (PackageParserException e) { 15566 // there was something wrong with the certificates we were given; 15567 // try to pull them from the APK 15568 PackageParser.collectCertificates(pkg, parseFlags); 15569 } 15570 } else { 15571 PackageParser.collectCertificates(pkg, parseFlags); 15572 } 15573 } catch (PackageParserException e) { 15574 res.setError("Failed collect during installPackageLI", e); 15575 return; 15576 } 15577 15578 // Get rid of all references to package scan path via parser. 15579 pp = null; 15580 String oldCodePath = null; 15581 boolean systemApp = false; 15582 synchronized (mPackages) { 15583 // Check if installing already existing package 15584 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15585 String oldName = mSettings.getRenamedPackageLPr(pkgName); 15586 if (pkg.mOriginalPackages != null 15587 && pkg.mOriginalPackages.contains(oldName) 15588 && mPackages.containsKey(oldName)) { 15589 // This package is derived from an original package, 15590 // and this device has been updating from that original 15591 // name. We must continue using the original name, so 15592 // rename the new package here. 15593 pkg.setPackageName(oldName); 15594 pkgName = pkg.packageName; 15595 replace = true; 15596 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15597 + oldName + " pkgName=" + pkgName); 15598 } else if (mPackages.containsKey(pkgName)) { 15599 // This package, under its official name, already exists 15600 // on the device; we should replace it. 15601 replace = true; 15602 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15603 } 15604 15605 // Child packages are installed through the parent package 15606 if (pkg.parentPackage != null) { 15607 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15608 "Package " + pkg.packageName + " is child of package " 15609 + pkg.parentPackage.parentPackage + ". Child packages " 15610 + "can be updated only through the parent package."); 15611 return; 15612 } 15613 15614 if (replace) { 15615 // Prevent apps opting out from runtime permissions 15616 PackageParser.Package oldPackage = mPackages.get(pkgName); 15617 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15618 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15619 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15620 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15621 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15622 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15623 + " doesn't support runtime permissions but the old" 15624 + " target SDK " + oldTargetSdk + " does."); 15625 return; 15626 } 15627 15628 // Prevent installing of child packages 15629 if (oldPackage.parentPackage != null) { 15630 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15631 "Package " + pkg.packageName + " is child of package " 15632 + oldPackage.parentPackage + ". Child packages " 15633 + "can be updated only through the parent package."); 15634 return; 15635 } 15636 } 15637 } 15638 15639 PackageSetting ps = mSettings.mPackages.get(pkgName); 15640 if (ps != null) { 15641 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15642 15643 // Quick sanity check that we're signed correctly if updating; 15644 // we'll check this again later when scanning, but we want to 15645 // bail early here before tripping over redefined permissions. 15646 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15647 if (!checkUpgradeKeySetLP(ps, pkg)) { 15648 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15649 + pkg.packageName + " upgrade keys do not match the " 15650 + "previously installed version"); 15651 return; 15652 } 15653 } else { 15654 try { 15655 verifySignaturesLP(ps, pkg); 15656 } catch (PackageManagerException e) { 15657 res.setError(e.error, e.getMessage()); 15658 return; 15659 } 15660 } 15661 15662 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15663 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15664 systemApp = (ps.pkg.applicationInfo.flags & 15665 ApplicationInfo.FLAG_SYSTEM) != 0; 15666 } 15667 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15668 } 15669 15670 // Check whether the newly-scanned package wants to define an already-defined perm 15671 int N = pkg.permissions.size(); 15672 for (int i = N-1; i >= 0; i--) { 15673 PackageParser.Permission perm = pkg.permissions.get(i); 15674 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15675 if (bp != null) { 15676 // If the defining package is signed with our cert, it's okay. This 15677 // also includes the "updating the same package" case, of course. 15678 // "updating same package" could also involve key-rotation. 15679 final boolean sigsOk; 15680 if (bp.sourcePackage.equals(pkg.packageName) 15681 && (bp.packageSetting instanceof PackageSetting) 15682 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15683 scanFlags))) { 15684 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15685 } else { 15686 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15687 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15688 } 15689 if (!sigsOk) { 15690 // If the owning package is the system itself, we log but allow 15691 // install to proceed; we fail the install on all other permission 15692 // redefinitions. 15693 if (!bp.sourcePackage.equals("android")) { 15694 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15695 + pkg.packageName + " attempting to redeclare permission " 15696 + perm.info.name + " already owned by " + bp.sourcePackage); 15697 res.origPermission = perm.info.name; 15698 res.origPackage = bp.sourcePackage; 15699 return; 15700 } else { 15701 Slog.w(TAG, "Package " + pkg.packageName 15702 + " attempting to redeclare system permission " 15703 + perm.info.name + "; ignoring new declaration"); 15704 pkg.permissions.remove(i); 15705 } 15706 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 15707 // Prevent apps to change protection level to dangerous from any other 15708 // type as this would allow a privilege escalation where an app adds a 15709 // normal/signature permission in other app's group and later redefines 15710 // it as dangerous leading to the group auto-grant. 15711 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 15712 == PermissionInfo.PROTECTION_DANGEROUS) { 15713 if (bp != null && !bp.isRuntime()) { 15714 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 15715 + "non-runtime permission " + perm.info.name 15716 + " to runtime; keeping old protection level"); 15717 perm.info.protectionLevel = bp.protectionLevel; 15718 } 15719 } 15720 } 15721 } 15722 } 15723 } 15724 15725 if (systemApp) { 15726 if (onExternal) { 15727 // Abort update; system app can't be replaced with app on sdcard 15728 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15729 "Cannot install updates to system apps on sdcard"); 15730 return; 15731 } else if (ephemeral) { 15732 // Abort update; system app can't be replaced with an ephemeral app 15733 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15734 "Cannot update a system app with an ephemeral app"); 15735 return; 15736 } 15737 } 15738 15739 if (args.move != null) { 15740 // We did an in-place move, so dex is ready to roll 15741 scanFlags |= SCAN_NO_DEX; 15742 scanFlags |= SCAN_MOVE; 15743 15744 synchronized (mPackages) { 15745 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15746 if (ps == null) { 15747 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15748 "Missing settings for moved package " + pkgName); 15749 } 15750 15751 // We moved the entire application as-is, so bring over the 15752 // previously derived ABI information. 15753 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15754 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15755 } 15756 15757 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15758 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15759 scanFlags |= SCAN_NO_DEX; 15760 15761 try { 15762 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15763 args.abiOverride : pkg.cpuAbiOverride); 15764 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15765 true /*extractLibs*/, mAppLib32InstallDir); 15766 } catch (PackageManagerException pme) { 15767 Slog.e(TAG, "Error deriving application ABI", pme); 15768 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15769 return; 15770 } 15771 15772 // Shared libraries for the package need to be updated. 15773 synchronized (mPackages) { 15774 try { 15775 updateSharedLibrariesLPr(pkg, null); 15776 } catch (PackageManagerException e) { 15777 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15778 } 15779 } 15780 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15781 // Do not run PackageDexOptimizer through the local performDexOpt 15782 // method because `pkg` may not be in `mPackages` yet. 15783 // 15784 // Also, don't fail application installs if the dexopt step fails. 15785 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15786 null /* instructionSets */, false /* checkProfiles */, 15787 getCompilerFilterForReason(REASON_INSTALL), 15788 getOrCreateCompilerPackageStats(pkg)); 15789 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15790 15791 // Notify BackgroundDexOptService that the package has been changed. 15792 // If this is an update of a package which used to fail to compile, 15793 // BDOS will remove it from its blacklist. 15794 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15795 } 15796 15797 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15798 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15799 return; 15800 } 15801 15802 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15803 15804 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15805 "installPackageLI")) { 15806 if (replace) { 15807 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15808 installerPackageName, res); 15809 } else { 15810 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15811 args.user, installerPackageName, volumeUuid, res); 15812 } 15813 } 15814 synchronized (mPackages) { 15815 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15816 if (ps != null) { 15817 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15818 } 15819 15820 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15821 for (int i = 0; i < childCount; i++) { 15822 PackageParser.Package childPkg = pkg.childPackages.get(i); 15823 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15824 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15825 if (childPs != null) { 15826 childRes.newUsers = childPs.queryInstalledUsers( 15827 sUserManager.getUserIds(), true); 15828 } 15829 } 15830 } 15831 } 15832 15833 private void startIntentFilterVerifications(int userId, boolean replacing, 15834 PackageParser.Package pkg) { 15835 if (mIntentFilterVerifierComponent == null) { 15836 Slog.w(TAG, "No IntentFilter verification will not be done as " 15837 + "there is no IntentFilterVerifier available!"); 15838 return; 15839 } 15840 15841 final int verifierUid = getPackageUid( 15842 mIntentFilterVerifierComponent.getPackageName(), 15843 MATCH_DEBUG_TRIAGED_MISSING, 15844 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15845 15846 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15847 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15848 mHandler.sendMessage(msg); 15849 15850 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15851 for (int i = 0; i < childCount; i++) { 15852 PackageParser.Package childPkg = pkg.childPackages.get(i); 15853 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15854 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15855 mHandler.sendMessage(msg); 15856 } 15857 } 15858 15859 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15860 PackageParser.Package pkg) { 15861 int size = pkg.activities.size(); 15862 if (size == 0) { 15863 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15864 "No activity, so no need to verify any IntentFilter!"); 15865 return; 15866 } 15867 15868 final boolean hasDomainURLs = hasDomainURLs(pkg); 15869 if (!hasDomainURLs) { 15870 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15871 "No domain URLs, so no need to verify any IntentFilter!"); 15872 return; 15873 } 15874 15875 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15876 + " if any IntentFilter from the " + size 15877 + " Activities needs verification ..."); 15878 15879 int count = 0; 15880 final String packageName = pkg.packageName; 15881 15882 synchronized (mPackages) { 15883 // If this is a new install and we see that we've already run verification for this 15884 // package, we have nothing to do: it means the state was restored from backup. 15885 if (!replacing) { 15886 IntentFilterVerificationInfo ivi = 15887 mSettings.getIntentFilterVerificationLPr(packageName); 15888 if (ivi != null) { 15889 if (DEBUG_DOMAIN_VERIFICATION) { 15890 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15891 + ivi.getStatusString()); 15892 } 15893 return; 15894 } 15895 } 15896 15897 // If any filters need to be verified, then all need to be. 15898 boolean needToVerify = false; 15899 for (PackageParser.Activity a : pkg.activities) { 15900 for (ActivityIntentInfo filter : a.intents) { 15901 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15902 if (DEBUG_DOMAIN_VERIFICATION) { 15903 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15904 } 15905 needToVerify = true; 15906 break; 15907 } 15908 } 15909 } 15910 15911 if (needToVerify) { 15912 final int verificationId = mIntentFilterVerificationToken++; 15913 for (PackageParser.Activity a : pkg.activities) { 15914 for (ActivityIntentInfo filter : a.intents) { 15915 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15916 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15917 "Verification needed for IntentFilter:" + filter.toString()); 15918 mIntentFilterVerifier.addOneIntentFilterVerification( 15919 verifierUid, userId, verificationId, filter, packageName); 15920 count++; 15921 } 15922 } 15923 } 15924 } 15925 } 15926 15927 if (count > 0) { 15928 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15929 + " IntentFilter verification" + (count > 1 ? "s" : "") 15930 + " for userId:" + userId); 15931 mIntentFilterVerifier.startVerifications(userId); 15932 } else { 15933 if (DEBUG_DOMAIN_VERIFICATION) { 15934 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15935 } 15936 } 15937 } 15938 15939 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15940 final ComponentName cn = filter.activity.getComponentName(); 15941 final String packageName = cn.getPackageName(); 15942 15943 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15944 packageName); 15945 if (ivi == null) { 15946 return true; 15947 } 15948 int status = ivi.getStatus(); 15949 switch (status) { 15950 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15951 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15952 return true; 15953 15954 default: 15955 // Nothing to do 15956 return false; 15957 } 15958 } 15959 15960 private static boolean isMultiArch(ApplicationInfo info) { 15961 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15962 } 15963 15964 private static boolean isExternal(PackageParser.Package pkg) { 15965 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15966 } 15967 15968 private static boolean isExternal(PackageSetting ps) { 15969 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15970 } 15971 15972 private static boolean isEphemeral(PackageParser.Package pkg) { 15973 return pkg.applicationInfo.isEphemeralApp(); 15974 } 15975 15976 private static boolean isEphemeral(PackageSetting ps) { 15977 return ps.pkg != null && isEphemeral(ps.pkg); 15978 } 15979 15980 private static boolean isSystemApp(PackageParser.Package pkg) { 15981 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15982 } 15983 15984 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15985 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15986 } 15987 15988 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15989 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15990 } 15991 15992 private static boolean isSystemApp(PackageSetting ps) { 15993 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15994 } 15995 15996 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15997 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15998 } 15999 16000 private int packageFlagsToInstallFlags(PackageSetting ps) { 16001 int installFlags = 0; 16002 if (isEphemeral(ps)) { 16003 installFlags |= PackageManager.INSTALL_EPHEMERAL; 16004 } 16005 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 16006 // This existing package was an external ASEC install when we have 16007 // the external flag without a UUID 16008 installFlags |= PackageManager.INSTALL_EXTERNAL; 16009 } 16010 if (ps.isForwardLocked()) { 16011 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 16012 } 16013 return installFlags; 16014 } 16015 16016 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 16017 if (isExternal(pkg)) { 16018 if (TextUtils.isEmpty(pkg.volumeUuid)) { 16019 return StorageManager.UUID_PRIMARY_PHYSICAL; 16020 } else { 16021 return pkg.volumeUuid; 16022 } 16023 } else { 16024 return StorageManager.UUID_PRIVATE_INTERNAL; 16025 } 16026 } 16027 16028 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 16029 if (isExternal(pkg)) { 16030 if (TextUtils.isEmpty(pkg.volumeUuid)) { 16031 return mSettings.getExternalVersion(); 16032 } else { 16033 return mSettings.findOrCreateVersion(pkg.volumeUuid); 16034 } 16035 } else { 16036 return mSettings.getInternalVersion(); 16037 } 16038 } 16039 16040 private void deleteTempPackageFiles() { 16041 final FilenameFilter filter = new FilenameFilter() { 16042 public boolean accept(File dir, String name) { 16043 return name.startsWith("vmdl") && name.endsWith(".tmp"); 16044 } 16045 }; 16046 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 16047 file.delete(); 16048 } 16049 } 16050 16051 @Override 16052 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 16053 int flags) { 16054 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 16055 flags); 16056 } 16057 16058 @Override 16059 public void deletePackage(final String packageName, 16060 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 16061 mContext.enforceCallingOrSelfPermission( 16062 android.Manifest.permission.DELETE_PACKAGES, null); 16063 Preconditions.checkNotNull(packageName); 16064 Preconditions.checkNotNull(observer); 16065 final int uid = Binder.getCallingUid(); 16066 if (!isOrphaned(packageName) 16067 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 16068 try { 16069 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 16070 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 16071 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 16072 observer.onUserActionRequired(intent); 16073 } catch (RemoteException re) { 16074 } 16075 return; 16076 } 16077 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 16078 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 16079 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 16080 mContext.enforceCallingOrSelfPermission( 16081 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 16082 "deletePackage for user " + userId); 16083 } 16084 16085 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 16086 try { 16087 observer.onPackageDeleted(packageName, 16088 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 16089 } catch (RemoteException re) { 16090 } 16091 return; 16092 } 16093 16094 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 16095 try { 16096 observer.onPackageDeleted(packageName, 16097 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 16098 } catch (RemoteException re) { 16099 } 16100 return; 16101 } 16102 16103 if (DEBUG_REMOVE) { 16104 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 16105 + " deleteAllUsers: " + deleteAllUsers ); 16106 } 16107 // Queue up an async operation since the package deletion may take a little while. 16108 mHandler.post(new Runnable() { 16109 public void run() { 16110 mHandler.removeCallbacks(this); 16111 int returnCode; 16112 if (!deleteAllUsers) { 16113 returnCode = deletePackageX(packageName, userId, deleteFlags); 16114 } else { 16115 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 16116 // If nobody is blocking uninstall, proceed with delete for all users 16117 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 16118 returnCode = deletePackageX(packageName, userId, deleteFlags); 16119 } else { 16120 // Otherwise uninstall individually for users with blockUninstalls=false 16121 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 16122 for (int userId : users) { 16123 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 16124 returnCode = deletePackageX(packageName, userId, userFlags); 16125 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 16126 Slog.w(TAG, "Package delete failed for user " + userId 16127 + ", returnCode " + returnCode); 16128 } 16129 } 16130 } 16131 // The app has only been marked uninstalled for certain users. 16132 // We still need to report that delete was blocked 16133 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 16134 } 16135 } 16136 try { 16137 observer.onPackageDeleted(packageName, returnCode, null); 16138 } catch (RemoteException e) { 16139 Log.i(TAG, "Observer no longer exists."); 16140 } //end catch 16141 } //end run 16142 }); 16143 } 16144 16145 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 16146 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 16147 || callingUid == Process.SYSTEM_UID) { 16148 return true; 16149 } 16150 final int callingUserId = UserHandle.getUserId(callingUid); 16151 // If the caller installed the pkgName, then allow it to silently uninstall. 16152 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 16153 return true; 16154 } 16155 16156 // Allow package verifier to silently uninstall. 16157 if (mRequiredVerifierPackage != null && 16158 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 16159 return true; 16160 } 16161 16162 // Allow package uninstaller to silently uninstall. 16163 if (mRequiredUninstallerPackage != null && 16164 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 16165 return true; 16166 } 16167 16168 // Allow storage manager to silently uninstall. 16169 if (mStorageManagerPackage != null && 16170 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 16171 return true; 16172 } 16173 return false; 16174 } 16175 16176 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 16177 int[] result = EMPTY_INT_ARRAY; 16178 for (int userId : userIds) { 16179 if (getBlockUninstallForUser(packageName, userId)) { 16180 result = ArrayUtils.appendInt(result, userId); 16181 } 16182 } 16183 return result; 16184 } 16185 16186 @Override 16187 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 16188 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 16189 } 16190 16191 private boolean isPackageDeviceAdmin(String packageName, int userId) { 16192 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 16193 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 16194 try { 16195 if (dpm != null) { 16196 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 16197 /* callingUserOnly =*/ false); 16198 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 16199 : deviceOwnerComponentName.getPackageName(); 16200 // Does the package contains the device owner? 16201 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 16202 // this check is probably not needed, since DO should be registered as a device 16203 // admin on some user too. (Original bug for this: b/17657954) 16204 if (packageName.equals(deviceOwnerPackageName)) { 16205 return true; 16206 } 16207 // Does it contain a device admin for any user? 16208 int[] users; 16209 if (userId == UserHandle.USER_ALL) { 16210 users = sUserManager.getUserIds(); 16211 } else { 16212 users = new int[]{userId}; 16213 } 16214 for (int i = 0; i < users.length; ++i) { 16215 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 16216 return true; 16217 } 16218 } 16219 } 16220 } catch (RemoteException e) { 16221 } 16222 return false; 16223 } 16224 16225 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 16226 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 16227 } 16228 16229 /** 16230 * This method is an internal method that could be get invoked either 16231 * to delete an installed package or to clean up a failed installation. 16232 * After deleting an installed package, a broadcast is sent to notify any 16233 * listeners that the package has been removed. For cleaning up a failed 16234 * installation, the broadcast is not necessary since the package's 16235 * installation wouldn't have sent the initial broadcast either 16236 * The key steps in deleting a package are 16237 * deleting the package information in internal structures like mPackages, 16238 * deleting the packages base directories through installd 16239 * updating mSettings to reflect current status 16240 * persisting settings for later use 16241 * sending a broadcast if necessary 16242 */ 16243 private int deletePackageX(String packageName, int userId, int deleteFlags) { 16244 final PackageRemovedInfo info = new PackageRemovedInfo(); 16245 final boolean res; 16246 16247 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 16248 ? UserHandle.USER_ALL : userId; 16249 16250 if (isPackageDeviceAdmin(packageName, removeUser)) { 16251 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 16252 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 16253 } 16254 16255 PackageSetting uninstalledPs = null; 16256 16257 // for the uninstall-updates case and restricted profiles, remember the per- 16258 // user handle installed state 16259 int[] allUsers; 16260 synchronized (mPackages) { 16261 uninstalledPs = mSettings.mPackages.get(packageName); 16262 if (uninstalledPs == null) { 16263 Slog.w(TAG, "Not removing non-existent package " + packageName); 16264 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 16265 } 16266 allUsers = sUserManager.getUserIds(); 16267 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 16268 } 16269 16270 final int freezeUser; 16271 if (isUpdatedSystemApp(uninstalledPs) 16272 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 16273 // We're downgrading a system app, which will apply to all users, so 16274 // freeze them all during the downgrade 16275 freezeUser = UserHandle.USER_ALL; 16276 } else { 16277 freezeUser = removeUser; 16278 } 16279 16280 synchronized (mInstallLock) { 16281 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 16282 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 16283 deleteFlags, "deletePackageX")) { 16284 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 16285 deleteFlags | REMOVE_CHATTY, info, true, null); 16286 } 16287 synchronized (mPackages) { 16288 if (res) { 16289 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 16290 } 16291 } 16292 } 16293 16294 if (res) { 16295 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 16296 info.sendPackageRemovedBroadcasts(killApp); 16297 info.sendSystemPackageUpdatedBroadcasts(); 16298 info.sendSystemPackageAppearedBroadcasts(); 16299 } 16300 // Force a gc here. 16301 Runtime.getRuntime().gc(); 16302 // Delete the resources here after sending the broadcast to let 16303 // other processes clean up before deleting resources. 16304 if (info.args != null) { 16305 synchronized (mInstallLock) { 16306 info.args.doPostDeleteLI(true); 16307 } 16308 } 16309 16310 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 16311 } 16312 16313 class PackageRemovedInfo { 16314 String removedPackage; 16315 int uid = -1; 16316 int removedAppId = -1; 16317 int[] origUsers; 16318 int[] removedUsers = null; 16319 boolean isRemovedPackageSystemUpdate = false; 16320 boolean isUpdate; 16321 boolean dataRemoved; 16322 boolean removedForAllUsers; 16323 // Clean up resources deleted packages. 16324 InstallArgs args = null; 16325 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 16326 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 16327 16328 void sendPackageRemovedBroadcasts(boolean killApp) { 16329 sendPackageRemovedBroadcastInternal(killApp); 16330 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 16331 for (int i = 0; i < childCount; i++) { 16332 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 16333 childInfo.sendPackageRemovedBroadcastInternal(killApp); 16334 } 16335 } 16336 16337 void sendSystemPackageUpdatedBroadcasts() { 16338 if (isRemovedPackageSystemUpdate) { 16339 sendSystemPackageUpdatedBroadcastsInternal(); 16340 final int childCount = (removedChildPackages != null) 16341 ? removedChildPackages.size() : 0; 16342 for (int i = 0; i < childCount; i++) { 16343 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 16344 if (childInfo.isRemovedPackageSystemUpdate) { 16345 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 16346 } 16347 } 16348 } 16349 } 16350 16351 void sendSystemPackageAppearedBroadcasts() { 16352 final int packageCount = (appearedChildPackages != null) 16353 ? appearedChildPackages.size() : 0; 16354 for (int i = 0; i < packageCount; i++) { 16355 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 16356 sendPackageAddedForNewUsers(installedInfo.name, true, 16357 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 16358 } 16359 } 16360 16361 private void sendSystemPackageUpdatedBroadcastsInternal() { 16362 Bundle extras = new Bundle(2); 16363 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16364 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16365 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 16366 extras, 0, null, null, null); 16367 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 16368 extras, 0, null, null, null); 16369 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 16370 null, 0, removedPackage, null, null); 16371 } 16372 16373 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 16374 Bundle extras = new Bundle(2); 16375 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16376 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 16377 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 16378 if (isUpdate || isRemovedPackageSystemUpdate) { 16379 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16380 } 16381 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 16382 if (removedPackage != null) { 16383 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 16384 extras, 0, null, null, removedUsers); 16385 if (dataRemoved && !isRemovedPackageSystemUpdate) { 16386 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 16387 removedPackage, extras, 0, null, null, removedUsers); 16388 } 16389 } 16390 if (removedAppId >= 0) { 16391 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 16392 removedUsers); 16393 } 16394 } 16395 } 16396 16397 /* 16398 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 16399 * flag is not set, the data directory is removed as well. 16400 * make sure this flag is set for partially installed apps. If not its meaningless to 16401 * delete a partially installed application. 16402 */ 16403 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 16404 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 16405 String packageName = ps.name; 16406 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 16407 // Retrieve object to delete permissions for shared user later on 16408 final PackageParser.Package deletedPkg; 16409 final PackageSetting deletedPs; 16410 // reader 16411 synchronized (mPackages) { 16412 deletedPkg = mPackages.get(packageName); 16413 deletedPs = mSettings.mPackages.get(packageName); 16414 if (outInfo != null) { 16415 outInfo.removedPackage = packageName; 16416 outInfo.removedUsers = deletedPs != null 16417 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 16418 : null; 16419 } 16420 } 16421 16422 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 16423 16424 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 16425 final PackageParser.Package resolvedPkg; 16426 if (deletedPkg != null) { 16427 resolvedPkg = deletedPkg; 16428 } else { 16429 // We don't have a parsed package when it lives on an ejected 16430 // adopted storage device, so fake something together 16431 resolvedPkg = new PackageParser.Package(ps.name); 16432 resolvedPkg.setVolumeUuid(ps.volumeUuid); 16433 } 16434 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 16435 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16436 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 16437 if (outInfo != null) { 16438 outInfo.dataRemoved = true; 16439 } 16440 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 16441 } 16442 16443 // writer 16444 synchronized (mPackages) { 16445 if (deletedPs != null) { 16446 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 16447 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 16448 clearDefaultBrowserIfNeeded(packageName); 16449 if (outInfo != null) { 16450 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 16451 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 16452 } 16453 updatePermissionsLPw(deletedPs.name, null, 0); 16454 if (deletedPs.sharedUser != null) { 16455 // Remove permissions associated with package. Since runtime 16456 // permissions are per user we have to kill the removed package 16457 // or packages running under the shared user of the removed 16458 // package if revoking the permissions requested only by the removed 16459 // package is successful and this causes a change in gids. 16460 for (int userId : UserManagerService.getInstance().getUserIds()) { 16461 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 16462 userId); 16463 if (userIdToKill == UserHandle.USER_ALL 16464 || userIdToKill >= UserHandle.USER_SYSTEM) { 16465 // If gids changed for this user, kill all affected packages. 16466 mHandler.post(new Runnable() { 16467 @Override 16468 public void run() { 16469 // This has to happen with no lock held. 16470 killApplication(deletedPs.name, deletedPs.appId, 16471 KILL_APP_REASON_GIDS_CHANGED); 16472 } 16473 }); 16474 break; 16475 } 16476 } 16477 } 16478 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 16479 } 16480 // make sure to preserve per-user disabled state if this removal was just 16481 // a downgrade of a system app to the factory package 16482 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 16483 if (DEBUG_REMOVE) { 16484 Slog.d(TAG, "Propagating install state across downgrade"); 16485 } 16486 for (int userId : allUserHandles) { 16487 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16488 if (DEBUG_REMOVE) { 16489 Slog.d(TAG, " user " + userId + " => " + installed); 16490 } 16491 ps.setInstalled(installed, userId); 16492 } 16493 } 16494 } 16495 // can downgrade to reader 16496 if (writeSettings) { 16497 // Save settings now 16498 mSettings.writeLPr(); 16499 } 16500 } 16501 if (outInfo != null) { 16502 // A user ID was deleted here. Go through all users and remove it 16503 // from KeyStore. 16504 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 16505 } 16506 } 16507 16508 static boolean locationIsPrivileged(File path) { 16509 try { 16510 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 16511 .getCanonicalPath(); 16512 return path.getCanonicalPath().startsWith(privilegedAppDir); 16513 } catch (IOException e) { 16514 Slog.e(TAG, "Unable to access code path " + path); 16515 } 16516 return false; 16517 } 16518 16519 /* 16520 * Tries to delete system package. 16521 */ 16522 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 16523 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 16524 boolean writeSettings) { 16525 if (deletedPs.parentPackageName != null) { 16526 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 16527 return false; 16528 } 16529 16530 final boolean applyUserRestrictions 16531 = (allUserHandles != null) && (outInfo.origUsers != null); 16532 final PackageSetting disabledPs; 16533 // Confirm if the system package has been updated 16534 // An updated system app can be deleted. This will also have to restore 16535 // the system pkg from system partition 16536 // reader 16537 synchronized (mPackages) { 16538 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 16539 } 16540 16541 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 16542 + " disabledPs=" + disabledPs); 16543 16544 if (disabledPs == null) { 16545 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 16546 return false; 16547 } else if (DEBUG_REMOVE) { 16548 Slog.d(TAG, "Deleting system pkg from data partition"); 16549 } 16550 16551 if (DEBUG_REMOVE) { 16552 if (applyUserRestrictions) { 16553 Slog.d(TAG, "Remembering install states:"); 16554 for (int userId : allUserHandles) { 16555 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 16556 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 16557 } 16558 } 16559 } 16560 16561 // Delete the updated package 16562 outInfo.isRemovedPackageSystemUpdate = true; 16563 if (outInfo.removedChildPackages != null) { 16564 final int childCount = (deletedPs.childPackageNames != null) 16565 ? deletedPs.childPackageNames.size() : 0; 16566 for (int i = 0; i < childCount; i++) { 16567 String childPackageName = deletedPs.childPackageNames.get(i); 16568 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16569 .contains(childPackageName)) { 16570 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16571 childPackageName); 16572 if (childInfo != null) { 16573 childInfo.isRemovedPackageSystemUpdate = true; 16574 } 16575 } 16576 } 16577 } 16578 16579 if (disabledPs.versionCode < deletedPs.versionCode) { 16580 // Delete data for downgrades 16581 flags &= ~PackageManager.DELETE_KEEP_DATA; 16582 } else { 16583 // Preserve data by setting flag 16584 flags |= PackageManager.DELETE_KEEP_DATA; 16585 } 16586 16587 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16588 outInfo, writeSettings, disabledPs.pkg); 16589 if (!ret) { 16590 return false; 16591 } 16592 16593 // writer 16594 synchronized (mPackages) { 16595 // Reinstate the old system package 16596 enableSystemPackageLPw(disabledPs.pkg); 16597 // Remove any native libraries from the upgraded package. 16598 removeNativeBinariesLI(deletedPs); 16599 } 16600 16601 // Install the system package 16602 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16603 int parseFlags = mDefParseFlags 16604 | PackageParser.PARSE_MUST_BE_APK 16605 | PackageParser.PARSE_IS_SYSTEM 16606 | PackageParser.PARSE_IS_SYSTEM_DIR; 16607 if (locationIsPrivileged(disabledPs.codePath)) { 16608 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16609 } 16610 16611 final PackageParser.Package newPkg; 16612 try { 16613 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 16614 0 /* currentTime */, null); 16615 } catch (PackageManagerException e) { 16616 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16617 + e.getMessage()); 16618 return false; 16619 } 16620 try { 16621 // update shared libraries for the newly re-installed system package 16622 updateSharedLibrariesLPr(newPkg, null); 16623 } catch (PackageManagerException e) { 16624 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16625 } 16626 16627 prepareAppDataAfterInstallLIF(newPkg); 16628 16629 // writer 16630 synchronized (mPackages) { 16631 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16632 16633 // Propagate the permissions state as we do not want to drop on the floor 16634 // runtime permissions. The update permissions method below will take 16635 // care of removing obsolete permissions and grant install permissions. 16636 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16637 updatePermissionsLPw(newPkg.packageName, newPkg, 16638 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16639 16640 if (applyUserRestrictions) { 16641 if (DEBUG_REMOVE) { 16642 Slog.d(TAG, "Propagating install state across reinstall"); 16643 } 16644 for (int userId : allUserHandles) { 16645 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16646 if (DEBUG_REMOVE) { 16647 Slog.d(TAG, " user " + userId + " => " + installed); 16648 } 16649 ps.setInstalled(installed, userId); 16650 16651 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16652 } 16653 // Regardless of writeSettings we need to ensure that this restriction 16654 // state propagation is persisted 16655 mSettings.writeAllUsersPackageRestrictionsLPr(); 16656 } 16657 // can downgrade to reader here 16658 if (writeSettings) { 16659 mSettings.writeLPr(); 16660 } 16661 } 16662 return true; 16663 } 16664 16665 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16666 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16667 PackageRemovedInfo outInfo, boolean writeSettings, 16668 PackageParser.Package replacingPackage) { 16669 synchronized (mPackages) { 16670 if (outInfo != null) { 16671 outInfo.uid = ps.appId; 16672 } 16673 16674 if (outInfo != null && outInfo.removedChildPackages != null) { 16675 final int childCount = (ps.childPackageNames != null) 16676 ? ps.childPackageNames.size() : 0; 16677 for (int i = 0; i < childCount; i++) { 16678 String childPackageName = ps.childPackageNames.get(i); 16679 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16680 if (childPs == null) { 16681 return false; 16682 } 16683 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16684 childPackageName); 16685 if (childInfo != null) { 16686 childInfo.uid = childPs.appId; 16687 } 16688 } 16689 } 16690 } 16691 16692 // Delete package data from internal structures and also remove data if flag is set 16693 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16694 16695 // Delete the child packages data 16696 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16697 for (int i = 0; i < childCount; i++) { 16698 PackageSetting childPs; 16699 synchronized (mPackages) { 16700 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16701 } 16702 if (childPs != null) { 16703 PackageRemovedInfo childOutInfo = (outInfo != null 16704 && outInfo.removedChildPackages != null) 16705 ? outInfo.removedChildPackages.get(childPs.name) : null; 16706 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16707 && (replacingPackage != null 16708 && !replacingPackage.hasChildPackage(childPs.name)) 16709 ? flags & ~DELETE_KEEP_DATA : flags; 16710 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16711 deleteFlags, writeSettings); 16712 } 16713 } 16714 16715 // Delete application code and resources only for parent packages 16716 if (ps.parentPackageName == null) { 16717 if (deleteCodeAndResources && (outInfo != null)) { 16718 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16719 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16720 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16721 } 16722 } 16723 16724 return true; 16725 } 16726 16727 @Override 16728 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16729 int userId) { 16730 mContext.enforceCallingOrSelfPermission( 16731 android.Manifest.permission.DELETE_PACKAGES, null); 16732 synchronized (mPackages) { 16733 PackageSetting ps = mSettings.mPackages.get(packageName); 16734 if (ps == null) { 16735 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16736 return false; 16737 } 16738 if (!ps.getInstalled(userId)) { 16739 // Can't block uninstall for an app that is not installed or enabled. 16740 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16741 return false; 16742 } 16743 ps.setBlockUninstall(blockUninstall, userId); 16744 mSettings.writePackageRestrictionsLPr(userId); 16745 } 16746 return true; 16747 } 16748 16749 @Override 16750 public boolean getBlockUninstallForUser(String packageName, int userId) { 16751 synchronized (mPackages) { 16752 PackageSetting ps = mSettings.mPackages.get(packageName); 16753 if (ps == null) { 16754 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16755 return false; 16756 } 16757 return ps.getBlockUninstall(userId); 16758 } 16759 } 16760 16761 @Override 16762 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16763 int callingUid = Binder.getCallingUid(); 16764 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16765 throw new SecurityException( 16766 "setRequiredForSystemUser can only be run by the system or root"); 16767 } 16768 synchronized (mPackages) { 16769 PackageSetting ps = mSettings.mPackages.get(packageName); 16770 if (ps == null) { 16771 Log.w(TAG, "Package doesn't exist: " + packageName); 16772 return false; 16773 } 16774 if (systemUserApp) { 16775 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16776 } else { 16777 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16778 } 16779 mSettings.writeLPr(); 16780 } 16781 return true; 16782 } 16783 16784 /* 16785 * This method handles package deletion in general 16786 */ 16787 private boolean deletePackageLIF(String packageName, UserHandle user, 16788 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16789 PackageRemovedInfo outInfo, boolean writeSettings, 16790 PackageParser.Package replacingPackage) { 16791 if (packageName == null) { 16792 Slog.w(TAG, "Attempt to delete null packageName."); 16793 return false; 16794 } 16795 16796 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16797 16798 PackageSetting ps; 16799 16800 synchronized (mPackages) { 16801 ps = mSettings.mPackages.get(packageName); 16802 if (ps == null) { 16803 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16804 return false; 16805 } 16806 16807 if (ps.parentPackageName != null && (!isSystemApp(ps) 16808 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16809 if (DEBUG_REMOVE) { 16810 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16811 + ((user == null) ? UserHandle.USER_ALL : user)); 16812 } 16813 final int removedUserId = (user != null) ? user.getIdentifier() 16814 : UserHandle.USER_ALL; 16815 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16816 return false; 16817 } 16818 markPackageUninstalledForUserLPw(ps, user); 16819 scheduleWritePackageRestrictionsLocked(user); 16820 return true; 16821 } 16822 } 16823 16824 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16825 && user.getIdentifier() != UserHandle.USER_ALL)) { 16826 // The caller is asking that the package only be deleted for a single 16827 // user. To do this, we just mark its uninstalled state and delete 16828 // its data. If this is a system app, we only allow this to happen if 16829 // they have set the special DELETE_SYSTEM_APP which requests different 16830 // semantics than normal for uninstalling system apps. 16831 markPackageUninstalledForUserLPw(ps, user); 16832 16833 if (!isSystemApp(ps)) { 16834 // Do not uninstall the APK if an app should be cached 16835 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16836 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16837 // Other user still have this package installed, so all 16838 // we need to do is clear this user's data and save that 16839 // it is uninstalled. 16840 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16841 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16842 return false; 16843 } 16844 scheduleWritePackageRestrictionsLocked(user); 16845 return true; 16846 } else { 16847 // We need to set it back to 'installed' so the uninstall 16848 // broadcasts will be sent correctly. 16849 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16850 ps.setInstalled(true, user.getIdentifier()); 16851 } 16852 } else { 16853 // This is a system app, so we assume that the 16854 // other users still have this package installed, so all 16855 // we need to do is clear this user's data and save that 16856 // it is uninstalled. 16857 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16858 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16859 return false; 16860 } 16861 scheduleWritePackageRestrictionsLocked(user); 16862 return true; 16863 } 16864 } 16865 16866 // If we are deleting a composite package for all users, keep track 16867 // of result for each child. 16868 if (ps.childPackageNames != null && outInfo != null) { 16869 synchronized (mPackages) { 16870 final int childCount = ps.childPackageNames.size(); 16871 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16872 for (int i = 0; i < childCount; i++) { 16873 String childPackageName = ps.childPackageNames.get(i); 16874 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16875 childInfo.removedPackage = childPackageName; 16876 outInfo.removedChildPackages.put(childPackageName, childInfo); 16877 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16878 if (childPs != null) { 16879 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16880 } 16881 } 16882 } 16883 } 16884 16885 boolean ret = false; 16886 if (isSystemApp(ps)) { 16887 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16888 // When an updated system application is deleted we delete the existing resources 16889 // as well and fall back to existing code in system partition 16890 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16891 } else { 16892 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16893 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16894 outInfo, writeSettings, replacingPackage); 16895 } 16896 16897 // Take a note whether we deleted the package for all users 16898 if (outInfo != null) { 16899 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16900 if (outInfo.removedChildPackages != null) { 16901 synchronized (mPackages) { 16902 final int childCount = outInfo.removedChildPackages.size(); 16903 for (int i = 0; i < childCount; i++) { 16904 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16905 if (childInfo != null) { 16906 childInfo.removedForAllUsers = mPackages.get( 16907 childInfo.removedPackage) == null; 16908 } 16909 } 16910 } 16911 } 16912 // If we uninstalled an update to a system app there may be some 16913 // child packages that appeared as they are declared in the system 16914 // app but were not declared in the update. 16915 if (isSystemApp(ps)) { 16916 synchronized (mPackages) { 16917 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 16918 final int childCount = (updatedPs.childPackageNames != null) 16919 ? updatedPs.childPackageNames.size() : 0; 16920 for (int i = 0; i < childCount; i++) { 16921 String childPackageName = updatedPs.childPackageNames.get(i); 16922 if (outInfo.removedChildPackages == null 16923 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16924 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16925 if (childPs == null) { 16926 continue; 16927 } 16928 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16929 installRes.name = childPackageName; 16930 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16931 installRes.pkg = mPackages.get(childPackageName); 16932 installRes.uid = childPs.pkg.applicationInfo.uid; 16933 if (outInfo.appearedChildPackages == null) { 16934 outInfo.appearedChildPackages = new ArrayMap<>(); 16935 } 16936 outInfo.appearedChildPackages.put(childPackageName, installRes); 16937 } 16938 } 16939 } 16940 } 16941 } 16942 16943 return ret; 16944 } 16945 16946 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16947 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16948 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16949 for (int nextUserId : userIds) { 16950 if (DEBUG_REMOVE) { 16951 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16952 } 16953 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16954 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16955 false /*hidden*/, false /*suspended*/, null, null, null, 16956 false /*blockUninstall*/, 16957 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16958 } 16959 } 16960 16961 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16962 PackageRemovedInfo outInfo) { 16963 final PackageParser.Package pkg; 16964 synchronized (mPackages) { 16965 pkg = mPackages.get(ps.name); 16966 } 16967 16968 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16969 : new int[] {userId}; 16970 for (int nextUserId : userIds) { 16971 if (DEBUG_REMOVE) { 16972 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16973 + nextUserId); 16974 } 16975 16976 destroyAppDataLIF(pkg, userId, 16977 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16978 destroyAppProfilesLIF(pkg, userId); 16979 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16980 schedulePackageCleaning(ps.name, nextUserId, false); 16981 synchronized (mPackages) { 16982 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16983 scheduleWritePackageRestrictionsLocked(nextUserId); 16984 } 16985 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16986 } 16987 } 16988 16989 if (outInfo != null) { 16990 outInfo.removedPackage = ps.name; 16991 outInfo.removedAppId = ps.appId; 16992 outInfo.removedUsers = userIds; 16993 } 16994 16995 return true; 16996 } 16997 16998 private final class ClearStorageConnection implements ServiceConnection { 16999 IMediaContainerService mContainerService; 17000 17001 @Override 17002 public void onServiceConnected(ComponentName name, IBinder service) { 17003 synchronized (this) { 17004 mContainerService = IMediaContainerService.Stub 17005 .asInterface(Binder.allowBlocking(service)); 17006 notifyAll(); 17007 } 17008 } 17009 17010 @Override 17011 public void onServiceDisconnected(ComponentName name) { 17012 } 17013 } 17014 17015 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 17016 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 17017 17018 final boolean mounted; 17019 if (Environment.isExternalStorageEmulated()) { 17020 mounted = true; 17021 } else { 17022 final String status = Environment.getExternalStorageState(); 17023 17024 mounted = status.equals(Environment.MEDIA_MOUNTED) 17025 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 17026 } 17027 17028 if (!mounted) { 17029 return; 17030 } 17031 17032 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 17033 int[] users; 17034 if (userId == UserHandle.USER_ALL) { 17035 users = sUserManager.getUserIds(); 17036 } else { 17037 users = new int[] { userId }; 17038 } 17039 final ClearStorageConnection conn = new ClearStorageConnection(); 17040 if (mContext.bindServiceAsUser( 17041 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 17042 try { 17043 for (int curUser : users) { 17044 long timeout = SystemClock.uptimeMillis() + 5000; 17045 synchronized (conn) { 17046 long now; 17047 while (conn.mContainerService == null && 17048 (now = SystemClock.uptimeMillis()) < timeout) { 17049 try { 17050 conn.wait(timeout - now); 17051 } catch (InterruptedException e) { 17052 } 17053 } 17054 } 17055 if (conn.mContainerService == null) { 17056 return; 17057 } 17058 17059 final UserEnvironment userEnv = new UserEnvironment(curUser); 17060 clearDirectory(conn.mContainerService, 17061 userEnv.buildExternalStorageAppCacheDirs(packageName)); 17062 if (allData) { 17063 clearDirectory(conn.mContainerService, 17064 userEnv.buildExternalStorageAppDataDirs(packageName)); 17065 clearDirectory(conn.mContainerService, 17066 userEnv.buildExternalStorageAppMediaDirs(packageName)); 17067 } 17068 } 17069 } finally { 17070 mContext.unbindService(conn); 17071 } 17072 } 17073 } 17074 17075 @Override 17076 public void clearApplicationProfileData(String packageName) { 17077 enforceSystemOrRoot("Only the system can clear all profile data"); 17078 17079 final PackageParser.Package pkg; 17080 synchronized (mPackages) { 17081 pkg = mPackages.get(packageName); 17082 } 17083 17084 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 17085 synchronized (mInstallLock) { 17086 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 17087 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 17088 true /* removeBaseMarker */); 17089 } 17090 } 17091 } 17092 17093 @Override 17094 public void clearApplicationUserData(final String packageName, 17095 final IPackageDataObserver observer, final int userId) { 17096 mContext.enforceCallingOrSelfPermission( 17097 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 17098 17099 enforceCrossUserPermission(Binder.getCallingUid(), userId, 17100 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 17101 17102 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 17103 throw new SecurityException("Cannot clear data for a protected package: " 17104 + packageName); 17105 } 17106 // Queue up an async operation since the package deletion may take a little while. 17107 mHandler.post(new Runnable() { 17108 public void run() { 17109 mHandler.removeCallbacks(this); 17110 final boolean succeeded; 17111 try (PackageFreezer freezer = freezePackage(packageName, 17112 "clearApplicationUserData")) { 17113 synchronized (mInstallLock) { 17114 succeeded = clearApplicationUserDataLIF(packageName, userId); 17115 } 17116 clearExternalStorageDataSync(packageName, userId, true); 17117 } 17118 if (succeeded) { 17119 // invoke DeviceStorageMonitor's update method to clear any notifications 17120 DeviceStorageMonitorInternal dsm = LocalServices 17121 .getService(DeviceStorageMonitorInternal.class); 17122 if (dsm != null) { 17123 dsm.checkMemory(); 17124 } 17125 } 17126 if(observer != null) { 17127 try { 17128 observer.onRemoveCompleted(packageName, succeeded); 17129 } catch (RemoteException e) { 17130 Log.i(TAG, "Observer no longer exists."); 17131 } 17132 } //end if observer 17133 } //end run 17134 }); 17135 } 17136 17137 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 17138 if (packageName == null) { 17139 Slog.w(TAG, "Attempt to delete null packageName."); 17140 return false; 17141 } 17142 17143 // Try finding details about the requested package 17144 PackageParser.Package pkg; 17145 synchronized (mPackages) { 17146 pkg = mPackages.get(packageName); 17147 if (pkg == null) { 17148 final PackageSetting ps = mSettings.mPackages.get(packageName); 17149 if (ps != null) { 17150 pkg = ps.pkg; 17151 } 17152 } 17153 17154 if (pkg == null) { 17155 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 17156 return false; 17157 } 17158 17159 PackageSetting ps = (PackageSetting) pkg.mExtras; 17160 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 17161 } 17162 17163 clearAppDataLIF(pkg, userId, 17164 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17165 17166 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 17167 removeKeystoreDataIfNeeded(userId, appId); 17168 17169 UserManagerInternal umInternal = getUserManagerInternal(); 17170 final int flags; 17171 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 17172 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17173 } else if (umInternal.isUserRunning(userId)) { 17174 flags = StorageManager.FLAG_STORAGE_DE; 17175 } else { 17176 flags = 0; 17177 } 17178 prepareAppDataContentsLIF(pkg, userId, flags); 17179 17180 return true; 17181 } 17182 17183 /** 17184 * Reverts user permission state changes (permissions and flags) in 17185 * all packages for a given user. 17186 * 17187 * @param userId The device user for which to do a reset. 17188 */ 17189 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 17190 final int packageCount = mPackages.size(); 17191 for (int i = 0; i < packageCount; i++) { 17192 PackageParser.Package pkg = mPackages.valueAt(i); 17193 PackageSetting ps = (PackageSetting) pkg.mExtras; 17194 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 17195 } 17196 } 17197 17198 private void resetNetworkPolicies(int userId) { 17199 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 17200 } 17201 17202 /** 17203 * Reverts user permission state changes (permissions and flags). 17204 * 17205 * @param ps The package for which to reset. 17206 * @param userId The device user for which to do a reset. 17207 */ 17208 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 17209 final PackageSetting ps, final int userId) { 17210 if (ps.pkg == null) { 17211 return; 17212 } 17213 17214 // These are flags that can change base on user actions. 17215 final int userSettableMask = FLAG_PERMISSION_USER_SET 17216 | FLAG_PERMISSION_USER_FIXED 17217 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 17218 | FLAG_PERMISSION_REVIEW_REQUIRED; 17219 17220 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 17221 | FLAG_PERMISSION_POLICY_FIXED; 17222 17223 boolean writeInstallPermissions = false; 17224 boolean writeRuntimePermissions = false; 17225 17226 final int permissionCount = ps.pkg.requestedPermissions.size(); 17227 for (int i = 0; i < permissionCount; i++) { 17228 String permission = ps.pkg.requestedPermissions.get(i); 17229 17230 BasePermission bp = mSettings.mPermissions.get(permission); 17231 if (bp == null) { 17232 continue; 17233 } 17234 17235 // If shared user we just reset the state to which only this app contributed. 17236 if (ps.sharedUser != null) { 17237 boolean used = false; 17238 final int packageCount = ps.sharedUser.packages.size(); 17239 for (int j = 0; j < packageCount; j++) { 17240 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 17241 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 17242 && pkg.pkg.requestedPermissions.contains(permission)) { 17243 used = true; 17244 break; 17245 } 17246 } 17247 if (used) { 17248 continue; 17249 } 17250 } 17251 17252 PermissionsState permissionsState = ps.getPermissionsState(); 17253 17254 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 17255 17256 // Always clear the user settable flags. 17257 final boolean hasInstallState = permissionsState.getInstallPermissionState( 17258 bp.name) != null; 17259 // If permission review is enabled and this is a legacy app, mark the 17260 // permission as requiring a review as this is the initial state. 17261 int flags = 0; 17262 if (mPermissionReviewRequired 17263 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 17264 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 17265 } 17266 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 17267 if (hasInstallState) { 17268 writeInstallPermissions = true; 17269 } else { 17270 writeRuntimePermissions = true; 17271 } 17272 } 17273 17274 // Below is only runtime permission handling. 17275 if (!bp.isRuntime()) { 17276 continue; 17277 } 17278 17279 // Never clobber system or policy. 17280 if ((oldFlags & policyOrSystemFlags) != 0) { 17281 continue; 17282 } 17283 17284 // If this permission was granted by default, make sure it is. 17285 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 17286 if (permissionsState.grantRuntimePermission(bp, userId) 17287 != PERMISSION_OPERATION_FAILURE) { 17288 writeRuntimePermissions = true; 17289 } 17290 // If permission review is enabled the permissions for a legacy apps 17291 // are represented as constantly granted runtime ones, so don't revoke. 17292 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 17293 // Otherwise, reset the permission. 17294 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 17295 switch (revokeResult) { 17296 case PERMISSION_OPERATION_SUCCESS: 17297 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 17298 writeRuntimePermissions = true; 17299 final int appId = ps.appId; 17300 mHandler.post(new Runnable() { 17301 @Override 17302 public void run() { 17303 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 17304 } 17305 }); 17306 } break; 17307 } 17308 } 17309 } 17310 17311 // Synchronously write as we are taking permissions away. 17312 if (writeRuntimePermissions) { 17313 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 17314 } 17315 17316 // Synchronously write as we are taking permissions away. 17317 if (writeInstallPermissions) { 17318 mSettings.writeLPr(); 17319 } 17320 } 17321 17322 /** 17323 * Remove entries from the keystore daemon. Will only remove it if the 17324 * {@code appId} is valid. 17325 */ 17326 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 17327 if (appId < 0) { 17328 return; 17329 } 17330 17331 final KeyStore keyStore = KeyStore.getInstance(); 17332 if (keyStore != null) { 17333 if (userId == UserHandle.USER_ALL) { 17334 for (final int individual : sUserManager.getUserIds()) { 17335 keyStore.clearUid(UserHandle.getUid(individual, appId)); 17336 } 17337 } else { 17338 keyStore.clearUid(UserHandle.getUid(userId, appId)); 17339 } 17340 } else { 17341 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 17342 } 17343 } 17344 17345 @Override 17346 public void deleteApplicationCacheFiles(final String packageName, 17347 final IPackageDataObserver observer) { 17348 final int userId = UserHandle.getCallingUserId(); 17349 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 17350 } 17351 17352 @Override 17353 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 17354 final IPackageDataObserver observer) { 17355 mContext.enforceCallingOrSelfPermission( 17356 android.Manifest.permission.DELETE_CACHE_FILES, null); 17357 enforceCrossUserPermission(Binder.getCallingUid(), userId, 17358 /* requireFullPermission= */ true, /* checkShell= */ false, 17359 "delete application cache files"); 17360 17361 final PackageParser.Package pkg; 17362 synchronized (mPackages) { 17363 pkg = mPackages.get(packageName); 17364 } 17365 17366 // Queue up an async operation since the package deletion may take a little while. 17367 mHandler.post(new Runnable() { 17368 public void run() { 17369 synchronized (mInstallLock) { 17370 final int flags = StorageManager.FLAG_STORAGE_DE 17371 | StorageManager.FLAG_STORAGE_CE; 17372 // We're only clearing cache files, so we don't care if the 17373 // app is unfrozen and still able to run 17374 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 17375 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 17376 } 17377 clearExternalStorageDataSync(packageName, userId, false); 17378 if (observer != null) { 17379 try { 17380 observer.onRemoveCompleted(packageName, true); 17381 } catch (RemoteException e) { 17382 Log.i(TAG, "Observer no longer exists."); 17383 } 17384 } 17385 } 17386 }); 17387 } 17388 17389 @Override 17390 public void getPackageSizeInfo(final String packageName, int userHandle, 17391 final IPackageStatsObserver observer) { 17392 mContext.enforceCallingOrSelfPermission( 17393 android.Manifest.permission.GET_PACKAGE_SIZE, null); 17394 if (packageName == null) { 17395 throw new IllegalArgumentException("Attempt to get size of null packageName"); 17396 } 17397 17398 PackageStats stats = new PackageStats(packageName, userHandle); 17399 17400 /* 17401 * Queue up an async operation since the package measurement may take a 17402 * little while. 17403 */ 17404 Message msg = mHandler.obtainMessage(INIT_COPY); 17405 msg.obj = new MeasureParams(stats, observer); 17406 mHandler.sendMessage(msg); 17407 } 17408 17409 private boolean equals(PackageStats a, PackageStats b) { 17410 return (a.codeSize == b.codeSize) && (a.dataSize == b.dataSize) 17411 && (a.cacheSize == b.cacheSize); 17412 } 17413 17414 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 17415 final PackageSetting ps; 17416 synchronized (mPackages) { 17417 ps = mSettings.mPackages.get(packageName); 17418 if (ps == null) { 17419 Slog.w(TAG, "Failed to find settings for " + packageName); 17420 return false; 17421 } 17422 } 17423 17424 final long ceDataInode = ps.getCeDataInode(userId); 17425 final PackageStats quotaStats = new PackageStats(stats.packageName, stats.userHandle); 17426 17427 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17428 final String externalUuid = storage.getPrimaryStorageUuid(); 17429 try { 17430 final long start = SystemClock.elapsedRealtimeNanos(); 17431 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 0, 17432 ps.appId, ceDataInode, ps.codePathString, externalUuid, stats); 17433 final long stopManual = SystemClock.elapsedRealtimeNanos(); 17434 if (ENABLE_QUOTA) { 17435 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, Installer.FLAG_USE_QUOTA, 17436 ps.appId, ceDataInode, ps.codePathString, externalUuid, quotaStats); 17437 } 17438 final long stopQuota = SystemClock.elapsedRealtimeNanos(); 17439 17440 // For now, ignore code size of packages on system partition 17441 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 17442 stats.codeSize = 0; 17443 quotaStats.codeSize = 0; 17444 } 17445 17446 if (ENABLE_QUOTA && Build.IS_ENG && !ps.isSharedUser()) { 17447 if (!equals(stats, quotaStats)) { 17448 Log.w(TAG, "Found discrepancy between statistics:"); 17449 Log.w(TAG, "Manual: " + stats); 17450 Log.w(TAG, "Quota: " + quotaStats); 17451 } 17452 final long manualTime = stopManual - start; 17453 final long quotaTime = stopQuota - stopManual; 17454 EventLogTags.writePmPackageStats(manualTime, quotaTime, 17455 stats.dataSize, quotaStats.dataSize, 17456 stats.cacheSize, quotaStats.cacheSize); 17457 } 17458 17459 // External clients expect these to be tracked separately 17460 stats.dataSize -= stats.cacheSize; 17461 quotaStats.dataSize -= quotaStats.cacheSize; 17462 17463 } catch (InstallerException e) { 17464 Slog.w(TAG, String.valueOf(e)); 17465 return false; 17466 } 17467 17468 return true; 17469 } 17470 17471 private int getUidTargetSdkVersionLockedLPr(int uid) { 17472 Object obj = mSettings.getUserIdLPr(uid); 17473 if (obj instanceof SharedUserSetting) { 17474 final SharedUserSetting sus = (SharedUserSetting) obj; 17475 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 17476 final Iterator<PackageSetting> it = sus.packages.iterator(); 17477 while (it.hasNext()) { 17478 final PackageSetting ps = it.next(); 17479 if (ps.pkg != null) { 17480 int v = ps.pkg.applicationInfo.targetSdkVersion; 17481 if (v < vers) vers = v; 17482 } 17483 } 17484 return vers; 17485 } else if (obj instanceof PackageSetting) { 17486 final PackageSetting ps = (PackageSetting) obj; 17487 if (ps.pkg != null) { 17488 return ps.pkg.applicationInfo.targetSdkVersion; 17489 } 17490 } 17491 return Build.VERSION_CODES.CUR_DEVELOPMENT; 17492 } 17493 17494 @Override 17495 public void addPreferredActivity(IntentFilter filter, int match, 17496 ComponentName[] set, ComponentName activity, int userId) { 17497 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17498 "Adding preferred"); 17499 } 17500 17501 private void addPreferredActivityInternal(IntentFilter filter, int match, 17502 ComponentName[] set, ComponentName activity, boolean always, int userId, 17503 String opname) { 17504 // writer 17505 int callingUid = Binder.getCallingUid(); 17506 enforceCrossUserPermission(callingUid, userId, 17507 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 17508 if (filter.countActions() == 0) { 17509 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17510 return; 17511 } 17512 synchronized (mPackages) { 17513 if (mContext.checkCallingOrSelfPermission( 17514 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17515 != PackageManager.PERMISSION_GRANTED) { 17516 if (getUidTargetSdkVersionLockedLPr(callingUid) 17517 < Build.VERSION_CODES.FROYO) { 17518 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 17519 + callingUid); 17520 return; 17521 } 17522 mContext.enforceCallingOrSelfPermission( 17523 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17524 } 17525 17526 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 17527 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 17528 + userId + ":"); 17529 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17530 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 17531 scheduleWritePackageRestrictionsLocked(userId); 17532 postPreferredActivityChangedBroadcast(userId); 17533 } 17534 } 17535 17536 private void postPreferredActivityChangedBroadcast(int userId) { 17537 mHandler.post(() -> { 17538 final IActivityManager am = ActivityManager.getService(); 17539 if (am == null) { 17540 return; 17541 } 17542 17543 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 17544 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17545 try { 17546 am.broadcastIntent(null, intent, null, null, 17547 0, null, null, null, android.app.AppOpsManager.OP_NONE, 17548 null, false, false, userId); 17549 } catch (RemoteException e) { 17550 } 17551 }); 17552 } 17553 17554 @Override 17555 public void replacePreferredActivity(IntentFilter filter, int match, 17556 ComponentName[] set, ComponentName activity, int userId) { 17557 if (filter.countActions() != 1) { 17558 throw new IllegalArgumentException( 17559 "replacePreferredActivity expects filter to have only 1 action."); 17560 } 17561 if (filter.countDataAuthorities() != 0 17562 || filter.countDataPaths() != 0 17563 || filter.countDataSchemes() > 1 17564 || filter.countDataTypes() != 0) { 17565 throw new IllegalArgumentException( 17566 "replacePreferredActivity expects filter to have no data authorities, " + 17567 "paths, or types; and at most one scheme."); 17568 } 17569 17570 final int callingUid = Binder.getCallingUid(); 17571 enforceCrossUserPermission(callingUid, userId, 17572 true /* requireFullPermission */, false /* checkShell */, 17573 "replace preferred activity"); 17574 synchronized (mPackages) { 17575 if (mContext.checkCallingOrSelfPermission( 17576 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17577 != PackageManager.PERMISSION_GRANTED) { 17578 if (getUidTargetSdkVersionLockedLPr(callingUid) 17579 < Build.VERSION_CODES.FROYO) { 17580 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 17581 + Binder.getCallingUid()); 17582 return; 17583 } 17584 mContext.enforceCallingOrSelfPermission( 17585 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17586 } 17587 17588 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17589 if (pir != null) { 17590 // Get all of the existing entries that exactly match this filter. 17591 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 17592 if (existing != null && existing.size() == 1) { 17593 PreferredActivity cur = existing.get(0); 17594 if (DEBUG_PREFERRED) { 17595 Slog.i(TAG, "Checking replace of preferred:"); 17596 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17597 if (!cur.mPref.mAlways) { 17598 Slog.i(TAG, " -- CUR; not mAlways!"); 17599 } else { 17600 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 17601 Slog.i(TAG, " -- CUR: mSet=" 17602 + Arrays.toString(cur.mPref.mSetComponents)); 17603 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 17604 Slog.i(TAG, " -- NEW: mMatch=" 17605 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 17606 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17607 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17608 } 17609 } 17610 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17611 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17612 && cur.mPref.sameSet(set)) { 17613 // Setting the preferred activity to what it happens to be already 17614 if (DEBUG_PREFERRED) { 17615 Slog.i(TAG, "Replacing with same preferred activity " 17616 + cur.mPref.mShortComponent + " for user " 17617 + userId + ":"); 17618 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17619 } 17620 return; 17621 } 17622 } 17623 17624 if (existing != null) { 17625 if (DEBUG_PREFERRED) { 17626 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17627 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17628 } 17629 for (int i = 0; i < existing.size(); i++) { 17630 PreferredActivity pa = existing.get(i); 17631 if (DEBUG_PREFERRED) { 17632 Slog.i(TAG, "Removing existing preferred activity " 17633 + pa.mPref.mComponent + ":"); 17634 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17635 } 17636 pir.removeFilter(pa); 17637 } 17638 } 17639 } 17640 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17641 "Replacing preferred"); 17642 } 17643 } 17644 17645 @Override 17646 public void clearPackagePreferredActivities(String packageName) { 17647 final int uid = Binder.getCallingUid(); 17648 // writer 17649 synchronized (mPackages) { 17650 PackageParser.Package pkg = mPackages.get(packageName); 17651 if (pkg == null || pkg.applicationInfo.uid != uid) { 17652 if (mContext.checkCallingOrSelfPermission( 17653 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17654 != PackageManager.PERMISSION_GRANTED) { 17655 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17656 < Build.VERSION_CODES.FROYO) { 17657 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17658 + Binder.getCallingUid()); 17659 return; 17660 } 17661 mContext.enforceCallingOrSelfPermission( 17662 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17663 } 17664 } 17665 17666 int user = UserHandle.getCallingUserId(); 17667 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17668 scheduleWritePackageRestrictionsLocked(user); 17669 } 17670 } 17671 } 17672 17673 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17674 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17675 ArrayList<PreferredActivity> removed = null; 17676 boolean changed = false; 17677 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17678 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17679 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17680 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17681 continue; 17682 } 17683 Iterator<PreferredActivity> it = pir.filterIterator(); 17684 while (it.hasNext()) { 17685 PreferredActivity pa = it.next(); 17686 // Mark entry for removal only if it matches the package name 17687 // and the entry is of type "always". 17688 if (packageName == null || 17689 (pa.mPref.mComponent.getPackageName().equals(packageName) 17690 && pa.mPref.mAlways)) { 17691 if (removed == null) { 17692 removed = new ArrayList<PreferredActivity>(); 17693 } 17694 removed.add(pa); 17695 } 17696 } 17697 if (removed != null) { 17698 for (int j=0; j<removed.size(); j++) { 17699 PreferredActivity pa = removed.get(j); 17700 pir.removeFilter(pa); 17701 } 17702 changed = true; 17703 } 17704 } 17705 if (changed) { 17706 postPreferredActivityChangedBroadcast(userId); 17707 } 17708 return changed; 17709 } 17710 17711 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17712 private void clearIntentFilterVerificationsLPw(int userId) { 17713 final int packageCount = mPackages.size(); 17714 for (int i = 0; i < packageCount; i++) { 17715 PackageParser.Package pkg = mPackages.valueAt(i); 17716 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17717 } 17718 } 17719 17720 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17721 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17722 if (userId == UserHandle.USER_ALL) { 17723 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17724 sUserManager.getUserIds())) { 17725 for (int oneUserId : sUserManager.getUserIds()) { 17726 scheduleWritePackageRestrictionsLocked(oneUserId); 17727 } 17728 } 17729 } else { 17730 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17731 scheduleWritePackageRestrictionsLocked(userId); 17732 } 17733 } 17734 } 17735 17736 void clearDefaultBrowserIfNeeded(String packageName) { 17737 for (int oneUserId : sUserManager.getUserIds()) { 17738 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17739 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17740 if (packageName.equals(defaultBrowserPackageName)) { 17741 setDefaultBrowserPackageName(null, oneUserId); 17742 } 17743 } 17744 } 17745 17746 @Override 17747 public void resetApplicationPreferences(int userId) { 17748 mContext.enforceCallingOrSelfPermission( 17749 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17750 final long identity = Binder.clearCallingIdentity(); 17751 // writer 17752 try { 17753 synchronized (mPackages) { 17754 clearPackagePreferredActivitiesLPw(null, userId); 17755 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17756 // TODO: We have to reset the default SMS and Phone. This requires 17757 // significant refactoring to keep all default apps in the package 17758 // manager (cleaner but more work) or have the services provide 17759 // callbacks to the package manager to request a default app reset. 17760 applyFactoryDefaultBrowserLPw(userId); 17761 clearIntentFilterVerificationsLPw(userId); 17762 primeDomainVerificationsLPw(userId); 17763 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17764 scheduleWritePackageRestrictionsLocked(userId); 17765 } 17766 resetNetworkPolicies(userId); 17767 } finally { 17768 Binder.restoreCallingIdentity(identity); 17769 } 17770 } 17771 17772 @Override 17773 public int getPreferredActivities(List<IntentFilter> outFilters, 17774 List<ComponentName> outActivities, String packageName) { 17775 17776 int num = 0; 17777 final int userId = UserHandle.getCallingUserId(); 17778 // reader 17779 synchronized (mPackages) { 17780 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17781 if (pir != null) { 17782 final Iterator<PreferredActivity> it = pir.filterIterator(); 17783 while (it.hasNext()) { 17784 final PreferredActivity pa = it.next(); 17785 if (packageName == null 17786 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17787 && pa.mPref.mAlways)) { 17788 if (outFilters != null) { 17789 outFilters.add(new IntentFilter(pa)); 17790 } 17791 if (outActivities != null) { 17792 outActivities.add(pa.mPref.mComponent); 17793 } 17794 } 17795 } 17796 } 17797 } 17798 17799 return num; 17800 } 17801 17802 @Override 17803 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17804 int userId) { 17805 int callingUid = Binder.getCallingUid(); 17806 if (callingUid != Process.SYSTEM_UID) { 17807 throw new SecurityException( 17808 "addPersistentPreferredActivity can only be run by the system"); 17809 } 17810 if (filter.countActions() == 0) { 17811 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17812 return; 17813 } 17814 synchronized (mPackages) { 17815 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17816 ":"); 17817 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17818 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17819 new PersistentPreferredActivity(filter, activity)); 17820 scheduleWritePackageRestrictionsLocked(userId); 17821 postPreferredActivityChangedBroadcast(userId); 17822 } 17823 } 17824 17825 @Override 17826 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17827 int callingUid = Binder.getCallingUid(); 17828 if (callingUid != Process.SYSTEM_UID) { 17829 throw new SecurityException( 17830 "clearPackagePersistentPreferredActivities can only be run by the system"); 17831 } 17832 ArrayList<PersistentPreferredActivity> removed = null; 17833 boolean changed = false; 17834 synchronized (mPackages) { 17835 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17836 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17837 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17838 .valueAt(i); 17839 if (userId != thisUserId) { 17840 continue; 17841 } 17842 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17843 while (it.hasNext()) { 17844 PersistentPreferredActivity ppa = it.next(); 17845 // Mark entry for removal only if it matches the package name. 17846 if (ppa.mComponent.getPackageName().equals(packageName)) { 17847 if (removed == null) { 17848 removed = new ArrayList<PersistentPreferredActivity>(); 17849 } 17850 removed.add(ppa); 17851 } 17852 } 17853 if (removed != null) { 17854 for (int j=0; j<removed.size(); j++) { 17855 PersistentPreferredActivity ppa = removed.get(j); 17856 ppir.removeFilter(ppa); 17857 } 17858 changed = true; 17859 } 17860 } 17861 17862 if (changed) { 17863 scheduleWritePackageRestrictionsLocked(userId); 17864 postPreferredActivityChangedBroadcast(userId); 17865 } 17866 } 17867 } 17868 17869 /** 17870 * Common machinery for picking apart a restored XML blob and passing 17871 * it to a caller-supplied functor to be applied to the running system. 17872 */ 17873 private void restoreFromXml(XmlPullParser parser, int userId, 17874 String expectedStartTag, BlobXmlRestorer functor) 17875 throws IOException, XmlPullParserException { 17876 int type; 17877 while ((type = parser.next()) != XmlPullParser.START_TAG 17878 && type != XmlPullParser.END_DOCUMENT) { 17879 } 17880 if (type != XmlPullParser.START_TAG) { 17881 // oops didn't find a start tag?! 17882 if (DEBUG_BACKUP) { 17883 Slog.e(TAG, "Didn't find start tag during restore"); 17884 } 17885 return; 17886 } 17887Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17888 // this is supposed to be TAG_PREFERRED_BACKUP 17889 if (!expectedStartTag.equals(parser.getName())) { 17890 if (DEBUG_BACKUP) { 17891 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17892 } 17893 return; 17894 } 17895 17896 // skip interfering stuff, then we're aligned with the backing implementation 17897 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17898Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17899 functor.apply(parser, userId); 17900 } 17901 17902 private interface BlobXmlRestorer { 17903 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17904 } 17905 17906 /** 17907 * Non-Binder method, support for the backup/restore mechanism: write the 17908 * full set of preferred activities in its canonical XML format. Returns the 17909 * XML output as a byte array, or null if there is none. 17910 */ 17911 @Override 17912 public byte[] getPreferredActivityBackup(int userId) { 17913 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17914 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17915 } 17916 17917 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17918 try { 17919 final XmlSerializer serializer = new FastXmlSerializer(); 17920 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17921 serializer.startDocument(null, true); 17922 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17923 17924 synchronized (mPackages) { 17925 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17926 } 17927 17928 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17929 serializer.endDocument(); 17930 serializer.flush(); 17931 } catch (Exception e) { 17932 if (DEBUG_BACKUP) { 17933 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17934 } 17935 return null; 17936 } 17937 17938 return dataStream.toByteArray(); 17939 } 17940 17941 @Override 17942 public void restorePreferredActivities(byte[] backup, int userId) { 17943 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17944 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17945 } 17946 17947 try { 17948 final XmlPullParser parser = Xml.newPullParser(); 17949 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17950 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17951 new BlobXmlRestorer() { 17952 @Override 17953 public void apply(XmlPullParser parser, int userId) 17954 throws XmlPullParserException, IOException { 17955 synchronized (mPackages) { 17956 mSettings.readPreferredActivitiesLPw(parser, userId); 17957 } 17958 } 17959 } ); 17960 } catch (Exception e) { 17961 if (DEBUG_BACKUP) { 17962 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17963 } 17964 } 17965 } 17966 17967 /** 17968 * Non-Binder method, support for the backup/restore mechanism: write the 17969 * default browser (etc) settings in its canonical XML format. Returns the default 17970 * browser XML representation as a byte array, or null if there is none. 17971 */ 17972 @Override 17973 public byte[] getDefaultAppsBackup(int userId) { 17974 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17975 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17976 } 17977 17978 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17979 try { 17980 final XmlSerializer serializer = new FastXmlSerializer(); 17981 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17982 serializer.startDocument(null, true); 17983 serializer.startTag(null, TAG_DEFAULT_APPS); 17984 17985 synchronized (mPackages) { 17986 mSettings.writeDefaultAppsLPr(serializer, userId); 17987 } 17988 17989 serializer.endTag(null, TAG_DEFAULT_APPS); 17990 serializer.endDocument(); 17991 serializer.flush(); 17992 } catch (Exception e) { 17993 if (DEBUG_BACKUP) { 17994 Slog.e(TAG, "Unable to write default apps for backup", e); 17995 } 17996 return null; 17997 } 17998 17999 return dataStream.toByteArray(); 18000 } 18001 18002 @Override 18003 public void restoreDefaultApps(byte[] backup, int userId) { 18004 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18005 throw new SecurityException("Only the system may call restoreDefaultApps()"); 18006 } 18007 18008 try { 18009 final XmlPullParser parser = Xml.newPullParser(); 18010 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18011 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 18012 new BlobXmlRestorer() { 18013 @Override 18014 public void apply(XmlPullParser parser, int userId) 18015 throws XmlPullParserException, IOException { 18016 synchronized (mPackages) { 18017 mSettings.readDefaultAppsLPw(parser, userId); 18018 } 18019 } 18020 } ); 18021 } catch (Exception e) { 18022 if (DEBUG_BACKUP) { 18023 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 18024 } 18025 } 18026 } 18027 18028 @Override 18029 public byte[] getIntentFilterVerificationBackup(int userId) { 18030 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18031 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 18032 } 18033 18034 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 18035 try { 18036 final XmlSerializer serializer = new FastXmlSerializer(); 18037 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 18038 serializer.startDocument(null, true); 18039 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 18040 18041 synchronized (mPackages) { 18042 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 18043 } 18044 18045 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 18046 serializer.endDocument(); 18047 serializer.flush(); 18048 } catch (Exception e) { 18049 if (DEBUG_BACKUP) { 18050 Slog.e(TAG, "Unable to write default apps for backup", e); 18051 } 18052 return null; 18053 } 18054 18055 return dataStream.toByteArray(); 18056 } 18057 18058 @Override 18059 public void restoreIntentFilterVerification(byte[] backup, int userId) { 18060 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18061 throw new SecurityException("Only the system may call restorePreferredActivities()"); 18062 } 18063 18064 try { 18065 final XmlPullParser parser = Xml.newPullParser(); 18066 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18067 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 18068 new BlobXmlRestorer() { 18069 @Override 18070 public void apply(XmlPullParser parser, int userId) 18071 throws XmlPullParserException, IOException { 18072 synchronized (mPackages) { 18073 mSettings.readAllDomainVerificationsLPr(parser, userId); 18074 mSettings.writeLPr(); 18075 } 18076 } 18077 } ); 18078 } catch (Exception e) { 18079 if (DEBUG_BACKUP) { 18080 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 18081 } 18082 } 18083 } 18084 18085 @Override 18086 public byte[] getPermissionGrantBackup(int userId) { 18087 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18088 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 18089 } 18090 18091 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 18092 try { 18093 final XmlSerializer serializer = new FastXmlSerializer(); 18094 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 18095 serializer.startDocument(null, true); 18096 serializer.startTag(null, TAG_PERMISSION_BACKUP); 18097 18098 synchronized (mPackages) { 18099 serializeRuntimePermissionGrantsLPr(serializer, userId); 18100 } 18101 18102 serializer.endTag(null, TAG_PERMISSION_BACKUP); 18103 serializer.endDocument(); 18104 serializer.flush(); 18105 } catch (Exception e) { 18106 if (DEBUG_BACKUP) { 18107 Slog.e(TAG, "Unable to write default apps for backup", e); 18108 } 18109 return null; 18110 } 18111 18112 return dataStream.toByteArray(); 18113 } 18114 18115 @Override 18116 public void restorePermissionGrants(byte[] backup, int userId) { 18117 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18118 throw new SecurityException("Only the system may call restorePermissionGrants()"); 18119 } 18120 18121 try { 18122 final XmlPullParser parser = Xml.newPullParser(); 18123 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18124 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 18125 new BlobXmlRestorer() { 18126 @Override 18127 public void apply(XmlPullParser parser, int userId) 18128 throws XmlPullParserException, IOException { 18129 synchronized (mPackages) { 18130 processRestoredPermissionGrantsLPr(parser, userId); 18131 } 18132 } 18133 } ); 18134 } catch (Exception e) { 18135 if (DEBUG_BACKUP) { 18136 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 18137 } 18138 } 18139 } 18140 18141 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 18142 throws IOException { 18143 serializer.startTag(null, TAG_ALL_GRANTS); 18144 18145 final int N = mSettings.mPackages.size(); 18146 for (int i = 0; i < N; i++) { 18147 final PackageSetting ps = mSettings.mPackages.valueAt(i); 18148 boolean pkgGrantsKnown = false; 18149 18150 PermissionsState packagePerms = ps.getPermissionsState(); 18151 18152 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 18153 final int grantFlags = state.getFlags(); 18154 // only look at grants that are not system/policy fixed 18155 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 18156 final boolean isGranted = state.isGranted(); 18157 // And only back up the user-twiddled state bits 18158 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 18159 final String packageName = mSettings.mPackages.keyAt(i); 18160 if (!pkgGrantsKnown) { 18161 serializer.startTag(null, TAG_GRANT); 18162 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 18163 pkgGrantsKnown = true; 18164 } 18165 18166 final boolean userSet = 18167 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 18168 final boolean userFixed = 18169 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 18170 final boolean revoke = 18171 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 18172 18173 serializer.startTag(null, TAG_PERMISSION); 18174 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 18175 if (isGranted) { 18176 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 18177 } 18178 if (userSet) { 18179 serializer.attribute(null, ATTR_USER_SET, "true"); 18180 } 18181 if (userFixed) { 18182 serializer.attribute(null, ATTR_USER_FIXED, "true"); 18183 } 18184 if (revoke) { 18185 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 18186 } 18187 serializer.endTag(null, TAG_PERMISSION); 18188 } 18189 } 18190 } 18191 18192 if (pkgGrantsKnown) { 18193 serializer.endTag(null, TAG_GRANT); 18194 } 18195 } 18196 18197 serializer.endTag(null, TAG_ALL_GRANTS); 18198 } 18199 18200 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 18201 throws XmlPullParserException, IOException { 18202 String pkgName = null; 18203 int outerDepth = parser.getDepth(); 18204 int type; 18205 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 18206 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 18207 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 18208 continue; 18209 } 18210 18211 final String tagName = parser.getName(); 18212 if (tagName.equals(TAG_GRANT)) { 18213 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 18214 if (DEBUG_BACKUP) { 18215 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 18216 } 18217 } else if (tagName.equals(TAG_PERMISSION)) { 18218 18219 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 18220 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 18221 18222 int newFlagSet = 0; 18223 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 18224 newFlagSet |= FLAG_PERMISSION_USER_SET; 18225 } 18226 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 18227 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 18228 } 18229 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 18230 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 18231 } 18232 if (DEBUG_BACKUP) { 18233 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 18234 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 18235 } 18236 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18237 if (ps != null) { 18238 // Already installed so we apply the grant immediately 18239 if (DEBUG_BACKUP) { 18240 Slog.v(TAG, " + already installed; applying"); 18241 } 18242 PermissionsState perms = ps.getPermissionsState(); 18243 BasePermission bp = mSettings.mPermissions.get(permName); 18244 if (bp != null) { 18245 if (isGranted) { 18246 perms.grantRuntimePermission(bp, userId); 18247 } 18248 if (newFlagSet != 0) { 18249 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 18250 } 18251 } 18252 } else { 18253 // Need to wait for post-restore install to apply the grant 18254 if (DEBUG_BACKUP) { 18255 Slog.v(TAG, " - not yet installed; saving for later"); 18256 } 18257 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 18258 isGranted, newFlagSet, userId); 18259 } 18260 } else { 18261 PackageManagerService.reportSettingsProblem(Log.WARN, 18262 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 18263 XmlUtils.skipCurrentTag(parser); 18264 } 18265 } 18266 18267 scheduleWriteSettingsLocked(); 18268 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18269 } 18270 18271 @Override 18272 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 18273 int sourceUserId, int targetUserId, int flags) { 18274 mContext.enforceCallingOrSelfPermission( 18275 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 18276 int callingUid = Binder.getCallingUid(); 18277 enforceOwnerRights(ownerPackage, callingUid); 18278 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 18279 if (intentFilter.countActions() == 0) { 18280 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 18281 return; 18282 } 18283 synchronized (mPackages) { 18284 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 18285 ownerPackage, targetUserId, flags); 18286 CrossProfileIntentResolver resolver = 18287 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 18288 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 18289 // We have all those whose filter is equal. Now checking if the rest is equal as well. 18290 if (existing != null) { 18291 int size = existing.size(); 18292 for (int i = 0; i < size; i++) { 18293 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 18294 return; 18295 } 18296 } 18297 } 18298 resolver.addFilter(newFilter); 18299 scheduleWritePackageRestrictionsLocked(sourceUserId); 18300 } 18301 } 18302 18303 @Override 18304 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 18305 mContext.enforceCallingOrSelfPermission( 18306 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 18307 int callingUid = Binder.getCallingUid(); 18308 enforceOwnerRights(ownerPackage, callingUid); 18309 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 18310 synchronized (mPackages) { 18311 CrossProfileIntentResolver resolver = 18312 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 18313 ArraySet<CrossProfileIntentFilter> set = 18314 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 18315 for (CrossProfileIntentFilter filter : set) { 18316 if (filter.getOwnerPackage().equals(ownerPackage)) { 18317 resolver.removeFilter(filter); 18318 } 18319 } 18320 scheduleWritePackageRestrictionsLocked(sourceUserId); 18321 } 18322 } 18323 18324 // Enforcing that callingUid is owning pkg on userId 18325 private void enforceOwnerRights(String pkg, int callingUid) { 18326 // The system owns everything. 18327 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 18328 return; 18329 } 18330 int callingUserId = UserHandle.getUserId(callingUid); 18331 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 18332 if (pi == null) { 18333 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 18334 + callingUserId); 18335 } 18336 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 18337 throw new SecurityException("Calling uid " + callingUid 18338 + " does not own package " + pkg); 18339 } 18340 } 18341 18342 @Override 18343 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 18344 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 18345 } 18346 18347 private Intent getHomeIntent() { 18348 Intent intent = new Intent(Intent.ACTION_MAIN); 18349 intent.addCategory(Intent.CATEGORY_HOME); 18350 intent.addCategory(Intent.CATEGORY_DEFAULT); 18351 return intent; 18352 } 18353 18354 private IntentFilter getHomeFilter() { 18355 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 18356 filter.addCategory(Intent.CATEGORY_HOME); 18357 filter.addCategory(Intent.CATEGORY_DEFAULT); 18358 return filter; 18359 } 18360 18361 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 18362 int userId) { 18363 Intent intent = getHomeIntent(); 18364 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 18365 PackageManager.GET_META_DATA, userId); 18366 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 18367 true, false, false, userId); 18368 18369 allHomeCandidates.clear(); 18370 if (list != null) { 18371 for (ResolveInfo ri : list) { 18372 allHomeCandidates.add(ri); 18373 } 18374 } 18375 return (preferred == null || preferred.activityInfo == null) 18376 ? null 18377 : new ComponentName(preferred.activityInfo.packageName, 18378 preferred.activityInfo.name); 18379 } 18380 18381 @Override 18382 public void setHomeActivity(ComponentName comp, int userId) { 18383 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 18384 getHomeActivitiesAsUser(homeActivities, userId); 18385 18386 boolean found = false; 18387 18388 final int size = homeActivities.size(); 18389 final ComponentName[] set = new ComponentName[size]; 18390 for (int i = 0; i < size; i++) { 18391 final ResolveInfo candidate = homeActivities.get(i); 18392 final ActivityInfo info = candidate.activityInfo; 18393 final ComponentName activityName = new ComponentName(info.packageName, info.name); 18394 set[i] = activityName; 18395 if (!found && activityName.equals(comp)) { 18396 found = true; 18397 } 18398 } 18399 if (!found) { 18400 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 18401 + userId); 18402 } 18403 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 18404 set, comp, userId); 18405 } 18406 18407 private @Nullable String getSetupWizardPackageName() { 18408 final Intent intent = new Intent(Intent.ACTION_MAIN); 18409 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 18410 18411 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18412 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18413 | MATCH_DISABLED_COMPONENTS, 18414 UserHandle.myUserId()); 18415 if (matches.size() == 1) { 18416 return matches.get(0).getComponentInfo().packageName; 18417 } else { 18418 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 18419 + ": matches=" + matches); 18420 return null; 18421 } 18422 } 18423 18424 private @Nullable String getStorageManagerPackageName() { 18425 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 18426 18427 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18428 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18429 | MATCH_DISABLED_COMPONENTS, 18430 UserHandle.myUserId()); 18431 if (matches.size() == 1) { 18432 return matches.get(0).getComponentInfo().packageName; 18433 } else { 18434 Slog.e(TAG, "There should probably be exactly one storage manager; found " 18435 + matches.size() + ": matches=" + matches); 18436 return null; 18437 } 18438 } 18439 18440 @Override 18441 public void setApplicationEnabledSetting(String appPackageName, 18442 int newState, int flags, int userId, String callingPackage) { 18443 if (!sUserManager.exists(userId)) return; 18444 if (callingPackage == null) { 18445 callingPackage = Integer.toString(Binder.getCallingUid()); 18446 } 18447 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 18448 } 18449 18450 @Override 18451 public void setComponentEnabledSetting(ComponentName componentName, 18452 int newState, int flags, int userId) { 18453 if (!sUserManager.exists(userId)) return; 18454 setEnabledSetting(componentName.getPackageName(), 18455 componentName.getClassName(), newState, flags, userId, null); 18456 } 18457 18458 private void setEnabledSetting(final String packageName, String className, int newState, 18459 final int flags, int userId, String callingPackage) { 18460 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 18461 || newState == COMPONENT_ENABLED_STATE_ENABLED 18462 || newState == COMPONENT_ENABLED_STATE_DISABLED 18463 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18464 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 18465 throw new IllegalArgumentException("Invalid new component state: " 18466 + newState); 18467 } 18468 PackageSetting pkgSetting; 18469 final int uid = Binder.getCallingUid(); 18470 final int permission; 18471 if (uid == Process.SYSTEM_UID) { 18472 permission = PackageManager.PERMISSION_GRANTED; 18473 } else { 18474 permission = mContext.checkCallingOrSelfPermission( 18475 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18476 } 18477 enforceCrossUserPermission(uid, userId, 18478 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 18479 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18480 boolean sendNow = false; 18481 boolean isApp = (className == null); 18482 String componentName = isApp ? packageName : className; 18483 int packageUid = -1; 18484 ArrayList<String> components; 18485 18486 // writer 18487 synchronized (mPackages) { 18488 pkgSetting = mSettings.mPackages.get(packageName); 18489 if (pkgSetting == null) { 18490 if (className == null) { 18491 throw new IllegalArgumentException("Unknown package: " + packageName); 18492 } 18493 throw new IllegalArgumentException( 18494 "Unknown component: " + packageName + "/" + className); 18495 } 18496 } 18497 18498 // Limit who can change which apps 18499 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 18500 // Don't allow apps that don't have permission to modify other apps 18501 if (!allowedByPermission) { 18502 throw new SecurityException( 18503 "Permission Denial: attempt to change component state from pid=" 18504 + Binder.getCallingPid() 18505 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 18506 } 18507 // Don't allow changing protected packages. 18508 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 18509 throw new SecurityException("Cannot disable a protected package: " + packageName); 18510 } 18511 } 18512 18513 synchronized (mPackages) { 18514 if (uid == Process.SHELL_UID 18515 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 18516 // Shell can only change whole packages between ENABLED and DISABLED_USER states 18517 // unless it is a test package. 18518 int oldState = pkgSetting.getEnabled(userId); 18519 if (className == null 18520 && 18521 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 18522 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 18523 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 18524 && 18525 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18526 || newState == COMPONENT_ENABLED_STATE_DEFAULT 18527 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 18528 // ok 18529 } else { 18530 throw new SecurityException( 18531 "Shell cannot change component state for " + packageName + "/" 18532 + className + " to " + newState); 18533 } 18534 } 18535 if (className == null) { 18536 // We're dealing with an application/package level state change 18537 if (pkgSetting.getEnabled(userId) == newState) { 18538 // Nothing to do 18539 return; 18540 } 18541 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 18542 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 18543 // Don't care about who enables an app. 18544 callingPackage = null; 18545 } 18546 pkgSetting.setEnabled(newState, userId, callingPackage); 18547 // pkgSetting.pkg.mSetEnabled = newState; 18548 } else { 18549 // We're dealing with a component level state change 18550 // First, verify that this is a valid class name. 18551 PackageParser.Package pkg = pkgSetting.pkg; 18552 if (pkg == null || !pkg.hasComponentClassName(className)) { 18553 if (pkg != null && 18554 pkg.applicationInfo.targetSdkVersion >= 18555 Build.VERSION_CODES.JELLY_BEAN) { 18556 throw new IllegalArgumentException("Component class " + className 18557 + " does not exist in " + packageName); 18558 } else { 18559 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 18560 + className + " does not exist in " + packageName); 18561 } 18562 } 18563 switch (newState) { 18564 case COMPONENT_ENABLED_STATE_ENABLED: 18565 if (!pkgSetting.enableComponentLPw(className, userId)) { 18566 return; 18567 } 18568 break; 18569 case COMPONENT_ENABLED_STATE_DISABLED: 18570 if (!pkgSetting.disableComponentLPw(className, userId)) { 18571 return; 18572 } 18573 break; 18574 case COMPONENT_ENABLED_STATE_DEFAULT: 18575 if (!pkgSetting.restoreComponentLPw(className, userId)) { 18576 return; 18577 } 18578 break; 18579 default: 18580 Slog.e(TAG, "Invalid new component state: " + newState); 18581 return; 18582 } 18583 } 18584 scheduleWritePackageRestrictionsLocked(userId); 18585 components = mPendingBroadcasts.get(userId, packageName); 18586 final boolean newPackage = components == null; 18587 if (newPackage) { 18588 components = new ArrayList<String>(); 18589 } 18590 if (!components.contains(componentName)) { 18591 components.add(componentName); 18592 } 18593 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 18594 sendNow = true; 18595 // Purge entry from pending broadcast list if another one exists already 18596 // since we are sending one right away. 18597 mPendingBroadcasts.remove(userId, packageName); 18598 } else { 18599 if (newPackage) { 18600 mPendingBroadcasts.put(userId, packageName, components); 18601 } 18602 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 18603 // Schedule a message 18604 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 18605 } 18606 } 18607 } 18608 18609 long callingId = Binder.clearCallingIdentity(); 18610 try { 18611 if (sendNow) { 18612 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18613 sendPackageChangedBroadcast(packageName, 18614 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18615 } 18616 } finally { 18617 Binder.restoreCallingIdentity(callingId); 18618 } 18619 } 18620 18621 @Override 18622 public void flushPackageRestrictionsAsUser(int userId) { 18623 if (!sUserManager.exists(userId)) { 18624 return; 18625 } 18626 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18627 false /* checkShell */, "flushPackageRestrictions"); 18628 synchronized (mPackages) { 18629 mSettings.writePackageRestrictionsLPr(userId); 18630 mDirtyUsers.remove(userId); 18631 if (mDirtyUsers.isEmpty()) { 18632 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18633 } 18634 } 18635 } 18636 18637 private void sendPackageChangedBroadcast(String packageName, 18638 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18639 if (DEBUG_INSTALL) 18640 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18641 + componentNames); 18642 Bundle extras = new Bundle(4); 18643 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18644 String nameList[] = new String[componentNames.size()]; 18645 componentNames.toArray(nameList); 18646 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18647 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18648 extras.putInt(Intent.EXTRA_UID, packageUid); 18649 // If this is not reporting a change of the overall package, then only send it 18650 // to registered receivers. We don't want to launch a swath of apps for every 18651 // little component state change. 18652 final int flags = !componentNames.contains(packageName) 18653 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18654 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18655 new int[] {UserHandle.getUserId(packageUid)}); 18656 } 18657 18658 @Override 18659 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18660 if (!sUserManager.exists(userId)) return; 18661 final int uid = Binder.getCallingUid(); 18662 final int permission = mContext.checkCallingOrSelfPermission( 18663 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18664 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18665 enforceCrossUserPermission(uid, userId, 18666 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18667 // writer 18668 synchronized (mPackages) { 18669 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18670 allowedByPermission, uid, userId)) { 18671 scheduleWritePackageRestrictionsLocked(userId); 18672 } 18673 } 18674 } 18675 18676 @Override 18677 public String getInstallerPackageName(String packageName) { 18678 // reader 18679 synchronized (mPackages) { 18680 return mSettings.getInstallerPackageNameLPr(packageName); 18681 } 18682 } 18683 18684 public boolean isOrphaned(String packageName) { 18685 // reader 18686 synchronized (mPackages) { 18687 return mSettings.isOrphaned(packageName); 18688 } 18689 } 18690 18691 @Override 18692 public int getApplicationEnabledSetting(String packageName, int userId) { 18693 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18694 int uid = Binder.getCallingUid(); 18695 enforceCrossUserPermission(uid, userId, 18696 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18697 // reader 18698 synchronized (mPackages) { 18699 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18700 } 18701 } 18702 18703 @Override 18704 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18705 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18706 int uid = Binder.getCallingUid(); 18707 enforceCrossUserPermission(uid, userId, 18708 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18709 // reader 18710 synchronized (mPackages) { 18711 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18712 } 18713 } 18714 18715 @Override 18716 public void enterSafeMode() { 18717 enforceSystemOrRoot("Only the system can request entering safe mode"); 18718 18719 if (!mSystemReady) { 18720 mSafeMode = true; 18721 } 18722 } 18723 18724 @Override 18725 public void systemReady() { 18726 mSystemReady = true; 18727 18728 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18729 // disabled after already being started. 18730 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18731 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18732 18733 // Read the compatibilty setting when the system is ready. 18734 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18735 mContext.getContentResolver(), 18736 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18737 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18738 if (DEBUG_SETTINGS) { 18739 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18740 } 18741 18742 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18743 18744 synchronized (mPackages) { 18745 // Verify that all of the preferred activity components actually 18746 // exist. It is possible for applications to be updated and at 18747 // that point remove a previously declared activity component that 18748 // had been set as a preferred activity. We try to clean this up 18749 // the next time we encounter that preferred activity, but it is 18750 // possible for the user flow to never be able to return to that 18751 // situation so here we do a sanity check to make sure we haven't 18752 // left any junk around. 18753 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18754 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18755 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18756 removed.clear(); 18757 for (PreferredActivity pa : pir.filterSet()) { 18758 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18759 removed.add(pa); 18760 } 18761 } 18762 if (removed.size() > 0) { 18763 for (int r=0; r<removed.size(); r++) { 18764 PreferredActivity pa = removed.get(r); 18765 Slog.w(TAG, "Removing dangling preferred activity: " 18766 + pa.mPref.mComponent); 18767 pir.removeFilter(pa); 18768 } 18769 mSettings.writePackageRestrictionsLPr( 18770 mSettings.mPreferredActivities.keyAt(i)); 18771 } 18772 } 18773 18774 for (int userId : UserManagerService.getInstance().getUserIds()) { 18775 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18776 grantPermissionsUserIds = ArrayUtils.appendInt( 18777 grantPermissionsUserIds, userId); 18778 } 18779 } 18780 } 18781 sUserManager.systemReady(); 18782 18783 // If we upgraded grant all default permissions before kicking off. 18784 for (int userId : grantPermissionsUserIds) { 18785 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18786 } 18787 18788 // If we did not grant default permissions, we preload from this the 18789 // default permission exceptions lazily to ensure we don't hit the 18790 // disk on a new user creation. 18791 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18792 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18793 } 18794 18795 // Kick off any messages waiting for system ready 18796 if (mPostSystemReadyMessages != null) { 18797 for (Message msg : mPostSystemReadyMessages) { 18798 msg.sendToTarget(); 18799 } 18800 mPostSystemReadyMessages = null; 18801 } 18802 18803 // Watch for external volumes that come and go over time 18804 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18805 storage.registerListener(mStorageListener); 18806 18807 mInstallerService.systemReady(); 18808 mPackageDexOptimizer.systemReady(); 18809 18810 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 18811 StorageManagerInternal.class); 18812 StorageManagerInternal.addExternalStoragePolicy( 18813 new StorageManagerInternal.ExternalStorageMountPolicy() { 18814 @Override 18815 public int getMountMode(int uid, String packageName) { 18816 if (Process.isIsolated(uid)) { 18817 return Zygote.MOUNT_EXTERNAL_NONE; 18818 } 18819 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18820 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18821 } 18822 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18823 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18824 } 18825 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18826 return Zygote.MOUNT_EXTERNAL_READ; 18827 } 18828 return Zygote.MOUNT_EXTERNAL_WRITE; 18829 } 18830 18831 @Override 18832 public boolean hasExternalStorage(int uid, String packageName) { 18833 return true; 18834 } 18835 }); 18836 18837 // Now that we're mostly running, clean up stale users and apps 18838 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18839 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18840 } 18841 18842 @Override 18843 public boolean isSafeMode() { 18844 return mSafeMode; 18845 } 18846 18847 @Override 18848 public boolean hasSystemUidErrors() { 18849 return mHasSystemUidErrors; 18850 } 18851 18852 static String arrayToString(int[] array) { 18853 StringBuffer buf = new StringBuffer(128); 18854 buf.append('['); 18855 if (array != null) { 18856 for (int i=0; i<array.length; i++) { 18857 if (i > 0) buf.append(", "); 18858 buf.append(array[i]); 18859 } 18860 } 18861 buf.append(']'); 18862 return buf.toString(); 18863 } 18864 18865 static class DumpState { 18866 public static final int DUMP_LIBS = 1 << 0; 18867 public static final int DUMP_FEATURES = 1 << 1; 18868 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18869 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18870 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18871 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18872 public static final int DUMP_PERMISSIONS = 1 << 6; 18873 public static final int DUMP_PACKAGES = 1 << 7; 18874 public static final int DUMP_SHARED_USERS = 1 << 8; 18875 public static final int DUMP_MESSAGES = 1 << 9; 18876 public static final int DUMP_PROVIDERS = 1 << 10; 18877 public static final int DUMP_VERIFIERS = 1 << 11; 18878 public static final int DUMP_PREFERRED = 1 << 12; 18879 public static final int DUMP_PREFERRED_XML = 1 << 13; 18880 public static final int DUMP_KEYSETS = 1 << 14; 18881 public static final int DUMP_VERSION = 1 << 15; 18882 public static final int DUMP_INSTALLS = 1 << 16; 18883 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18884 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18885 public static final int DUMP_FROZEN = 1 << 19; 18886 public static final int DUMP_DEXOPT = 1 << 20; 18887 public static final int DUMP_COMPILER_STATS = 1 << 21; 18888 18889 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18890 18891 private int mTypes; 18892 18893 private int mOptions; 18894 18895 private boolean mTitlePrinted; 18896 18897 private SharedUserSetting mSharedUser; 18898 18899 public boolean isDumping(int type) { 18900 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18901 return true; 18902 } 18903 18904 return (mTypes & type) != 0; 18905 } 18906 18907 public void setDump(int type) { 18908 mTypes |= type; 18909 } 18910 18911 public boolean isOptionEnabled(int option) { 18912 return (mOptions & option) != 0; 18913 } 18914 18915 public void setOptionEnabled(int option) { 18916 mOptions |= option; 18917 } 18918 18919 public boolean onTitlePrinted() { 18920 final boolean printed = mTitlePrinted; 18921 mTitlePrinted = true; 18922 return printed; 18923 } 18924 18925 public boolean getTitlePrinted() { 18926 return mTitlePrinted; 18927 } 18928 18929 public void setTitlePrinted(boolean enabled) { 18930 mTitlePrinted = enabled; 18931 } 18932 18933 public SharedUserSetting getSharedUser() { 18934 return mSharedUser; 18935 } 18936 18937 public void setSharedUser(SharedUserSetting user) { 18938 mSharedUser = user; 18939 } 18940 } 18941 18942 @Override 18943 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18944 FileDescriptor err, String[] args, ShellCallback callback, 18945 ResultReceiver resultReceiver) { 18946 (new PackageManagerShellCommand(this)).exec( 18947 this, in, out, err, args, callback, resultReceiver); 18948 } 18949 18950 @Override 18951 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18952 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18953 != PackageManager.PERMISSION_GRANTED) { 18954 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18955 + Binder.getCallingPid() 18956 + ", uid=" + Binder.getCallingUid() 18957 + " without permission " 18958 + android.Manifest.permission.DUMP); 18959 return; 18960 } 18961 18962 DumpState dumpState = new DumpState(); 18963 boolean fullPreferred = false; 18964 boolean checkin = false; 18965 18966 String packageName = null; 18967 ArraySet<String> permissionNames = null; 18968 18969 int opti = 0; 18970 while (opti < args.length) { 18971 String opt = args[opti]; 18972 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18973 break; 18974 } 18975 opti++; 18976 18977 if ("-a".equals(opt)) { 18978 // Right now we only know how to print all. 18979 } else if ("-h".equals(opt)) { 18980 pw.println("Package manager dump options:"); 18981 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18982 pw.println(" --checkin: dump for a checkin"); 18983 pw.println(" -f: print details of intent filters"); 18984 pw.println(" -h: print this help"); 18985 pw.println(" cmd may be one of:"); 18986 pw.println(" l[ibraries]: list known shared libraries"); 18987 pw.println(" f[eatures]: list device features"); 18988 pw.println(" k[eysets]: print known keysets"); 18989 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18990 pw.println(" perm[issions]: dump permissions"); 18991 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18992 pw.println(" pref[erred]: print preferred package settings"); 18993 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18994 pw.println(" prov[iders]: dump content providers"); 18995 pw.println(" p[ackages]: dump installed packages"); 18996 pw.println(" s[hared-users]: dump shared user IDs"); 18997 pw.println(" m[essages]: print collected runtime messages"); 18998 pw.println(" v[erifiers]: print package verifier info"); 18999 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 19000 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 19001 pw.println(" version: print database version info"); 19002 pw.println(" write: write current settings now"); 19003 pw.println(" installs: details about install sessions"); 19004 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 19005 pw.println(" dexopt: dump dexopt state"); 19006 pw.println(" compiler-stats: dump compiler statistics"); 19007 pw.println(" <package.name>: info about given package"); 19008 return; 19009 } else if ("--checkin".equals(opt)) { 19010 checkin = true; 19011 } else if ("-f".equals(opt)) { 19012 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 19013 } else { 19014 pw.println("Unknown argument: " + opt + "; use -h for help"); 19015 } 19016 } 19017 19018 // Is the caller requesting to dump a particular piece of data? 19019 if (opti < args.length) { 19020 String cmd = args[opti]; 19021 opti++; 19022 // Is this a package name? 19023 if ("android".equals(cmd) || cmd.contains(".")) { 19024 packageName = cmd; 19025 // When dumping a single package, we always dump all of its 19026 // filter information since the amount of data will be reasonable. 19027 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 19028 } else if ("check-permission".equals(cmd)) { 19029 if (opti >= args.length) { 19030 pw.println("Error: check-permission missing permission argument"); 19031 return; 19032 } 19033 String perm = args[opti]; 19034 opti++; 19035 if (opti >= args.length) { 19036 pw.println("Error: check-permission missing package argument"); 19037 return; 19038 } 19039 String pkg = args[opti]; 19040 opti++; 19041 int user = UserHandle.getUserId(Binder.getCallingUid()); 19042 if (opti < args.length) { 19043 try { 19044 user = Integer.parseInt(args[opti]); 19045 } catch (NumberFormatException e) { 19046 pw.println("Error: check-permission user argument is not a number: " 19047 + args[opti]); 19048 return; 19049 } 19050 } 19051 pw.println(checkPermission(perm, pkg, user)); 19052 return; 19053 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 19054 dumpState.setDump(DumpState.DUMP_LIBS); 19055 } else if ("f".equals(cmd) || "features".equals(cmd)) { 19056 dumpState.setDump(DumpState.DUMP_FEATURES); 19057 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 19058 if (opti >= args.length) { 19059 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 19060 | DumpState.DUMP_SERVICE_RESOLVERS 19061 | DumpState.DUMP_RECEIVER_RESOLVERS 19062 | DumpState.DUMP_CONTENT_RESOLVERS); 19063 } else { 19064 while (opti < args.length) { 19065 String name = args[opti]; 19066 if ("a".equals(name) || "activity".equals(name)) { 19067 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 19068 } else if ("s".equals(name) || "service".equals(name)) { 19069 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 19070 } else if ("r".equals(name) || "receiver".equals(name)) { 19071 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 19072 } else if ("c".equals(name) || "content".equals(name)) { 19073 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 19074 } else { 19075 pw.println("Error: unknown resolver table type: " + name); 19076 return; 19077 } 19078 opti++; 19079 } 19080 } 19081 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 19082 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 19083 } else if ("permission".equals(cmd)) { 19084 if (opti >= args.length) { 19085 pw.println("Error: permission requires permission name"); 19086 return; 19087 } 19088 permissionNames = new ArraySet<>(); 19089 while (opti < args.length) { 19090 permissionNames.add(args[opti]); 19091 opti++; 19092 } 19093 dumpState.setDump(DumpState.DUMP_PERMISSIONS 19094 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 19095 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 19096 dumpState.setDump(DumpState.DUMP_PREFERRED); 19097 } else if ("preferred-xml".equals(cmd)) { 19098 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 19099 if (opti < args.length && "--full".equals(args[opti])) { 19100 fullPreferred = true; 19101 opti++; 19102 } 19103 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 19104 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 19105 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 19106 dumpState.setDump(DumpState.DUMP_PACKAGES); 19107 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 19108 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 19109 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 19110 dumpState.setDump(DumpState.DUMP_PROVIDERS); 19111 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 19112 dumpState.setDump(DumpState.DUMP_MESSAGES); 19113 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 19114 dumpState.setDump(DumpState.DUMP_VERIFIERS); 19115 } else if ("i".equals(cmd) || "ifv".equals(cmd) 19116 || "intent-filter-verifiers".equals(cmd)) { 19117 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 19118 } else if ("version".equals(cmd)) { 19119 dumpState.setDump(DumpState.DUMP_VERSION); 19120 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 19121 dumpState.setDump(DumpState.DUMP_KEYSETS); 19122 } else if ("installs".equals(cmd)) { 19123 dumpState.setDump(DumpState.DUMP_INSTALLS); 19124 } else if ("frozen".equals(cmd)) { 19125 dumpState.setDump(DumpState.DUMP_FROZEN); 19126 } else if ("dexopt".equals(cmd)) { 19127 dumpState.setDump(DumpState.DUMP_DEXOPT); 19128 } else if ("compiler-stats".equals(cmd)) { 19129 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 19130 } else if ("write".equals(cmd)) { 19131 synchronized (mPackages) { 19132 mSettings.writeLPr(); 19133 pw.println("Settings written."); 19134 return; 19135 } 19136 } 19137 } 19138 19139 if (checkin) { 19140 pw.println("vers,1"); 19141 } 19142 19143 // reader 19144 synchronized (mPackages) { 19145 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 19146 if (!checkin) { 19147 if (dumpState.onTitlePrinted()) 19148 pw.println(); 19149 pw.println("Database versions:"); 19150 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 19151 } 19152 } 19153 19154 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 19155 if (!checkin) { 19156 if (dumpState.onTitlePrinted()) 19157 pw.println(); 19158 pw.println("Verifiers:"); 19159 pw.print(" Required: "); 19160 pw.print(mRequiredVerifierPackage); 19161 pw.print(" (uid="); 19162 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 19163 UserHandle.USER_SYSTEM)); 19164 pw.println(")"); 19165 } else if (mRequiredVerifierPackage != null) { 19166 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 19167 pw.print(","); 19168 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 19169 UserHandle.USER_SYSTEM)); 19170 } 19171 } 19172 19173 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 19174 packageName == null) { 19175 if (mIntentFilterVerifierComponent != null) { 19176 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 19177 if (!checkin) { 19178 if (dumpState.onTitlePrinted()) 19179 pw.println(); 19180 pw.println("Intent Filter Verifier:"); 19181 pw.print(" Using: "); 19182 pw.print(verifierPackageName); 19183 pw.print(" (uid="); 19184 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 19185 UserHandle.USER_SYSTEM)); 19186 pw.println(")"); 19187 } else if (verifierPackageName != null) { 19188 pw.print("ifv,"); pw.print(verifierPackageName); 19189 pw.print(","); 19190 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 19191 UserHandle.USER_SYSTEM)); 19192 } 19193 } else { 19194 pw.println(); 19195 pw.println("No Intent Filter Verifier available!"); 19196 } 19197 } 19198 19199 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 19200 boolean printedHeader = false; 19201 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 19202 while (it.hasNext()) { 19203 String name = it.next(); 19204 SharedLibraryEntry ent = mSharedLibraries.get(name); 19205 if (!checkin) { 19206 if (!printedHeader) { 19207 if (dumpState.onTitlePrinted()) 19208 pw.println(); 19209 pw.println("Libraries:"); 19210 printedHeader = true; 19211 } 19212 pw.print(" "); 19213 } else { 19214 pw.print("lib,"); 19215 } 19216 pw.print(name); 19217 if (!checkin) { 19218 pw.print(" -> "); 19219 } 19220 if (ent.path != null) { 19221 if (!checkin) { 19222 pw.print("(jar) "); 19223 pw.print(ent.path); 19224 } else { 19225 pw.print(",jar,"); 19226 pw.print(ent.path); 19227 } 19228 } else { 19229 if (!checkin) { 19230 pw.print("(apk) "); 19231 pw.print(ent.apk); 19232 } else { 19233 pw.print(",apk,"); 19234 pw.print(ent.apk); 19235 } 19236 } 19237 pw.println(); 19238 } 19239 } 19240 19241 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 19242 if (dumpState.onTitlePrinted()) 19243 pw.println(); 19244 if (!checkin) { 19245 pw.println("Features:"); 19246 } 19247 19248 for (FeatureInfo feat : mAvailableFeatures.values()) { 19249 if (checkin) { 19250 pw.print("feat,"); 19251 pw.print(feat.name); 19252 pw.print(","); 19253 pw.println(feat.version); 19254 } else { 19255 pw.print(" "); 19256 pw.print(feat.name); 19257 if (feat.version > 0) { 19258 pw.print(" version="); 19259 pw.print(feat.version); 19260 } 19261 pw.println(); 19262 } 19263 } 19264 } 19265 19266 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 19267 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 19268 : "Activity Resolver Table:", " ", packageName, 19269 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19270 dumpState.setTitlePrinted(true); 19271 } 19272 } 19273 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 19274 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 19275 : "Receiver Resolver Table:", " ", packageName, 19276 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19277 dumpState.setTitlePrinted(true); 19278 } 19279 } 19280 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 19281 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 19282 : "Service Resolver Table:", " ", packageName, 19283 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19284 dumpState.setTitlePrinted(true); 19285 } 19286 } 19287 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 19288 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 19289 : "Provider Resolver Table:", " ", packageName, 19290 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19291 dumpState.setTitlePrinted(true); 19292 } 19293 } 19294 19295 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 19296 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19297 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19298 int user = mSettings.mPreferredActivities.keyAt(i); 19299 if (pir.dump(pw, 19300 dumpState.getTitlePrinted() 19301 ? "\nPreferred Activities User " + user + ":" 19302 : "Preferred Activities User " + user + ":", " ", 19303 packageName, true, false)) { 19304 dumpState.setTitlePrinted(true); 19305 } 19306 } 19307 } 19308 19309 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 19310 pw.flush(); 19311 FileOutputStream fout = new FileOutputStream(fd); 19312 BufferedOutputStream str = new BufferedOutputStream(fout); 19313 XmlSerializer serializer = new FastXmlSerializer(); 19314 try { 19315 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 19316 serializer.startDocument(null, true); 19317 serializer.setFeature( 19318 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 19319 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 19320 serializer.endDocument(); 19321 serializer.flush(); 19322 } catch (IllegalArgumentException e) { 19323 pw.println("Failed writing: " + e); 19324 } catch (IllegalStateException e) { 19325 pw.println("Failed writing: " + e); 19326 } catch (IOException e) { 19327 pw.println("Failed writing: " + e); 19328 } 19329 } 19330 19331 if (!checkin 19332 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 19333 && packageName == null) { 19334 pw.println(); 19335 int count = mSettings.mPackages.size(); 19336 if (count == 0) { 19337 pw.println("No applications!"); 19338 pw.println(); 19339 } else { 19340 final String prefix = " "; 19341 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 19342 if (allPackageSettings.size() == 0) { 19343 pw.println("No domain preferred apps!"); 19344 pw.println(); 19345 } else { 19346 pw.println("App verification status:"); 19347 pw.println(); 19348 count = 0; 19349 for (PackageSetting ps : allPackageSettings) { 19350 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 19351 if (ivi == null || ivi.getPackageName() == null) continue; 19352 pw.println(prefix + "Package: " + ivi.getPackageName()); 19353 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 19354 pw.println(prefix + "Status: " + ivi.getStatusString()); 19355 pw.println(); 19356 count++; 19357 } 19358 if (count == 0) { 19359 pw.println(prefix + "No app verification established."); 19360 pw.println(); 19361 } 19362 for (int userId : sUserManager.getUserIds()) { 19363 pw.println("App linkages for user " + userId + ":"); 19364 pw.println(); 19365 count = 0; 19366 for (PackageSetting ps : allPackageSettings) { 19367 final long status = ps.getDomainVerificationStatusForUser(userId); 19368 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 19369 continue; 19370 } 19371 pw.println(prefix + "Package: " + ps.name); 19372 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 19373 String statusStr = IntentFilterVerificationInfo. 19374 getStatusStringFromValue(status); 19375 pw.println(prefix + "Status: " + statusStr); 19376 pw.println(); 19377 count++; 19378 } 19379 if (count == 0) { 19380 pw.println(prefix + "No configured app linkages."); 19381 pw.println(); 19382 } 19383 } 19384 } 19385 } 19386 } 19387 19388 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 19389 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 19390 if (packageName == null && permissionNames == null) { 19391 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 19392 if (iperm == 0) { 19393 if (dumpState.onTitlePrinted()) 19394 pw.println(); 19395 pw.println("AppOp Permissions:"); 19396 } 19397 pw.print(" AppOp Permission "); 19398 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 19399 pw.println(":"); 19400 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 19401 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 19402 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 19403 } 19404 } 19405 } 19406 } 19407 19408 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 19409 boolean printedSomething = false; 19410 for (PackageParser.Provider p : mProviders.mProviders.values()) { 19411 if (packageName != null && !packageName.equals(p.info.packageName)) { 19412 continue; 19413 } 19414 if (!printedSomething) { 19415 if (dumpState.onTitlePrinted()) 19416 pw.println(); 19417 pw.println("Registered ContentProviders:"); 19418 printedSomething = true; 19419 } 19420 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 19421 pw.print(" "); pw.println(p.toString()); 19422 } 19423 printedSomething = false; 19424 for (Map.Entry<String, PackageParser.Provider> entry : 19425 mProvidersByAuthority.entrySet()) { 19426 PackageParser.Provider p = entry.getValue(); 19427 if (packageName != null && !packageName.equals(p.info.packageName)) { 19428 continue; 19429 } 19430 if (!printedSomething) { 19431 if (dumpState.onTitlePrinted()) 19432 pw.println(); 19433 pw.println("ContentProvider Authorities:"); 19434 printedSomething = true; 19435 } 19436 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 19437 pw.print(" "); pw.println(p.toString()); 19438 if (p.info != null && p.info.applicationInfo != null) { 19439 final String appInfo = p.info.applicationInfo.toString(); 19440 pw.print(" applicationInfo="); pw.println(appInfo); 19441 } 19442 } 19443 } 19444 19445 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 19446 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 19447 } 19448 19449 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 19450 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 19451 } 19452 19453 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 19454 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 19455 } 19456 19457 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 19458 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 19459 } 19460 19461 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 19462 // XXX should handle packageName != null by dumping only install data that 19463 // the given package is involved with. 19464 if (dumpState.onTitlePrinted()) pw.println(); 19465 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 19466 } 19467 19468 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 19469 // XXX should handle packageName != null by dumping only install data that 19470 // the given package is involved with. 19471 if (dumpState.onTitlePrinted()) pw.println(); 19472 19473 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19474 ipw.println(); 19475 ipw.println("Frozen packages:"); 19476 ipw.increaseIndent(); 19477 if (mFrozenPackages.size() == 0) { 19478 ipw.println("(none)"); 19479 } else { 19480 for (int i = 0; i < mFrozenPackages.size(); i++) { 19481 ipw.println(mFrozenPackages.valueAt(i)); 19482 } 19483 } 19484 ipw.decreaseIndent(); 19485 } 19486 19487 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 19488 if (dumpState.onTitlePrinted()) pw.println(); 19489 dumpDexoptStateLPr(pw, packageName); 19490 } 19491 19492 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 19493 if (dumpState.onTitlePrinted()) pw.println(); 19494 dumpCompilerStatsLPr(pw, packageName); 19495 } 19496 19497 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 19498 if (dumpState.onTitlePrinted()) pw.println(); 19499 mSettings.dumpReadMessagesLPr(pw, dumpState); 19500 19501 pw.println(); 19502 pw.println("Package warning messages:"); 19503 BufferedReader in = null; 19504 String line = null; 19505 try { 19506 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19507 while ((line = in.readLine()) != null) { 19508 if (line.contains("ignored: updated version")) continue; 19509 pw.println(line); 19510 } 19511 } catch (IOException ignored) { 19512 } finally { 19513 IoUtils.closeQuietly(in); 19514 } 19515 } 19516 19517 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 19518 BufferedReader in = null; 19519 String line = null; 19520 try { 19521 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19522 while ((line = in.readLine()) != null) { 19523 if (line.contains("ignored: updated version")) continue; 19524 pw.print("msg,"); 19525 pw.println(line); 19526 } 19527 } catch (IOException ignored) { 19528 } finally { 19529 IoUtils.closeQuietly(in); 19530 } 19531 } 19532 } 19533 } 19534 19535 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 19536 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19537 ipw.println(); 19538 ipw.println("Dexopt state:"); 19539 ipw.increaseIndent(); 19540 Collection<PackageParser.Package> packages = null; 19541 if (packageName != null) { 19542 PackageParser.Package targetPackage = mPackages.get(packageName); 19543 if (targetPackage != null) { 19544 packages = Collections.singletonList(targetPackage); 19545 } else { 19546 ipw.println("Unable to find package: " + packageName); 19547 return; 19548 } 19549 } else { 19550 packages = mPackages.values(); 19551 } 19552 19553 for (PackageParser.Package pkg : packages) { 19554 ipw.println("[" + pkg.packageName + "]"); 19555 ipw.increaseIndent(); 19556 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 19557 ipw.decreaseIndent(); 19558 } 19559 } 19560 19561 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 19562 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19563 ipw.println(); 19564 ipw.println("Compiler stats:"); 19565 ipw.increaseIndent(); 19566 Collection<PackageParser.Package> packages = null; 19567 if (packageName != null) { 19568 PackageParser.Package targetPackage = mPackages.get(packageName); 19569 if (targetPackage != null) { 19570 packages = Collections.singletonList(targetPackage); 19571 } else { 19572 ipw.println("Unable to find package: " + packageName); 19573 return; 19574 } 19575 } else { 19576 packages = mPackages.values(); 19577 } 19578 19579 for (PackageParser.Package pkg : packages) { 19580 ipw.println("[" + pkg.packageName + "]"); 19581 ipw.increaseIndent(); 19582 19583 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 19584 if (stats == null) { 19585 ipw.println("(No recorded stats)"); 19586 } else { 19587 stats.dump(ipw); 19588 } 19589 ipw.decreaseIndent(); 19590 } 19591 } 19592 19593 private String dumpDomainString(String packageName) { 19594 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 19595 .getList(); 19596 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 19597 19598 ArraySet<String> result = new ArraySet<>(); 19599 if (iviList.size() > 0) { 19600 for (IntentFilterVerificationInfo ivi : iviList) { 19601 for (String host : ivi.getDomains()) { 19602 result.add(host); 19603 } 19604 } 19605 } 19606 if (filters != null && filters.size() > 0) { 19607 for (IntentFilter filter : filters) { 19608 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 19609 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19610 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19611 result.addAll(filter.getHostsList()); 19612 } 19613 } 19614 } 19615 19616 StringBuilder sb = new StringBuilder(result.size() * 16); 19617 for (String domain : result) { 19618 if (sb.length() > 0) sb.append(" "); 19619 sb.append(domain); 19620 } 19621 return sb.toString(); 19622 } 19623 19624 // ------- apps on sdcard specific code ------- 19625 static final boolean DEBUG_SD_INSTALL = false; 19626 19627 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19628 19629 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19630 19631 private boolean mMediaMounted = false; 19632 19633 static String getEncryptKey() { 19634 try { 19635 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19636 SD_ENCRYPTION_KEYSTORE_NAME); 19637 if (sdEncKey == null) { 19638 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19639 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19640 if (sdEncKey == null) { 19641 Slog.e(TAG, "Failed to create encryption keys"); 19642 return null; 19643 } 19644 } 19645 return sdEncKey; 19646 } catch (NoSuchAlgorithmException nsae) { 19647 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19648 return null; 19649 } catch (IOException ioe) { 19650 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19651 return null; 19652 } 19653 } 19654 19655 /* 19656 * Update media status on PackageManager. 19657 */ 19658 @Override 19659 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19660 int callingUid = Binder.getCallingUid(); 19661 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19662 throw new SecurityException("Media status can only be updated by the system"); 19663 } 19664 // reader; this apparently protects mMediaMounted, but should probably 19665 // be a different lock in that case. 19666 synchronized (mPackages) { 19667 Log.i(TAG, "Updating external media status from " 19668 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19669 + (mediaStatus ? "mounted" : "unmounted")); 19670 if (DEBUG_SD_INSTALL) 19671 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19672 + ", mMediaMounted=" + mMediaMounted); 19673 if (mediaStatus == mMediaMounted) { 19674 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19675 : 0, -1); 19676 mHandler.sendMessage(msg); 19677 return; 19678 } 19679 mMediaMounted = mediaStatus; 19680 } 19681 // Queue up an async operation since the package installation may take a 19682 // little while. 19683 mHandler.post(new Runnable() { 19684 public void run() { 19685 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19686 } 19687 }); 19688 } 19689 19690 /** 19691 * Called by StorageManagerService when the initial ASECs to scan are available. 19692 * Should block until all the ASEC containers are finished being scanned. 19693 */ 19694 public void scanAvailableAsecs() { 19695 updateExternalMediaStatusInner(true, false, false); 19696 } 19697 19698 /* 19699 * Collect information of applications on external media, map them against 19700 * existing containers and update information based on current mount status. 19701 * Please note that we always have to report status if reportStatus has been 19702 * set to true especially when unloading packages. 19703 */ 19704 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19705 boolean externalStorage) { 19706 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19707 int[] uidArr = EmptyArray.INT; 19708 19709 final String[] list = PackageHelper.getSecureContainerList(); 19710 if (ArrayUtils.isEmpty(list)) { 19711 Log.i(TAG, "No secure containers found"); 19712 } else { 19713 // Process list of secure containers and categorize them 19714 // as active or stale based on their package internal state. 19715 19716 // reader 19717 synchronized (mPackages) { 19718 for (String cid : list) { 19719 // Leave stages untouched for now; installer service owns them 19720 if (PackageInstallerService.isStageName(cid)) continue; 19721 19722 if (DEBUG_SD_INSTALL) 19723 Log.i(TAG, "Processing container " + cid); 19724 String pkgName = getAsecPackageName(cid); 19725 if (pkgName == null) { 19726 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19727 continue; 19728 } 19729 if (DEBUG_SD_INSTALL) 19730 Log.i(TAG, "Looking for pkg : " + pkgName); 19731 19732 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19733 if (ps == null) { 19734 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19735 continue; 19736 } 19737 19738 /* 19739 * Skip packages that are not external if we're unmounting 19740 * external storage. 19741 */ 19742 if (externalStorage && !isMounted && !isExternal(ps)) { 19743 continue; 19744 } 19745 19746 final AsecInstallArgs args = new AsecInstallArgs(cid, 19747 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19748 // The package status is changed only if the code path 19749 // matches between settings and the container id. 19750 if (ps.codePathString != null 19751 && ps.codePathString.startsWith(args.getCodePath())) { 19752 if (DEBUG_SD_INSTALL) { 19753 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19754 + " at code path: " + ps.codePathString); 19755 } 19756 19757 // We do have a valid package installed on sdcard 19758 processCids.put(args, ps.codePathString); 19759 final int uid = ps.appId; 19760 if (uid != -1) { 19761 uidArr = ArrayUtils.appendInt(uidArr, uid); 19762 } 19763 } else { 19764 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19765 + ps.codePathString); 19766 } 19767 } 19768 } 19769 19770 Arrays.sort(uidArr); 19771 } 19772 19773 // Process packages with valid entries. 19774 if (isMounted) { 19775 if (DEBUG_SD_INSTALL) 19776 Log.i(TAG, "Loading packages"); 19777 loadMediaPackages(processCids, uidArr, externalStorage); 19778 startCleaningPackages(); 19779 mInstallerService.onSecureContainersAvailable(); 19780 } else { 19781 if (DEBUG_SD_INSTALL) 19782 Log.i(TAG, "Unloading packages"); 19783 unloadMediaPackages(processCids, uidArr, reportStatus); 19784 } 19785 } 19786 19787 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19788 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19789 final int size = infos.size(); 19790 final String[] packageNames = new String[size]; 19791 final int[] packageUids = new int[size]; 19792 for (int i = 0; i < size; i++) { 19793 final ApplicationInfo info = infos.get(i); 19794 packageNames[i] = info.packageName; 19795 packageUids[i] = info.uid; 19796 } 19797 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19798 finishedReceiver); 19799 } 19800 19801 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19802 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19803 sendResourcesChangedBroadcast(mediaStatus, replacing, 19804 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19805 } 19806 19807 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19808 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19809 int size = pkgList.length; 19810 if (size > 0) { 19811 // Send broadcasts here 19812 Bundle extras = new Bundle(); 19813 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19814 if (uidArr != null) { 19815 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19816 } 19817 if (replacing) { 19818 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19819 } 19820 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19821 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19822 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19823 } 19824 } 19825 19826 /* 19827 * Look at potentially valid container ids from processCids If package 19828 * information doesn't match the one on record or package scanning fails, 19829 * the cid is added to list of removeCids. We currently don't delete stale 19830 * containers. 19831 */ 19832 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19833 boolean externalStorage) { 19834 ArrayList<String> pkgList = new ArrayList<String>(); 19835 Set<AsecInstallArgs> keys = processCids.keySet(); 19836 19837 for (AsecInstallArgs args : keys) { 19838 String codePath = processCids.get(args); 19839 if (DEBUG_SD_INSTALL) 19840 Log.i(TAG, "Loading container : " + args.cid); 19841 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19842 try { 19843 // Make sure there are no container errors first. 19844 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19845 Slog.e(TAG, "Failed to mount cid : " + args.cid 19846 + " when installing from sdcard"); 19847 continue; 19848 } 19849 // Check code path here. 19850 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19851 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19852 + " does not match one in settings " + codePath); 19853 continue; 19854 } 19855 // Parse package 19856 int parseFlags = mDefParseFlags; 19857 if (args.isExternalAsec()) { 19858 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19859 } 19860 if (args.isFwdLocked()) { 19861 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19862 } 19863 19864 synchronized (mInstallLock) { 19865 PackageParser.Package pkg = null; 19866 try { 19867 // Sadly we don't know the package name yet to freeze it 19868 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19869 SCAN_IGNORE_FROZEN, 0, null); 19870 } catch (PackageManagerException e) { 19871 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19872 } 19873 // Scan the package 19874 if (pkg != null) { 19875 /* 19876 * TODO why is the lock being held? doPostInstall is 19877 * called in other places without the lock. This needs 19878 * to be straightened out. 19879 */ 19880 // writer 19881 synchronized (mPackages) { 19882 retCode = PackageManager.INSTALL_SUCCEEDED; 19883 pkgList.add(pkg.packageName); 19884 // Post process args 19885 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19886 pkg.applicationInfo.uid); 19887 } 19888 } else { 19889 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19890 } 19891 } 19892 19893 } finally { 19894 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19895 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19896 } 19897 } 19898 } 19899 // writer 19900 synchronized (mPackages) { 19901 // If the platform SDK has changed since the last time we booted, 19902 // we need to re-grant app permission to catch any new ones that 19903 // appear. This is really a hack, and means that apps can in some 19904 // cases get permissions that the user didn't initially explicitly 19905 // allow... it would be nice to have some better way to handle 19906 // this situation. 19907 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19908 : mSettings.getInternalVersion(); 19909 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19910 : StorageManager.UUID_PRIVATE_INTERNAL; 19911 19912 int updateFlags = UPDATE_PERMISSIONS_ALL; 19913 if (ver.sdkVersion != mSdkVersion) { 19914 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19915 + mSdkVersion + "; regranting permissions for external"); 19916 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19917 } 19918 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19919 19920 // Yay, everything is now upgraded 19921 ver.forceCurrent(); 19922 19923 // can downgrade to reader 19924 // Persist settings 19925 mSettings.writeLPr(); 19926 } 19927 // Send a broadcast to let everyone know we are done processing 19928 if (pkgList.size() > 0) { 19929 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19930 } 19931 } 19932 19933 /* 19934 * Utility method to unload a list of specified containers 19935 */ 19936 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19937 // Just unmount all valid containers. 19938 for (AsecInstallArgs arg : cidArgs) { 19939 synchronized (mInstallLock) { 19940 arg.doPostDeleteLI(false); 19941 } 19942 } 19943 } 19944 19945 /* 19946 * Unload packages mounted on external media. This involves deleting package 19947 * data from internal structures, sending broadcasts about disabled packages, 19948 * gc'ing to free up references, unmounting all secure containers 19949 * corresponding to packages on external media, and posting a 19950 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19951 * that we always have to post this message if status has been requested no 19952 * matter what. 19953 */ 19954 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19955 final boolean reportStatus) { 19956 if (DEBUG_SD_INSTALL) 19957 Log.i(TAG, "unloading media packages"); 19958 ArrayList<String> pkgList = new ArrayList<String>(); 19959 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19960 final Set<AsecInstallArgs> keys = processCids.keySet(); 19961 for (AsecInstallArgs args : keys) { 19962 String pkgName = args.getPackageName(); 19963 if (DEBUG_SD_INSTALL) 19964 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19965 // Delete package internally 19966 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19967 synchronized (mInstallLock) { 19968 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19969 final boolean res; 19970 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19971 "unloadMediaPackages")) { 19972 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19973 null); 19974 } 19975 if (res) { 19976 pkgList.add(pkgName); 19977 } else { 19978 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19979 failedList.add(args); 19980 } 19981 } 19982 } 19983 19984 // reader 19985 synchronized (mPackages) { 19986 // We didn't update the settings after removing each package; 19987 // write them now for all packages. 19988 mSettings.writeLPr(); 19989 } 19990 19991 // We have to absolutely send UPDATED_MEDIA_STATUS only 19992 // after confirming that all the receivers processed the ordered 19993 // broadcast when packages get disabled, force a gc to clean things up. 19994 // and unload all the containers. 19995 if (pkgList.size() > 0) { 19996 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19997 new IIntentReceiver.Stub() { 19998 public void performReceive(Intent intent, int resultCode, String data, 19999 Bundle extras, boolean ordered, boolean sticky, 20000 int sendingUser) throws RemoteException { 20001 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 20002 reportStatus ? 1 : 0, 1, keys); 20003 mHandler.sendMessage(msg); 20004 } 20005 }); 20006 } else { 20007 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 20008 keys); 20009 mHandler.sendMessage(msg); 20010 } 20011 } 20012 20013 private void loadPrivatePackages(final VolumeInfo vol) { 20014 mHandler.post(new Runnable() { 20015 @Override 20016 public void run() { 20017 loadPrivatePackagesInner(vol); 20018 } 20019 }); 20020 } 20021 20022 private void loadPrivatePackagesInner(VolumeInfo vol) { 20023 final String volumeUuid = vol.fsUuid; 20024 if (TextUtils.isEmpty(volumeUuid)) { 20025 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 20026 return; 20027 } 20028 20029 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 20030 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 20031 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 20032 20033 final VersionInfo ver; 20034 final List<PackageSetting> packages; 20035 synchronized (mPackages) { 20036 ver = mSettings.findOrCreateVersion(volumeUuid); 20037 packages = mSettings.getVolumePackagesLPr(volumeUuid); 20038 } 20039 20040 for (PackageSetting ps : packages) { 20041 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 20042 synchronized (mInstallLock) { 20043 final PackageParser.Package pkg; 20044 try { 20045 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 20046 loaded.add(pkg.applicationInfo); 20047 20048 } catch (PackageManagerException e) { 20049 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 20050 } 20051 20052 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 20053 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 20054 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 20055 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20056 } 20057 } 20058 } 20059 20060 // Reconcile app data for all started/unlocked users 20061 final StorageManager sm = mContext.getSystemService(StorageManager.class); 20062 final UserManager um = mContext.getSystemService(UserManager.class); 20063 UserManagerInternal umInternal = getUserManagerInternal(); 20064 for (UserInfo user : um.getUsers()) { 20065 final int flags; 20066 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20067 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20068 } else if (umInternal.isUserRunning(user.id)) { 20069 flags = StorageManager.FLAG_STORAGE_DE; 20070 } else { 20071 continue; 20072 } 20073 20074 try { 20075 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 20076 synchronized (mInstallLock) { 20077 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 20078 } 20079 } catch (IllegalStateException e) { 20080 // Device was probably ejected, and we'll process that event momentarily 20081 Slog.w(TAG, "Failed to prepare storage: " + e); 20082 } 20083 } 20084 20085 synchronized (mPackages) { 20086 int updateFlags = UPDATE_PERMISSIONS_ALL; 20087 if (ver.sdkVersion != mSdkVersion) { 20088 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 20089 + mSdkVersion + "; regranting permissions for " + volumeUuid); 20090 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 20091 } 20092 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 20093 20094 // Yay, everything is now upgraded 20095 ver.forceCurrent(); 20096 20097 mSettings.writeLPr(); 20098 } 20099 20100 for (PackageFreezer freezer : freezers) { 20101 freezer.close(); 20102 } 20103 20104 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 20105 sendResourcesChangedBroadcast(true, false, loaded, null); 20106 } 20107 20108 private void unloadPrivatePackages(final VolumeInfo vol) { 20109 mHandler.post(new Runnable() { 20110 @Override 20111 public void run() { 20112 unloadPrivatePackagesInner(vol); 20113 } 20114 }); 20115 } 20116 20117 private void unloadPrivatePackagesInner(VolumeInfo vol) { 20118 final String volumeUuid = vol.fsUuid; 20119 if (TextUtils.isEmpty(volumeUuid)) { 20120 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 20121 return; 20122 } 20123 20124 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 20125 synchronized (mInstallLock) { 20126 synchronized (mPackages) { 20127 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 20128 for (PackageSetting ps : packages) { 20129 if (ps.pkg == null) continue; 20130 20131 final ApplicationInfo info = ps.pkg.applicationInfo; 20132 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 20133 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 20134 20135 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 20136 "unloadPrivatePackagesInner")) { 20137 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 20138 false, null)) { 20139 unloaded.add(info); 20140 } else { 20141 Slog.w(TAG, "Failed to unload " + ps.codePath); 20142 } 20143 } 20144 20145 // Try very hard to release any references to this package 20146 // so we don't risk the system server being killed due to 20147 // open FDs 20148 AttributeCache.instance().removePackage(ps.name); 20149 } 20150 20151 mSettings.writeLPr(); 20152 } 20153 } 20154 20155 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 20156 sendResourcesChangedBroadcast(false, false, unloaded, null); 20157 20158 // Try very hard to release any references to this path so we don't risk 20159 // the system server being killed due to open FDs 20160 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 20161 20162 for (int i = 0; i < 3; i++) { 20163 System.gc(); 20164 System.runFinalization(); 20165 } 20166 } 20167 20168 /** 20169 * Prepare storage areas for given user on all mounted devices. 20170 */ 20171 void prepareUserData(int userId, int userSerial, int flags) { 20172 synchronized (mInstallLock) { 20173 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20174 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20175 final String volumeUuid = vol.getFsUuid(); 20176 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 20177 } 20178 } 20179 } 20180 20181 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 20182 boolean allowRecover) { 20183 // Prepare storage and verify that serial numbers are consistent; if 20184 // there's a mismatch we need to destroy to avoid leaking data 20185 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20186 try { 20187 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 20188 20189 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 20190 UserManagerService.enforceSerialNumber( 20191 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 20192 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20193 UserManagerService.enforceSerialNumber( 20194 Environment.getDataSystemDeDirectory(userId), userSerial); 20195 } 20196 } 20197 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 20198 UserManagerService.enforceSerialNumber( 20199 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 20200 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20201 UserManagerService.enforceSerialNumber( 20202 Environment.getDataSystemCeDirectory(userId), userSerial); 20203 } 20204 } 20205 20206 synchronized (mInstallLock) { 20207 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 20208 } 20209 } catch (Exception e) { 20210 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 20211 + " because we failed to prepare: " + e); 20212 destroyUserDataLI(volumeUuid, userId, 20213 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 20214 20215 if (allowRecover) { 20216 // Try one last time; if we fail again we're really in trouble 20217 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 20218 } 20219 } 20220 } 20221 20222 /** 20223 * Destroy storage areas for given user on all mounted devices. 20224 */ 20225 void destroyUserData(int userId, int flags) { 20226 synchronized (mInstallLock) { 20227 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20228 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20229 final String volumeUuid = vol.getFsUuid(); 20230 destroyUserDataLI(volumeUuid, userId, flags); 20231 } 20232 } 20233 } 20234 20235 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 20236 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20237 try { 20238 // Clean up app data, profile data, and media data 20239 mInstaller.destroyUserData(volumeUuid, userId, flags); 20240 20241 // Clean up system data 20242 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20243 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20244 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 20245 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 20246 } 20247 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20248 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 20249 } 20250 } 20251 20252 // Data with special labels is now gone, so finish the job 20253 storage.destroyUserStorage(volumeUuid, userId, flags); 20254 20255 } catch (Exception e) { 20256 logCriticalInfo(Log.WARN, 20257 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 20258 } 20259 } 20260 20261 /** 20262 * Examine all users present on given mounted volume, and destroy data 20263 * belonging to users that are no longer valid, or whose user ID has been 20264 * recycled. 20265 */ 20266 private void reconcileUsers(String volumeUuid) { 20267 final List<File> files = new ArrayList<>(); 20268 Collections.addAll(files, FileUtils 20269 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 20270 Collections.addAll(files, FileUtils 20271 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 20272 Collections.addAll(files, FileUtils 20273 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 20274 Collections.addAll(files, FileUtils 20275 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 20276 for (File file : files) { 20277 if (!file.isDirectory()) continue; 20278 20279 final int userId; 20280 final UserInfo info; 20281 try { 20282 userId = Integer.parseInt(file.getName()); 20283 info = sUserManager.getUserInfo(userId); 20284 } catch (NumberFormatException e) { 20285 Slog.w(TAG, "Invalid user directory " + file); 20286 continue; 20287 } 20288 20289 boolean destroyUser = false; 20290 if (info == null) { 20291 logCriticalInfo(Log.WARN, "Destroying user directory " + file 20292 + " because no matching user was found"); 20293 destroyUser = true; 20294 } else if (!mOnlyCore) { 20295 try { 20296 UserManagerService.enforceSerialNumber(file, info.serialNumber); 20297 } catch (IOException e) { 20298 logCriticalInfo(Log.WARN, "Destroying user directory " + file 20299 + " because we failed to enforce serial number: " + e); 20300 destroyUser = true; 20301 } 20302 } 20303 20304 if (destroyUser) { 20305 synchronized (mInstallLock) { 20306 destroyUserDataLI(volumeUuid, userId, 20307 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 20308 } 20309 } 20310 } 20311 } 20312 20313 private void assertPackageKnown(String volumeUuid, String packageName) 20314 throws PackageManagerException { 20315 synchronized (mPackages) { 20316 // Normalize package name to handle renamed packages 20317 packageName = normalizePackageNameLPr(packageName); 20318 20319 final PackageSetting ps = mSettings.mPackages.get(packageName); 20320 if (ps == null) { 20321 throw new PackageManagerException("Package " + packageName + " is unknown"); 20322 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 20323 throw new PackageManagerException( 20324 "Package " + packageName + " found on unknown volume " + volumeUuid 20325 + "; expected volume " + ps.volumeUuid); 20326 } 20327 } 20328 } 20329 20330 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 20331 throws PackageManagerException { 20332 synchronized (mPackages) { 20333 // Normalize package name to handle renamed packages 20334 packageName = normalizePackageNameLPr(packageName); 20335 20336 final PackageSetting ps = mSettings.mPackages.get(packageName); 20337 if (ps == null) { 20338 throw new PackageManagerException("Package " + packageName + " is unknown"); 20339 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 20340 throw new PackageManagerException( 20341 "Package " + packageName + " found on unknown volume " + volumeUuid 20342 + "; expected volume " + ps.volumeUuid); 20343 } else if (!ps.getInstalled(userId)) { 20344 throw new PackageManagerException( 20345 "Package " + packageName + " not installed for user " + userId); 20346 } 20347 } 20348 } 20349 20350 /** 20351 * Examine all apps present on given mounted volume, and destroy apps that 20352 * aren't expected, either due to uninstallation or reinstallation on 20353 * another volume. 20354 */ 20355 private void reconcileApps(String volumeUuid) { 20356 final File[] files = FileUtils 20357 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 20358 for (File file : files) { 20359 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 20360 && !PackageInstallerService.isStageName(file.getName()); 20361 if (!isPackage) { 20362 // Ignore entries which are not packages 20363 continue; 20364 } 20365 20366 try { 20367 final PackageLite pkg = PackageParser.parsePackageLite(file, 20368 PackageParser.PARSE_MUST_BE_APK); 20369 assertPackageKnown(volumeUuid, pkg.packageName); 20370 20371 } catch (PackageParserException | PackageManagerException e) { 20372 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20373 synchronized (mInstallLock) { 20374 removeCodePathLI(file); 20375 } 20376 } 20377 } 20378 } 20379 20380 /** 20381 * Reconcile all app data for the given user. 20382 * <p> 20383 * Verifies that directories exist and that ownership and labeling is 20384 * correct for all installed apps on all mounted volumes. 20385 */ 20386 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 20387 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20388 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20389 final String volumeUuid = vol.getFsUuid(); 20390 synchronized (mInstallLock) { 20391 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 20392 } 20393 } 20394 } 20395 20396 /** 20397 * Reconcile all app data on given mounted volume. 20398 * <p> 20399 * Destroys app data that isn't expected, either due to uninstallation or 20400 * reinstallation on another volume. 20401 * <p> 20402 * Verifies that directories exist and that ownership and labeling is 20403 * correct for all installed apps. 20404 */ 20405 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 20406 boolean migrateAppData) { 20407 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 20408 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 20409 20410 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 20411 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 20412 20413 // First look for stale data that doesn't belong, and check if things 20414 // have changed since we did our last restorecon 20415 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20416 if (StorageManager.isFileEncryptedNativeOrEmulated() 20417 && !StorageManager.isUserKeyUnlocked(userId)) { 20418 throw new RuntimeException( 20419 "Yikes, someone asked us to reconcile CE storage while " + userId 20420 + " was still locked; this would have caused massive data loss!"); 20421 } 20422 20423 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 20424 for (File file : files) { 20425 final String packageName = file.getName(); 20426 try { 20427 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20428 } catch (PackageManagerException e) { 20429 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20430 try { 20431 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20432 StorageManager.FLAG_STORAGE_CE, 0); 20433 } catch (InstallerException e2) { 20434 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20435 } 20436 } 20437 } 20438 } 20439 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20440 final File[] files = FileUtils.listFilesOrEmpty(deDir); 20441 for (File file : files) { 20442 final String packageName = file.getName(); 20443 try { 20444 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20445 } catch (PackageManagerException e) { 20446 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20447 try { 20448 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20449 StorageManager.FLAG_STORAGE_DE, 0); 20450 } catch (InstallerException e2) { 20451 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20452 } 20453 } 20454 } 20455 } 20456 20457 // Ensure that data directories are ready to roll for all packages 20458 // installed for this volume and user 20459 final List<PackageSetting> packages; 20460 synchronized (mPackages) { 20461 packages = mSettings.getVolumePackagesLPr(volumeUuid); 20462 } 20463 int preparedCount = 0; 20464 for (PackageSetting ps : packages) { 20465 final String packageName = ps.name; 20466 if (ps.pkg == null) { 20467 Slog.w(TAG, "Odd, missing scanned package " + packageName); 20468 // TODO: might be due to legacy ASEC apps; we should circle back 20469 // and reconcile again once they're scanned 20470 continue; 20471 } 20472 20473 if (ps.getInstalled(userId)) { 20474 prepareAppDataLIF(ps.pkg, userId, flags); 20475 20476 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 20477 // We may have just shuffled around app data directories, so 20478 // prepare them one more time 20479 prepareAppDataLIF(ps.pkg, userId, flags); 20480 } 20481 20482 preparedCount++; 20483 } 20484 } 20485 20486 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 20487 } 20488 20489 /** 20490 * Prepare app data for the given app just after it was installed or 20491 * upgraded. This method carefully only touches users that it's installed 20492 * for, and it forces a restorecon to handle any seinfo changes. 20493 * <p> 20494 * Verifies that directories exist and that ownership and labeling is 20495 * correct for all installed apps. If there is an ownership mismatch, it 20496 * will try recovering system apps by wiping data; third-party app data is 20497 * left intact. 20498 * <p> 20499 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 20500 */ 20501 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 20502 final PackageSetting ps; 20503 synchronized (mPackages) { 20504 ps = mSettings.mPackages.get(pkg.packageName); 20505 mSettings.writeKernelMappingLPr(ps); 20506 } 20507 20508 final UserManager um = mContext.getSystemService(UserManager.class); 20509 UserManagerInternal umInternal = getUserManagerInternal(); 20510 for (UserInfo user : um.getUsers()) { 20511 final int flags; 20512 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20513 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20514 } else if (umInternal.isUserRunning(user.id)) { 20515 flags = StorageManager.FLAG_STORAGE_DE; 20516 } else { 20517 continue; 20518 } 20519 20520 if (ps.getInstalled(user.id)) { 20521 // TODO: when user data is locked, mark that we're still dirty 20522 prepareAppDataLIF(pkg, user.id, flags); 20523 } 20524 } 20525 } 20526 20527 /** 20528 * Prepare app data for the given app. 20529 * <p> 20530 * Verifies that directories exist and that ownership and labeling is 20531 * correct for all installed apps. If there is an ownership mismatch, this 20532 * will try recovering system apps by wiping data; third-party app data is 20533 * left intact. 20534 */ 20535 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 20536 if (pkg == null) { 20537 Slog.wtf(TAG, "Package was null!", new Throwable()); 20538 return; 20539 } 20540 prepareAppDataLeafLIF(pkg, userId, flags); 20541 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20542 for (int i = 0; i < childCount; i++) { 20543 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 20544 } 20545 } 20546 20547 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20548 if (DEBUG_APP_DATA) { 20549 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 20550 + Integer.toHexString(flags)); 20551 } 20552 20553 final String volumeUuid = pkg.volumeUuid; 20554 final String packageName = pkg.packageName; 20555 final ApplicationInfo app = pkg.applicationInfo; 20556 final int appId = UserHandle.getAppId(app.uid); 20557 20558 Preconditions.checkNotNull(app.seinfo); 20559 20560 long ceDataInode = -1; 20561 try { 20562 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20563 appId, app.seinfo, app.targetSdkVersion); 20564 } catch (InstallerException e) { 20565 if (app.isSystemApp()) { 20566 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 20567 + ", but trying to recover: " + e); 20568 destroyAppDataLeafLIF(pkg, userId, flags); 20569 try { 20570 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20571 appId, app.seinfo, app.targetSdkVersion); 20572 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 20573 } catch (InstallerException e2) { 20574 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 20575 } 20576 } else { 20577 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 20578 } 20579 } 20580 20581 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 20582 // TODO: mark this structure as dirty so we persist it! 20583 synchronized (mPackages) { 20584 final PackageSetting ps = mSettings.mPackages.get(packageName); 20585 if (ps != null) { 20586 ps.setCeDataInode(ceDataInode, userId); 20587 } 20588 } 20589 } 20590 20591 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20592 } 20593 20594 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 20595 if (pkg == null) { 20596 Slog.wtf(TAG, "Package was null!", new Throwable()); 20597 return; 20598 } 20599 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20600 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20601 for (int i = 0; i < childCount; i++) { 20602 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 20603 } 20604 } 20605 20606 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20607 final String volumeUuid = pkg.volumeUuid; 20608 final String packageName = pkg.packageName; 20609 final ApplicationInfo app = pkg.applicationInfo; 20610 20611 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20612 // Create a native library symlink only if we have native libraries 20613 // and if the native libraries are 32 bit libraries. We do not provide 20614 // this symlink for 64 bit libraries. 20615 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20616 final String nativeLibPath = app.nativeLibraryDir; 20617 try { 20618 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20619 nativeLibPath, userId); 20620 } catch (InstallerException e) { 20621 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20622 } 20623 } 20624 } 20625 } 20626 20627 /** 20628 * For system apps on non-FBE devices, this method migrates any existing 20629 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20630 * requested by the app. 20631 */ 20632 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20633 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20634 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20635 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20636 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20637 try { 20638 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20639 storageTarget); 20640 } catch (InstallerException e) { 20641 logCriticalInfo(Log.WARN, 20642 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20643 } 20644 return true; 20645 } else { 20646 return false; 20647 } 20648 } 20649 20650 public PackageFreezer freezePackage(String packageName, String killReason) { 20651 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20652 } 20653 20654 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20655 return new PackageFreezer(packageName, userId, killReason); 20656 } 20657 20658 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20659 String killReason) { 20660 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20661 } 20662 20663 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20664 String killReason) { 20665 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20666 return new PackageFreezer(); 20667 } else { 20668 return freezePackage(packageName, userId, killReason); 20669 } 20670 } 20671 20672 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20673 String killReason) { 20674 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20675 } 20676 20677 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20678 String killReason) { 20679 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20680 return new PackageFreezer(); 20681 } else { 20682 return freezePackage(packageName, userId, killReason); 20683 } 20684 } 20685 20686 /** 20687 * Class that freezes and kills the given package upon creation, and 20688 * unfreezes it upon closing. This is typically used when doing surgery on 20689 * app code/data to prevent the app from running while you're working. 20690 */ 20691 private class PackageFreezer implements AutoCloseable { 20692 private final String mPackageName; 20693 private final PackageFreezer[] mChildren; 20694 20695 private final boolean mWeFroze; 20696 20697 private final AtomicBoolean mClosed = new AtomicBoolean(); 20698 private final CloseGuard mCloseGuard = CloseGuard.get(); 20699 20700 /** 20701 * Create and return a stub freezer that doesn't actually do anything, 20702 * typically used when someone requested 20703 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20704 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20705 */ 20706 public PackageFreezer() { 20707 mPackageName = null; 20708 mChildren = null; 20709 mWeFroze = false; 20710 mCloseGuard.open("close"); 20711 } 20712 20713 public PackageFreezer(String packageName, int userId, String killReason) { 20714 synchronized (mPackages) { 20715 mPackageName = packageName; 20716 mWeFroze = mFrozenPackages.add(mPackageName); 20717 20718 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20719 if (ps != null) { 20720 killApplication(ps.name, ps.appId, userId, killReason); 20721 } 20722 20723 final PackageParser.Package p = mPackages.get(packageName); 20724 if (p != null && p.childPackages != null) { 20725 final int N = p.childPackages.size(); 20726 mChildren = new PackageFreezer[N]; 20727 for (int i = 0; i < N; i++) { 20728 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20729 userId, killReason); 20730 } 20731 } else { 20732 mChildren = null; 20733 } 20734 } 20735 mCloseGuard.open("close"); 20736 } 20737 20738 @Override 20739 protected void finalize() throws Throwable { 20740 try { 20741 mCloseGuard.warnIfOpen(); 20742 close(); 20743 } finally { 20744 super.finalize(); 20745 } 20746 } 20747 20748 @Override 20749 public void close() { 20750 mCloseGuard.close(); 20751 if (mClosed.compareAndSet(false, true)) { 20752 synchronized (mPackages) { 20753 if (mWeFroze) { 20754 mFrozenPackages.remove(mPackageName); 20755 } 20756 20757 if (mChildren != null) { 20758 for (PackageFreezer freezer : mChildren) { 20759 freezer.close(); 20760 } 20761 } 20762 } 20763 } 20764 } 20765 } 20766 20767 /** 20768 * Verify that given package is currently frozen. 20769 */ 20770 private void checkPackageFrozen(String packageName) { 20771 synchronized (mPackages) { 20772 if (!mFrozenPackages.contains(packageName)) { 20773 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20774 } 20775 } 20776 } 20777 20778 @Override 20779 public int movePackage(final String packageName, final String volumeUuid) { 20780 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20781 20782 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20783 final int moveId = mNextMoveId.getAndIncrement(); 20784 mHandler.post(new Runnable() { 20785 @Override 20786 public void run() { 20787 try { 20788 movePackageInternal(packageName, volumeUuid, moveId, user); 20789 } catch (PackageManagerException e) { 20790 Slog.w(TAG, "Failed to move " + packageName, e); 20791 mMoveCallbacks.notifyStatusChanged(moveId, 20792 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20793 } 20794 } 20795 }); 20796 return moveId; 20797 } 20798 20799 private void movePackageInternal(final String packageName, final String volumeUuid, 20800 final int moveId, UserHandle user) throws PackageManagerException { 20801 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20802 final PackageManager pm = mContext.getPackageManager(); 20803 20804 final boolean currentAsec; 20805 final String currentVolumeUuid; 20806 final File codeFile; 20807 final String installerPackageName; 20808 final String packageAbiOverride; 20809 final int appId; 20810 final String seinfo; 20811 final String label; 20812 final int targetSdkVersion; 20813 final PackageFreezer freezer; 20814 final int[] installedUserIds; 20815 20816 // reader 20817 synchronized (mPackages) { 20818 final PackageParser.Package pkg = mPackages.get(packageName); 20819 final PackageSetting ps = mSettings.mPackages.get(packageName); 20820 if (pkg == null || ps == null) { 20821 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20822 } 20823 20824 if (pkg.applicationInfo.isSystemApp()) { 20825 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20826 "Cannot move system application"); 20827 } 20828 20829 if (pkg.applicationInfo.isExternalAsec()) { 20830 currentAsec = true; 20831 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20832 } else if (pkg.applicationInfo.isForwardLocked()) { 20833 currentAsec = true; 20834 currentVolumeUuid = "forward_locked"; 20835 } else { 20836 currentAsec = false; 20837 currentVolumeUuid = ps.volumeUuid; 20838 20839 final File probe = new File(pkg.codePath); 20840 final File probeOat = new File(probe, "oat"); 20841 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20842 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20843 "Move only supported for modern cluster style installs"); 20844 } 20845 } 20846 20847 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20848 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20849 "Package already moved to " + volumeUuid); 20850 } 20851 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20852 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20853 "Device admin cannot be moved"); 20854 } 20855 20856 if (mFrozenPackages.contains(packageName)) { 20857 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20858 "Failed to move already frozen package"); 20859 } 20860 20861 codeFile = new File(pkg.codePath); 20862 installerPackageName = ps.installerPackageName; 20863 packageAbiOverride = ps.cpuAbiOverrideString; 20864 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20865 seinfo = pkg.applicationInfo.seinfo; 20866 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20867 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20868 freezer = freezePackage(packageName, "movePackageInternal"); 20869 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20870 } 20871 20872 final Bundle extras = new Bundle(); 20873 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20874 extras.putString(Intent.EXTRA_TITLE, label); 20875 mMoveCallbacks.notifyCreated(moveId, extras); 20876 20877 int installFlags; 20878 final boolean moveCompleteApp; 20879 final File measurePath; 20880 20881 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20882 installFlags = INSTALL_INTERNAL; 20883 moveCompleteApp = !currentAsec; 20884 measurePath = Environment.getDataAppDirectory(volumeUuid); 20885 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20886 installFlags = INSTALL_EXTERNAL; 20887 moveCompleteApp = false; 20888 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20889 } else { 20890 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20891 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20892 || !volume.isMountedWritable()) { 20893 freezer.close(); 20894 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20895 "Move location not mounted private volume"); 20896 } 20897 20898 Preconditions.checkState(!currentAsec); 20899 20900 installFlags = INSTALL_INTERNAL; 20901 moveCompleteApp = true; 20902 measurePath = Environment.getDataAppDirectory(volumeUuid); 20903 } 20904 20905 final PackageStats stats = new PackageStats(null, -1); 20906 synchronized (mInstaller) { 20907 for (int userId : installedUserIds) { 20908 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20909 freezer.close(); 20910 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20911 "Failed to measure package size"); 20912 } 20913 } 20914 } 20915 20916 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20917 + stats.dataSize); 20918 20919 final long startFreeBytes = measurePath.getFreeSpace(); 20920 final long sizeBytes; 20921 if (moveCompleteApp) { 20922 sizeBytes = stats.codeSize + stats.dataSize; 20923 } else { 20924 sizeBytes = stats.codeSize; 20925 } 20926 20927 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20928 freezer.close(); 20929 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20930 "Not enough free space to move"); 20931 } 20932 20933 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20934 20935 final CountDownLatch installedLatch = new CountDownLatch(1); 20936 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20937 @Override 20938 public void onUserActionRequired(Intent intent) throws RemoteException { 20939 throw new IllegalStateException(); 20940 } 20941 20942 @Override 20943 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20944 Bundle extras) throws RemoteException { 20945 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20946 + PackageManager.installStatusToString(returnCode, msg)); 20947 20948 installedLatch.countDown(); 20949 freezer.close(); 20950 20951 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20952 switch (status) { 20953 case PackageInstaller.STATUS_SUCCESS: 20954 mMoveCallbacks.notifyStatusChanged(moveId, 20955 PackageManager.MOVE_SUCCEEDED); 20956 break; 20957 case PackageInstaller.STATUS_FAILURE_STORAGE: 20958 mMoveCallbacks.notifyStatusChanged(moveId, 20959 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20960 break; 20961 default: 20962 mMoveCallbacks.notifyStatusChanged(moveId, 20963 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20964 break; 20965 } 20966 } 20967 }; 20968 20969 final MoveInfo move; 20970 if (moveCompleteApp) { 20971 // Kick off a thread to report progress estimates 20972 new Thread() { 20973 @Override 20974 public void run() { 20975 while (true) { 20976 try { 20977 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20978 break; 20979 } 20980 } catch (InterruptedException ignored) { 20981 } 20982 20983 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20984 final int progress = 10 + (int) MathUtils.constrain( 20985 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20986 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20987 } 20988 } 20989 }.start(); 20990 20991 final String dataAppName = codeFile.getName(); 20992 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20993 dataAppName, appId, seinfo, targetSdkVersion); 20994 } else { 20995 move = null; 20996 } 20997 20998 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20999 21000 final Message msg = mHandler.obtainMessage(INIT_COPY); 21001 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 21002 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 21003 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 21004 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 21005 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 21006 msg.obj = params; 21007 21008 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 21009 System.identityHashCode(msg.obj)); 21010 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 21011 System.identityHashCode(msg.obj)); 21012 21013 mHandler.sendMessage(msg); 21014 } 21015 21016 @Override 21017 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 21018 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 21019 21020 final int realMoveId = mNextMoveId.getAndIncrement(); 21021 final Bundle extras = new Bundle(); 21022 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 21023 mMoveCallbacks.notifyCreated(realMoveId, extras); 21024 21025 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 21026 @Override 21027 public void onCreated(int moveId, Bundle extras) { 21028 // Ignored 21029 } 21030 21031 @Override 21032 public void onStatusChanged(int moveId, int status, long estMillis) { 21033 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 21034 } 21035 }; 21036 21037 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21038 storage.setPrimaryStorageUuid(volumeUuid, callback); 21039 return realMoveId; 21040 } 21041 21042 @Override 21043 public int getMoveStatus(int moveId) { 21044 mContext.enforceCallingOrSelfPermission( 21045 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 21046 return mMoveCallbacks.mLastStatus.get(moveId); 21047 } 21048 21049 @Override 21050 public void registerMoveCallback(IPackageMoveObserver callback) { 21051 mContext.enforceCallingOrSelfPermission( 21052 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 21053 mMoveCallbacks.register(callback); 21054 } 21055 21056 @Override 21057 public void unregisterMoveCallback(IPackageMoveObserver callback) { 21058 mContext.enforceCallingOrSelfPermission( 21059 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 21060 mMoveCallbacks.unregister(callback); 21061 } 21062 21063 @Override 21064 public boolean setInstallLocation(int loc) { 21065 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 21066 null); 21067 if (getInstallLocation() == loc) { 21068 return true; 21069 } 21070 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 21071 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 21072 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 21073 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 21074 return true; 21075 } 21076 return false; 21077 } 21078 21079 @Override 21080 public int getInstallLocation() { 21081 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 21082 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 21083 PackageHelper.APP_INSTALL_AUTO); 21084 } 21085 21086 /** Called by UserManagerService */ 21087 void cleanUpUser(UserManagerService userManager, int userHandle) { 21088 synchronized (mPackages) { 21089 mDirtyUsers.remove(userHandle); 21090 mUserNeedsBadging.delete(userHandle); 21091 mSettings.removeUserLPw(userHandle); 21092 mPendingBroadcasts.remove(userHandle); 21093 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 21094 removeUnusedPackagesLPw(userManager, userHandle); 21095 } 21096 } 21097 21098 /** 21099 * We're removing userHandle and would like to remove any downloaded packages 21100 * that are no longer in use by any other user. 21101 * @param userHandle the user being removed 21102 */ 21103 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 21104 final boolean DEBUG_CLEAN_APKS = false; 21105 int [] users = userManager.getUserIds(); 21106 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 21107 while (psit.hasNext()) { 21108 PackageSetting ps = psit.next(); 21109 if (ps.pkg == null) { 21110 continue; 21111 } 21112 final String packageName = ps.pkg.packageName; 21113 // Skip over if system app 21114 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 21115 continue; 21116 } 21117 if (DEBUG_CLEAN_APKS) { 21118 Slog.i(TAG, "Checking package " + packageName); 21119 } 21120 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 21121 if (keep) { 21122 if (DEBUG_CLEAN_APKS) { 21123 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 21124 } 21125 } else { 21126 for (int i = 0; i < users.length; i++) { 21127 if (users[i] != userHandle && ps.getInstalled(users[i])) { 21128 keep = true; 21129 if (DEBUG_CLEAN_APKS) { 21130 Slog.i(TAG, " Keeping package " + packageName + " for user " 21131 + users[i]); 21132 } 21133 break; 21134 } 21135 } 21136 } 21137 if (!keep) { 21138 if (DEBUG_CLEAN_APKS) { 21139 Slog.i(TAG, " Removing package " + packageName); 21140 } 21141 mHandler.post(new Runnable() { 21142 public void run() { 21143 deletePackageX(packageName, userHandle, 0); 21144 } //end run 21145 }); 21146 } 21147 } 21148 } 21149 21150 /** Called by UserManagerService */ 21151 void createNewUser(int userId, String[] disallowedPackages) { 21152 synchronized (mInstallLock) { 21153 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 21154 } 21155 synchronized (mPackages) { 21156 scheduleWritePackageRestrictionsLocked(userId); 21157 scheduleWritePackageListLocked(userId); 21158 applyFactoryDefaultBrowserLPw(userId); 21159 primeDomainVerificationsLPw(userId); 21160 } 21161 } 21162 21163 void onNewUserCreated(final int userId) { 21164 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 21165 // If permission review for legacy apps is required, we represent 21166 // dagerous permissions for such apps as always granted runtime 21167 // permissions to keep per user flag state whether review is needed. 21168 // Hence, if a new user is added we have to propagate dangerous 21169 // permission grants for these legacy apps. 21170 if (mPermissionReviewRequired) { 21171 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 21172 | UPDATE_PERMISSIONS_REPLACE_ALL); 21173 } 21174 } 21175 21176 @Override 21177 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 21178 mContext.enforceCallingOrSelfPermission( 21179 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 21180 "Only package verification agents can read the verifier device identity"); 21181 21182 synchronized (mPackages) { 21183 return mSettings.getVerifierDeviceIdentityLPw(); 21184 } 21185 } 21186 21187 @Override 21188 public void setPermissionEnforced(String permission, boolean enforced) { 21189 // TODO: Now that we no longer change GID for storage, this should to away. 21190 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 21191 "setPermissionEnforced"); 21192 if (READ_EXTERNAL_STORAGE.equals(permission)) { 21193 synchronized (mPackages) { 21194 if (mSettings.mReadExternalStorageEnforced == null 21195 || mSettings.mReadExternalStorageEnforced != enforced) { 21196 mSettings.mReadExternalStorageEnforced = enforced; 21197 mSettings.writeLPr(); 21198 } 21199 } 21200 // kill any non-foreground processes so we restart them and 21201 // grant/revoke the GID. 21202 final IActivityManager am = ActivityManager.getService(); 21203 if (am != null) { 21204 final long token = Binder.clearCallingIdentity(); 21205 try { 21206 am.killProcessesBelowForeground("setPermissionEnforcement"); 21207 } catch (RemoteException e) { 21208 } finally { 21209 Binder.restoreCallingIdentity(token); 21210 } 21211 } 21212 } else { 21213 throw new IllegalArgumentException("No selective enforcement for " + permission); 21214 } 21215 } 21216 21217 @Override 21218 @Deprecated 21219 public boolean isPermissionEnforced(String permission) { 21220 return true; 21221 } 21222 21223 @Override 21224 public boolean isStorageLow() { 21225 final long token = Binder.clearCallingIdentity(); 21226 try { 21227 final DeviceStorageMonitorInternal 21228 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 21229 if (dsm != null) { 21230 return dsm.isMemoryLow(); 21231 } else { 21232 return false; 21233 } 21234 } finally { 21235 Binder.restoreCallingIdentity(token); 21236 } 21237 } 21238 21239 @Override 21240 public IPackageInstaller getPackageInstaller() { 21241 return mInstallerService; 21242 } 21243 21244 private boolean userNeedsBadging(int userId) { 21245 int index = mUserNeedsBadging.indexOfKey(userId); 21246 if (index < 0) { 21247 final UserInfo userInfo; 21248 final long token = Binder.clearCallingIdentity(); 21249 try { 21250 userInfo = sUserManager.getUserInfo(userId); 21251 } finally { 21252 Binder.restoreCallingIdentity(token); 21253 } 21254 final boolean b; 21255 if (userInfo != null && userInfo.isManagedProfile()) { 21256 b = true; 21257 } else { 21258 b = false; 21259 } 21260 mUserNeedsBadging.put(userId, b); 21261 return b; 21262 } 21263 return mUserNeedsBadging.valueAt(index); 21264 } 21265 21266 @Override 21267 public KeySet getKeySetByAlias(String packageName, String alias) { 21268 if (packageName == null || alias == null) { 21269 return null; 21270 } 21271 synchronized(mPackages) { 21272 final PackageParser.Package pkg = mPackages.get(packageName); 21273 if (pkg == null) { 21274 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21275 throw new IllegalArgumentException("Unknown package: " + packageName); 21276 } 21277 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21278 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 21279 } 21280 } 21281 21282 @Override 21283 public KeySet getSigningKeySet(String packageName) { 21284 if (packageName == null) { 21285 return null; 21286 } 21287 synchronized(mPackages) { 21288 final PackageParser.Package pkg = mPackages.get(packageName); 21289 if (pkg == null) { 21290 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21291 throw new IllegalArgumentException("Unknown package: " + packageName); 21292 } 21293 if (pkg.applicationInfo.uid != Binder.getCallingUid() 21294 && Process.SYSTEM_UID != Binder.getCallingUid()) { 21295 throw new SecurityException("May not access signing KeySet of other apps."); 21296 } 21297 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21298 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 21299 } 21300 } 21301 21302 @Override 21303 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 21304 if (packageName == null || ks == null) { 21305 return false; 21306 } 21307 synchronized(mPackages) { 21308 final PackageParser.Package pkg = mPackages.get(packageName); 21309 if (pkg == null) { 21310 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21311 throw new IllegalArgumentException("Unknown package: " + packageName); 21312 } 21313 IBinder ksh = ks.getToken(); 21314 if (ksh instanceof KeySetHandle) { 21315 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21316 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 21317 } 21318 return false; 21319 } 21320 } 21321 21322 @Override 21323 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 21324 if (packageName == null || ks == null) { 21325 return false; 21326 } 21327 synchronized(mPackages) { 21328 final PackageParser.Package pkg = mPackages.get(packageName); 21329 if (pkg == null) { 21330 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21331 throw new IllegalArgumentException("Unknown package: " + packageName); 21332 } 21333 IBinder ksh = ks.getToken(); 21334 if (ksh instanceof KeySetHandle) { 21335 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21336 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 21337 } 21338 return false; 21339 } 21340 } 21341 21342 private void deletePackageIfUnusedLPr(final String packageName) { 21343 PackageSetting ps = mSettings.mPackages.get(packageName); 21344 if (ps == null) { 21345 return; 21346 } 21347 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 21348 // TODO Implement atomic delete if package is unused 21349 // It is currently possible that the package will be deleted even if it is installed 21350 // after this method returns. 21351 mHandler.post(new Runnable() { 21352 public void run() { 21353 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 21354 } 21355 }); 21356 } 21357 } 21358 21359 /** 21360 * Check and throw if the given before/after packages would be considered a 21361 * downgrade. 21362 */ 21363 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 21364 throws PackageManagerException { 21365 if (after.versionCode < before.mVersionCode) { 21366 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21367 "Update version code " + after.versionCode + " is older than current " 21368 + before.mVersionCode); 21369 } else if (after.versionCode == before.mVersionCode) { 21370 if (after.baseRevisionCode < before.baseRevisionCode) { 21371 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21372 "Update base revision code " + after.baseRevisionCode 21373 + " is older than current " + before.baseRevisionCode); 21374 } 21375 21376 if (!ArrayUtils.isEmpty(after.splitNames)) { 21377 for (int i = 0; i < after.splitNames.length; i++) { 21378 final String splitName = after.splitNames[i]; 21379 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 21380 if (j != -1) { 21381 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 21382 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21383 "Update split " + splitName + " revision code " 21384 + after.splitRevisionCodes[i] + " is older than current " 21385 + before.splitRevisionCodes[j]); 21386 } 21387 } 21388 } 21389 } 21390 } 21391 } 21392 21393 private static class MoveCallbacks extends Handler { 21394 private static final int MSG_CREATED = 1; 21395 private static final int MSG_STATUS_CHANGED = 2; 21396 21397 private final RemoteCallbackList<IPackageMoveObserver> 21398 mCallbacks = new RemoteCallbackList<>(); 21399 21400 private final SparseIntArray mLastStatus = new SparseIntArray(); 21401 21402 public MoveCallbacks(Looper looper) { 21403 super(looper); 21404 } 21405 21406 public void register(IPackageMoveObserver callback) { 21407 mCallbacks.register(callback); 21408 } 21409 21410 public void unregister(IPackageMoveObserver callback) { 21411 mCallbacks.unregister(callback); 21412 } 21413 21414 @Override 21415 public void handleMessage(Message msg) { 21416 final SomeArgs args = (SomeArgs) msg.obj; 21417 final int n = mCallbacks.beginBroadcast(); 21418 for (int i = 0; i < n; i++) { 21419 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 21420 try { 21421 invokeCallback(callback, msg.what, args); 21422 } catch (RemoteException ignored) { 21423 } 21424 } 21425 mCallbacks.finishBroadcast(); 21426 args.recycle(); 21427 } 21428 21429 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 21430 throws RemoteException { 21431 switch (what) { 21432 case MSG_CREATED: { 21433 callback.onCreated(args.argi1, (Bundle) args.arg2); 21434 break; 21435 } 21436 case MSG_STATUS_CHANGED: { 21437 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 21438 break; 21439 } 21440 } 21441 } 21442 21443 private void notifyCreated(int moveId, Bundle extras) { 21444 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 21445 21446 final SomeArgs args = SomeArgs.obtain(); 21447 args.argi1 = moveId; 21448 args.arg2 = extras; 21449 obtainMessage(MSG_CREATED, args).sendToTarget(); 21450 } 21451 21452 private void notifyStatusChanged(int moveId, int status) { 21453 notifyStatusChanged(moveId, status, -1); 21454 } 21455 21456 private void notifyStatusChanged(int moveId, int status, long estMillis) { 21457 Slog.v(TAG, "Move " + moveId + " status " + status); 21458 21459 final SomeArgs args = SomeArgs.obtain(); 21460 args.argi1 = moveId; 21461 args.argi2 = status; 21462 args.arg3 = estMillis; 21463 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 21464 21465 synchronized (mLastStatus) { 21466 mLastStatus.put(moveId, status); 21467 } 21468 } 21469 } 21470 21471 private final static class OnPermissionChangeListeners extends Handler { 21472 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 21473 21474 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 21475 new RemoteCallbackList<>(); 21476 21477 public OnPermissionChangeListeners(Looper looper) { 21478 super(looper); 21479 } 21480 21481 @Override 21482 public void handleMessage(Message msg) { 21483 switch (msg.what) { 21484 case MSG_ON_PERMISSIONS_CHANGED: { 21485 final int uid = msg.arg1; 21486 handleOnPermissionsChanged(uid); 21487 } break; 21488 } 21489 } 21490 21491 public void addListenerLocked(IOnPermissionsChangeListener listener) { 21492 mPermissionListeners.register(listener); 21493 21494 } 21495 21496 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 21497 mPermissionListeners.unregister(listener); 21498 } 21499 21500 public void onPermissionsChanged(int uid) { 21501 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 21502 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 21503 } 21504 } 21505 21506 private void handleOnPermissionsChanged(int uid) { 21507 final int count = mPermissionListeners.beginBroadcast(); 21508 try { 21509 for (int i = 0; i < count; i++) { 21510 IOnPermissionsChangeListener callback = mPermissionListeners 21511 .getBroadcastItem(i); 21512 try { 21513 callback.onPermissionsChanged(uid); 21514 } catch (RemoteException e) { 21515 Log.e(TAG, "Permission listener is dead", e); 21516 } 21517 } 21518 } finally { 21519 mPermissionListeners.finishBroadcast(); 21520 } 21521 } 21522 } 21523 21524 private class PackageManagerInternalImpl extends PackageManagerInternal { 21525 @Override 21526 public void setLocationPackagesProvider(PackagesProvider provider) { 21527 synchronized (mPackages) { 21528 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 21529 } 21530 } 21531 21532 @Override 21533 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 21534 synchronized (mPackages) { 21535 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 21536 } 21537 } 21538 21539 @Override 21540 public void setSmsAppPackagesProvider(PackagesProvider provider) { 21541 synchronized (mPackages) { 21542 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 21543 } 21544 } 21545 21546 @Override 21547 public void setDialerAppPackagesProvider(PackagesProvider provider) { 21548 synchronized (mPackages) { 21549 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 21550 } 21551 } 21552 21553 @Override 21554 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 21555 synchronized (mPackages) { 21556 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 21557 } 21558 } 21559 21560 @Override 21561 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 21562 synchronized (mPackages) { 21563 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 21564 } 21565 } 21566 21567 @Override 21568 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 21569 synchronized (mPackages) { 21570 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 21571 packageName, userId); 21572 } 21573 } 21574 21575 @Override 21576 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 21577 synchronized (mPackages) { 21578 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 21579 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 21580 packageName, userId); 21581 } 21582 } 21583 21584 @Override 21585 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 21586 synchronized (mPackages) { 21587 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 21588 packageName, userId); 21589 } 21590 } 21591 21592 @Override 21593 public void setKeepUninstalledPackages(final List<String> packageList) { 21594 Preconditions.checkNotNull(packageList); 21595 List<String> removedFromList = null; 21596 synchronized (mPackages) { 21597 if (mKeepUninstalledPackages != null) { 21598 final int packagesCount = mKeepUninstalledPackages.size(); 21599 for (int i = 0; i < packagesCount; i++) { 21600 String oldPackage = mKeepUninstalledPackages.get(i); 21601 if (packageList != null && packageList.contains(oldPackage)) { 21602 continue; 21603 } 21604 if (removedFromList == null) { 21605 removedFromList = new ArrayList<>(); 21606 } 21607 removedFromList.add(oldPackage); 21608 } 21609 } 21610 mKeepUninstalledPackages = new ArrayList<>(packageList); 21611 if (removedFromList != null) { 21612 final int removedCount = removedFromList.size(); 21613 for (int i = 0; i < removedCount; i++) { 21614 deletePackageIfUnusedLPr(removedFromList.get(i)); 21615 } 21616 } 21617 } 21618 } 21619 21620 @Override 21621 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21622 synchronized (mPackages) { 21623 // If we do not support permission review, done. 21624 if (!mPermissionReviewRequired) { 21625 return false; 21626 } 21627 21628 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21629 if (packageSetting == null) { 21630 return false; 21631 } 21632 21633 // Permission review applies only to apps not supporting the new permission model. 21634 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21635 return false; 21636 } 21637 21638 // Legacy apps have the permission and get user consent on launch. 21639 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21640 return permissionsState.isPermissionReviewRequired(userId); 21641 } 21642 } 21643 21644 @Override 21645 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21646 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21647 } 21648 21649 @Override 21650 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21651 int userId) { 21652 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21653 } 21654 21655 @Override 21656 public void setDeviceAndProfileOwnerPackages( 21657 int deviceOwnerUserId, String deviceOwnerPackage, 21658 SparseArray<String> profileOwnerPackages) { 21659 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21660 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21661 } 21662 21663 @Override 21664 public boolean isPackageDataProtected(int userId, String packageName) { 21665 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21666 } 21667 21668 @Override 21669 public boolean isPackageEphemeral(int userId, String packageName) { 21670 synchronized (mPackages) { 21671 PackageParser.Package p = mPackages.get(packageName); 21672 return p != null ? p.applicationInfo.isEphemeralApp() : false; 21673 } 21674 } 21675 21676 @Override 21677 public boolean wasPackageEverLaunched(String packageName, int userId) { 21678 synchronized (mPackages) { 21679 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21680 } 21681 } 21682 21683 @Override 21684 public void grantRuntimePermission(String packageName, String name, int userId, 21685 boolean overridePolicy) { 21686 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 21687 overridePolicy); 21688 } 21689 21690 @Override 21691 public void revokeRuntimePermission(String packageName, String name, int userId, 21692 boolean overridePolicy) { 21693 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 21694 overridePolicy); 21695 } 21696 21697 @Override 21698 public String getNameForUid(int uid) { 21699 return PackageManagerService.this.getNameForUid(uid); 21700 } 21701 21702 @Override 21703 public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 21704 Intent origIntent, String resolvedType, Intent launchIntent, 21705 String callingPackage, int userId) { 21706 PackageManagerService.this.requestEphemeralResolutionPhaseTwo( 21707 responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId); 21708 } 21709 21710 public String getSetupWizardPackageName() { 21711 return mSetupWizardPackage; 21712 } 21713 } 21714 21715 @Override 21716 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21717 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21718 synchronized (mPackages) { 21719 final long identity = Binder.clearCallingIdentity(); 21720 try { 21721 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21722 packageNames, userId); 21723 } finally { 21724 Binder.restoreCallingIdentity(identity); 21725 } 21726 } 21727 } 21728 21729 private static void enforceSystemOrPhoneCaller(String tag) { 21730 int callingUid = Binder.getCallingUid(); 21731 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21732 throw new SecurityException( 21733 "Cannot call " + tag + " from UID " + callingUid); 21734 } 21735 } 21736 21737 boolean isHistoricalPackageUsageAvailable() { 21738 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21739 } 21740 21741 /** 21742 * Return a <b>copy</b> of the collection of packages known to the package manager. 21743 * @return A copy of the values of mPackages. 21744 */ 21745 Collection<PackageParser.Package> getPackages() { 21746 synchronized (mPackages) { 21747 return new ArrayList<>(mPackages.values()); 21748 } 21749 } 21750 21751 /** 21752 * Logs process start information (including base APK hash) to the security log. 21753 * @hide 21754 */ 21755 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21756 String apkFile, int pid) { 21757 if (!SecurityLog.isLoggingEnabled()) { 21758 return; 21759 } 21760 Bundle data = new Bundle(); 21761 data.putLong("startTimestamp", System.currentTimeMillis()); 21762 data.putString("processName", processName); 21763 data.putInt("uid", uid); 21764 data.putString("seinfo", seinfo); 21765 data.putString("apkFile", apkFile); 21766 data.putInt("pid", pid); 21767 Message msg = mProcessLoggingHandler.obtainMessage( 21768 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21769 msg.setData(data); 21770 mProcessLoggingHandler.sendMessage(msg); 21771 } 21772 21773 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21774 return mCompilerStats.getPackageStats(pkgName); 21775 } 21776 21777 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21778 return getOrCreateCompilerPackageStats(pkg.packageName); 21779 } 21780 21781 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21782 return mCompilerStats.getOrCreatePackageStats(pkgName); 21783 } 21784 21785 public void deleteCompilerPackageStats(String pkgName) { 21786 mCompilerStats.deletePackageStats(pkgName); 21787 } 21788} 21789