PackageManagerService.java revision fd6f4fb264d56726cd0e2fed731ad60bbe4aa06f
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 61import static android.content.pm.PackageManager.MATCH_ALL; 62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 63import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 65import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 66import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 74import static android.content.pm.PackageManager.PERMISSION_DENIED; 75import static android.content.pm.PackageManager.PERMISSION_GRANTED; 76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 77import static android.content.pm.PackageParser.isApkFile; 78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 79import static android.system.OsConstants.O_CREAT; 80import static android.system.OsConstants.O_RDWR; 81 82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 86import static com.android.internal.util.ArrayUtils.appendInt; 87import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 93import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 99 100import android.Manifest; 101import android.annotation.NonNull; 102import android.annotation.Nullable; 103import android.app.ActivityManager; 104import android.app.IActivityManager; 105import android.app.ResourcesManager; 106import android.app.admin.IDevicePolicyManager; 107import android.app.admin.SecurityLog; 108import android.app.backup.IBackupManager; 109import android.content.BroadcastReceiver; 110import android.content.ComponentName; 111import android.content.ContentResolver; 112import android.content.Context; 113import android.content.IIntentReceiver; 114import android.content.Intent; 115import android.content.IntentFilter; 116import android.content.IntentSender; 117import android.content.IntentSender.SendIntentException; 118import android.content.ServiceConnection; 119import android.content.pm.ActivityInfo; 120import android.content.pm.ApplicationInfo; 121import android.content.pm.AppsQueryHelper; 122import android.content.pm.ComponentInfo; 123import android.content.pm.EphemeralApplicationInfo; 124import android.content.pm.EphemeralRequest; 125import android.content.pm.EphemeralResolveInfo; 126import android.content.pm.EphemeralResponse; 127import android.content.pm.FeatureInfo; 128import android.content.pm.IOnPermissionsChangeListener; 129import android.content.pm.IPackageDataObserver; 130import android.content.pm.IPackageDeleteObserver; 131import android.content.pm.IPackageDeleteObserver2; 132import android.content.pm.IPackageInstallObserver2; 133import android.content.pm.IPackageInstaller; 134import android.content.pm.IPackageManager; 135import android.content.pm.IPackageMoveObserver; 136import android.content.pm.IPackageStatsObserver; 137import android.content.pm.InstrumentationInfo; 138import android.content.pm.IntentFilterVerificationInfo; 139import android.content.pm.KeySet; 140import android.content.pm.PackageCleanItem; 141import android.content.pm.PackageInfo; 142import android.content.pm.PackageInfoLite; 143import android.content.pm.PackageInstaller; 144import android.content.pm.PackageManager; 145import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 146import android.content.pm.PackageManagerInternal; 147import android.content.pm.PackageParser; 148import android.content.pm.PackageParser.ActivityIntentInfo; 149import android.content.pm.PackageParser.PackageLite; 150import android.content.pm.PackageParser.PackageParserException; 151import android.content.pm.PackageStats; 152import android.content.pm.PackageUserState; 153import android.content.pm.ParceledListSlice; 154import android.content.pm.PermissionGroupInfo; 155import android.content.pm.PermissionInfo; 156import android.content.pm.ProviderInfo; 157import android.content.pm.ResolveInfo; 158import android.content.pm.ServiceInfo; 159import android.content.pm.Signature; 160import android.content.pm.UserInfo; 161import android.content.pm.VerifierDeviceIdentity; 162import android.content.pm.VerifierInfo; 163import android.content.res.Resources; 164import android.graphics.Bitmap; 165import android.hardware.display.DisplayManager; 166import android.net.Uri; 167import android.os.Binder; 168import android.os.Build; 169import android.os.Bundle; 170import android.os.Debug; 171import android.os.Environment; 172import android.os.Environment.UserEnvironment; 173import android.os.FileUtils; 174import android.os.Handler; 175import android.os.IBinder; 176import android.os.Looper; 177import android.os.Message; 178import android.os.Parcel; 179import android.os.ParcelFileDescriptor; 180import android.os.PatternMatcher; 181import android.os.Process; 182import android.os.RemoteCallbackList; 183import android.os.RemoteException; 184import android.os.ResultReceiver; 185import android.os.SELinux; 186import android.os.ServiceManager; 187import android.os.ShellCallback; 188import android.os.SystemClock; 189import android.os.SystemProperties; 190import android.os.Trace; 191import android.os.UserHandle; 192import android.os.UserManager; 193import android.os.UserManagerInternal; 194import android.os.storage.IStorageManager; 195import android.os.storage.StorageManagerInternal; 196import android.os.storage.StorageEventListener; 197import android.os.storage.StorageManager; 198import android.os.storage.VolumeInfo; 199import android.os.storage.VolumeRecord; 200import android.provider.Settings.Global; 201import android.provider.Settings.Secure; 202import android.security.KeyStore; 203import android.security.SystemKeyStore; 204import android.system.ErrnoException; 205import android.system.Os; 206import android.text.TextUtils; 207import android.text.format.DateUtils; 208import android.util.ArrayMap; 209import android.util.ArraySet; 210import android.util.Base64; 211import android.util.DisplayMetrics; 212import android.util.EventLog; 213import android.util.ExceptionUtils; 214import android.util.Log; 215import android.util.LogPrinter; 216import android.util.MathUtils; 217import android.util.Pair; 218import android.util.PrintStreamPrinter; 219import android.util.Slog; 220import android.util.SparseArray; 221import android.util.SparseBooleanArray; 222import android.util.SparseIntArray; 223import android.util.Xml; 224import android.util.jar.StrictJarFile; 225import android.view.Display; 226 227import com.android.internal.R; 228import com.android.internal.annotations.GuardedBy; 229import com.android.internal.app.IMediaContainerService; 230import com.android.internal.app.ResolverActivity; 231import com.android.internal.content.NativeLibraryHelper; 232import com.android.internal.content.PackageHelper; 233import com.android.internal.logging.MetricsLogger; 234import com.android.internal.os.IParcelFileDescriptorFactory; 235import com.android.internal.os.InstallerConnection.InstallerException; 236import com.android.internal.os.RoSystemProperties; 237import com.android.internal.os.SomeArgs; 238import com.android.internal.os.Zygote; 239import com.android.internal.telephony.CarrierAppUtils; 240import com.android.internal.util.ArrayUtils; 241import com.android.internal.util.FastPrintWriter; 242import com.android.internal.util.FastXmlSerializer; 243import com.android.internal.util.IndentingPrintWriter; 244import com.android.internal.util.Preconditions; 245import com.android.internal.util.XmlUtils; 246import com.android.server.AttributeCache; 247import com.android.server.EventLogTags; 248import com.android.server.FgThread; 249import com.android.server.IntentResolver; 250import com.android.server.LocalServices; 251import com.android.server.ServiceThread; 252import com.android.server.SystemConfig; 253import com.android.server.Watchdog; 254import com.android.server.net.NetworkPolicyManagerInternal; 255import com.android.server.pm.PermissionsState.PermissionState; 256import com.android.server.pm.Settings.DatabaseVersion; 257import com.android.server.pm.Settings.VersionInfo; 258import com.android.server.storage.DeviceStorageMonitorInternal; 259 260import dalvik.system.CloseGuard; 261import dalvik.system.DexFile; 262import dalvik.system.VMRuntime; 263 264import libcore.io.IoUtils; 265import libcore.util.EmptyArray; 266 267import org.xmlpull.v1.XmlPullParser; 268import org.xmlpull.v1.XmlPullParserException; 269import org.xmlpull.v1.XmlSerializer; 270 271import java.io.BufferedOutputStream; 272import java.io.BufferedReader; 273import java.io.ByteArrayInputStream; 274import java.io.ByteArrayOutputStream; 275import java.io.File; 276import java.io.FileDescriptor; 277import java.io.FileInputStream; 278import java.io.FileNotFoundException; 279import java.io.FileOutputStream; 280import java.io.FileReader; 281import java.io.FilenameFilter; 282import java.io.IOException; 283import java.io.PrintWriter; 284import java.nio.charset.StandardCharsets; 285import java.security.DigestInputStream; 286import java.security.MessageDigest; 287import java.security.NoSuchAlgorithmException; 288import java.security.PublicKey; 289import java.security.SecureRandom; 290import java.security.cert.Certificate; 291import java.security.cert.CertificateEncodingException; 292import java.security.cert.CertificateException; 293import java.text.SimpleDateFormat; 294import java.util.ArrayList; 295import java.util.Arrays; 296import java.util.Collection; 297import java.util.Collections; 298import java.util.Comparator; 299import java.util.Date; 300import java.util.HashSet; 301import java.util.Iterator; 302import java.util.List; 303import java.util.Map; 304import java.util.Objects; 305import java.util.Set; 306import java.util.concurrent.CountDownLatch; 307import java.util.concurrent.TimeUnit; 308import java.util.concurrent.atomic.AtomicBoolean; 309import java.util.concurrent.atomic.AtomicInteger; 310 311/** 312 * Keep track of all those APKs everywhere. 313 * <p> 314 * Internally there are two important locks: 315 * <ul> 316 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 317 * and other related state. It is a fine-grained lock that should only be held 318 * momentarily, as it's one of the most contended locks in the system. 319 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 320 * operations typically involve heavy lifting of application data on disk. Since 321 * {@code installd} is single-threaded, and it's operations can often be slow, 322 * this lock should never be acquired while already holding {@link #mPackages}. 323 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 324 * holding {@link #mInstallLock}. 325 * </ul> 326 * Many internal methods rely on the caller to hold the appropriate locks, and 327 * this contract is expressed through method name suffixes: 328 * <ul> 329 * <li>fooLI(): the caller must hold {@link #mInstallLock} 330 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 331 * being modified must be frozen 332 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 333 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 334 * </ul> 335 * <p> 336 * Because this class is very central to the platform's security; please run all 337 * CTS and unit tests whenever making modifications: 338 * 339 * <pre> 340 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 341 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 342 * </pre> 343 */ 344public class PackageManagerService extends IPackageManager.Stub { 345 static final String TAG = "PackageManager"; 346 static final boolean DEBUG_SETTINGS = false; 347 static final boolean DEBUG_PREFERRED = false; 348 static final boolean DEBUG_UPGRADE = false; 349 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 350 private static final boolean DEBUG_BACKUP = false; 351 private static final boolean DEBUG_INSTALL = false; 352 private static final boolean DEBUG_REMOVE = false; 353 private static final boolean DEBUG_BROADCASTS = false; 354 private static final boolean DEBUG_SHOW_INFO = false; 355 private static final boolean DEBUG_PACKAGE_INFO = false; 356 private static final boolean DEBUG_INTENT_MATCHING = false; 357 private static final boolean DEBUG_PACKAGE_SCANNING = false; 358 private static final boolean DEBUG_VERIFY = false; 359 private static final boolean DEBUG_FILTERS = false; 360 361 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 362 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 363 // user, but by default initialize to this. 364 static final boolean DEBUG_DEXOPT = false; 365 366 private static final boolean DEBUG_ABI_SELECTION = false; 367 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 368 private static final boolean DEBUG_TRIAGED_MISSING = false; 369 private static final boolean DEBUG_APP_DATA = false; 370 371 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 372 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 373 374 private static final boolean DISABLE_EPHEMERAL_APPS = false; 375 private static final boolean HIDE_EPHEMERAL_APIS = true; 376 377 private static final int RADIO_UID = Process.PHONE_UID; 378 private static final int LOG_UID = Process.LOG_UID; 379 private static final int NFC_UID = Process.NFC_UID; 380 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 381 private static final int SHELL_UID = Process.SHELL_UID; 382 383 // Cap the size of permission trees that 3rd party apps can define 384 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 385 386 // Suffix used during package installation when copying/moving 387 // package apks to install directory. 388 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 389 390 static final int SCAN_NO_DEX = 1<<1; 391 static final int SCAN_FORCE_DEX = 1<<2; 392 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 393 static final int SCAN_NEW_INSTALL = 1<<4; 394 static final int SCAN_UPDATE_TIME = 1<<5; 395 static final int SCAN_BOOTING = 1<<6; 396 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 397 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 398 static final int SCAN_REPLACING = 1<<9; 399 static final int SCAN_REQUIRE_KNOWN = 1<<10; 400 static final int SCAN_MOVE = 1<<11; 401 static final int SCAN_INITIAL = 1<<12; 402 static final int SCAN_CHECK_ONLY = 1<<13; 403 static final int SCAN_DONT_KILL_APP = 1<<14; 404 static final int SCAN_IGNORE_FROZEN = 1<<15; 405 406 static final int REMOVE_CHATTY = 1<<16; 407 408 private static final int[] EMPTY_INT_ARRAY = new int[0]; 409 410 /** 411 * Timeout (in milliseconds) after which the watchdog should declare that 412 * our handler thread is wedged. The usual default for such things is one 413 * minute but we sometimes do very lengthy I/O operations on this thread, 414 * such as installing multi-gigabyte applications, so ours needs to be longer. 415 */ 416 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 417 418 /** 419 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 420 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 421 * settings entry if available, otherwise we use the hardcoded default. If it's been 422 * more than this long since the last fstrim, we force one during the boot sequence. 423 * 424 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 425 * one gets run at the next available charging+idle time. This final mandatory 426 * no-fstrim check kicks in only of the other scheduling criteria is never met. 427 */ 428 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 429 430 /** 431 * Whether verification is enabled by default. 432 */ 433 private static final boolean DEFAULT_VERIFY_ENABLE = true; 434 435 /** 436 * The default maximum time to wait for the verification agent to return in 437 * milliseconds. 438 */ 439 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 440 441 /** 442 * The default response for package verification timeout. 443 * 444 * This can be either PackageManager.VERIFICATION_ALLOW or 445 * PackageManager.VERIFICATION_REJECT. 446 */ 447 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 448 449 static final String PLATFORM_PACKAGE_NAME = "android"; 450 451 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 452 453 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 454 DEFAULT_CONTAINER_PACKAGE, 455 "com.android.defcontainer.DefaultContainerService"); 456 457 private static final String KILL_APP_REASON_GIDS_CHANGED = 458 "permission grant or revoke changed gids"; 459 460 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 461 "permissions revoked"; 462 463 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 464 465 private static final String PACKAGE_SCHEME = "package"; 466 467 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 468 /** 469 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 470 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 471 * VENDOR_OVERLAY_DIR. 472 */ 473 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 474 /** 475 * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever 476 * is in VENDOR_OVERLAY_THEME_PROPERTY. 477 */ 478 private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY 479 = "persist.vendor.overlay.theme"; 480 481 /** Permission grant: not grant the permission. */ 482 private static final int GRANT_DENIED = 1; 483 484 /** Permission grant: grant the permission as an install permission. */ 485 private static final int GRANT_INSTALL = 2; 486 487 /** Permission grant: grant the permission as a runtime one. */ 488 private static final int GRANT_RUNTIME = 3; 489 490 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 491 private static final int GRANT_UPGRADE = 4; 492 493 /** Canonical intent used to identify what counts as a "web browser" app */ 494 private static final Intent sBrowserIntent; 495 static { 496 sBrowserIntent = new Intent(); 497 sBrowserIntent.setAction(Intent.ACTION_VIEW); 498 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 499 sBrowserIntent.setData(Uri.parse("http:")); 500 } 501 502 /** 503 * The set of all protected actions [i.e. those actions for which a high priority 504 * intent filter is disallowed]. 505 */ 506 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 507 static { 508 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 509 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 510 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 511 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 512 } 513 514 // Compilation reasons. 515 public static final int REASON_FIRST_BOOT = 0; 516 public static final int REASON_BOOT = 1; 517 public static final int REASON_INSTALL = 2; 518 public static final int REASON_BACKGROUND_DEXOPT = 3; 519 public static final int REASON_AB_OTA = 4; 520 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 521 public static final int REASON_SHARED_APK = 6; 522 public static final int REASON_FORCED_DEXOPT = 7; 523 public static final int REASON_CORE_APP = 8; 524 525 public static final int REASON_LAST = REASON_CORE_APP; 526 527 /** Special library name that skips shared libraries check during compilation. */ 528 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 529 530 final ServiceThread mHandlerThread; 531 532 final PackageHandler mHandler; 533 534 private final ProcessLoggingHandler mProcessLoggingHandler; 535 536 /** 537 * Messages for {@link #mHandler} that need to wait for system ready before 538 * being dispatched. 539 */ 540 private ArrayList<Message> mPostSystemReadyMessages; 541 542 final int mSdkVersion = Build.VERSION.SDK_INT; 543 544 final Context mContext; 545 final boolean mFactoryTest; 546 final boolean mOnlyCore; 547 final DisplayMetrics mMetrics; 548 final int mDefParseFlags; 549 final String[] mSeparateProcesses; 550 final boolean mIsUpgrade; 551 final boolean mIsPreNUpgrade; 552 final boolean mIsPreNMR1Upgrade; 553 554 @GuardedBy("mPackages") 555 private boolean mDexOptDialogShown; 556 557 /** The location for ASEC container files on internal storage. */ 558 final String mAsecInternalPath; 559 560 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 561 // LOCK HELD. Can be called with mInstallLock held. 562 @GuardedBy("mInstallLock") 563 final Installer mInstaller; 564 565 /** Directory where installed third-party apps stored */ 566 final File mAppInstallDir; 567 final File mEphemeralInstallDir; 568 569 /** 570 * Directory to which applications installed internally have their 571 * 32 bit native libraries copied. 572 */ 573 private File mAppLib32InstallDir; 574 575 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 576 // apps. 577 final File mDrmAppPrivateInstallDir; 578 579 // ---------------------------------------------------------------- 580 581 // Lock for state used when installing and doing other long running 582 // operations. Methods that must be called with this lock held have 583 // the suffix "LI". 584 final Object mInstallLock = new Object(); 585 586 // ---------------------------------------------------------------- 587 588 // Keys are String (package name), values are Package. This also serves 589 // as the lock for the global state. Methods that must be called with 590 // this lock held have the prefix "LP". 591 @GuardedBy("mPackages") 592 final ArrayMap<String, PackageParser.Package> mPackages = 593 new ArrayMap<String, PackageParser.Package>(); 594 595 final ArrayMap<String, Set<String>> mKnownCodebase = 596 new ArrayMap<String, Set<String>>(); 597 598 // Tracks available target package names -> overlay package paths. 599 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 600 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 601 602 /** 603 * Tracks new system packages [received in an OTA] that we expect to 604 * find updated user-installed versions. Keys are package name, values 605 * are package location. 606 */ 607 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 608 /** 609 * Tracks high priority intent filters for protected actions. During boot, certain 610 * filter actions are protected and should never be allowed to have a high priority 611 * intent filter for them. However, there is one, and only one exception -- the 612 * setup wizard. It must be able to define a high priority intent filter for these 613 * actions to ensure there are no escapes from the wizard. We need to delay processing 614 * of these during boot as we need to look at all of the system packages in order 615 * to know which component is the setup wizard. 616 */ 617 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 618 /** 619 * Whether or not processing protected filters should be deferred. 620 */ 621 private boolean mDeferProtectedFilters = true; 622 623 /** 624 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 625 */ 626 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 627 /** 628 * Whether or not system app permissions should be promoted from install to runtime. 629 */ 630 boolean mPromoteSystemApps; 631 632 @GuardedBy("mPackages") 633 final Settings mSettings; 634 635 /** 636 * Set of package names that are currently "frozen", which means active 637 * surgery is being done on the code/data for that package. The platform 638 * will refuse to launch frozen packages to avoid race conditions. 639 * 640 * @see PackageFreezer 641 */ 642 @GuardedBy("mPackages") 643 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 644 645 final ProtectedPackages mProtectedPackages; 646 647 boolean mFirstBoot; 648 649 // System configuration read by SystemConfig. 650 final int[] mGlobalGids; 651 final SparseArray<ArraySet<String>> mSystemPermissions; 652 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 653 654 // If mac_permissions.xml was found for seinfo labeling. 655 boolean mFoundPolicyFile; 656 657 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 658 659 public static final class SharedLibraryEntry { 660 public final String path; 661 public final String apk; 662 663 SharedLibraryEntry(String _path, String _apk) { 664 path = _path; 665 apk = _apk; 666 } 667 } 668 669 // Currently known shared libraries. 670 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 671 new ArrayMap<String, SharedLibraryEntry>(); 672 673 // All available activities, for your resolving pleasure. 674 final ActivityIntentResolver mActivities = 675 new ActivityIntentResolver(); 676 677 // All available receivers, for your resolving pleasure. 678 final ActivityIntentResolver mReceivers = 679 new ActivityIntentResolver(); 680 681 // All available services, for your resolving pleasure. 682 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 683 684 // All available providers, for your resolving pleasure. 685 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 686 687 // Mapping from provider base names (first directory in content URI codePath) 688 // to the provider information. 689 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 690 new ArrayMap<String, PackageParser.Provider>(); 691 692 // Mapping from instrumentation class names to info about them. 693 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 694 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 695 696 // Mapping from permission names to info about them. 697 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 698 new ArrayMap<String, PackageParser.PermissionGroup>(); 699 700 // Packages whose data we have transfered into another package, thus 701 // should no longer exist. 702 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 703 704 // Broadcast actions that are only available to the system. 705 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 706 707 /** List of packages waiting for verification. */ 708 final SparseArray<PackageVerificationState> mPendingVerification 709 = new SparseArray<PackageVerificationState>(); 710 711 /** Set of packages associated with each app op permission. */ 712 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 713 714 final PackageInstallerService mInstallerService; 715 716 private final PackageDexOptimizer mPackageDexOptimizer; 717 718 private AtomicInteger mNextMoveId = new AtomicInteger(); 719 private final MoveCallbacks mMoveCallbacks; 720 721 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 722 723 // Cache of users who need badging. 724 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 725 726 /** Token for keys in mPendingVerification. */ 727 private int mPendingVerificationToken = 0; 728 729 volatile boolean mSystemReady; 730 volatile boolean mSafeMode; 731 volatile boolean mHasSystemUidErrors; 732 733 ApplicationInfo mAndroidApplication; 734 final ActivityInfo mResolveActivity = new ActivityInfo(); 735 final ResolveInfo mResolveInfo = new ResolveInfo(); 736 ComponentName mResolveComponentName; 737 PackageParser.Package mPlatformPackage; 738 ComponentName mCustomResolverComponentName; 739 740 boolean mResolverReplaced = false; 741 742 private final @Nullable ComponentName mIntentFilterVerifierComponent; 743 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 744 745 private int mIntentFilterVerificationToken = 0; 746 747 /** Component that knows whether or not an ephemeral application exists */ 748 final ComponentName mEphemeralResolverComponent; 749 /** The service connection to the ephemeral resolver */ 750 final EphemeralResolverConnection mEphemeralResolverConnection; 751 752 /** Component used to install ephemeral applications */ 753 final ComponentName mEphemeralInstallerComponent; 754 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 755 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 756 757 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 758 = new SparseArray<IntentFilterVerificationState>(); 759 760 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 761 762 // List of packages names to keep cached, even if they are uninstalled for all users 763 private List<String> mKeepUninstalledPackages; 764 765 private UserManagerInternal mUserManagerInternal; 766 767 private static class IFVerificationParams { 768 PackageParser.Package pkg; 769 boolean replacing; 770 int userId; 771 int verifierUid; 772 773 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 774 int _userId, int _verifierUid) { 775 pkg = _pkg; 776 replacing = _replacing; 777 userId = _userId; 778 replacing = _replacing; 779 verifierUid = _verifierUid; 780 } 781 } 782 783 private interface IntentFilterVerifier<T extends IntentFilter> { 784 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 785 T filter, String packageName); 786 void startVerifications(int userId); 787 void receiveVerificationResponse(int verificationId); 788 } 789 790 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 791 private Context mContext; 792 private ComponentName mIntentFilterVerifierComponent; 793 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 794 795 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 796 mContext = context; 797 mIntentFilterVerifierComponent = verifierComponent; 798 } 799 800 private String getDefaultScheme() { 801 return IntentFilter.SCHEME_HTTPS; 802 } 803 804 @Override 805 public void startVerifications(int userId) { 806 // Launch verifications requests 807 int count = mCurrentIntentFilterVerifications.size(); 808 for (int n=0; n<count; n++) { 809 int verificationId = mCurrentIntentFilterVerifications.get(n); 810 final IntentFilterVerificationState ivs = 811 mIntentFilterVerificationStates.get(verificationId); 812 813 String packageName = ivs.getPackageName(); 814 815 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 816 final int filterCount = filters.size(); 817 ArraySet<String> domainsSet = new ArraySet<>(); 818 for (int m=0; m<filterCount; m++) { 819 PackageParser.ActivityIntentInfo filter = filters.get(m); 820 domainsSet.addAll(filter.getHostsList()); 821 } 822 synchronized (mPackages) { 823 if (mSettings.createIntentFilterVerificationIfNeededLPw( 824 packageName, domainsSet) != null) { 825 scheduleWriteSettingsLocked(); 826 } 827 } 828 sendVerificationRequest(userId, verificationId, ivs); 829 } 830 mCurrentIntentFilterVerifications.clear(); 831 } 832 833 private void sendVerificationRequest(int userId, int verificationId, 834 IntentFilterVerificationState ivs) { 835 836 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 837 verificationIntent.putExtra( 838 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 839 verificationId); 840 verificationIntent.putExtra( 841 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 842 getDefaultScheme()); 843 verificationIntent.putExtra( 844 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 845 ivs.getHostsString()); 846 verificationIntent.putExtra( 847 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 848 ivs.getPackageName()); 849 verificationIntent.setComponent(mIntentFilterVerifierComponent); 850 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 851 852 UserHandle user = new UserHandle(userId); 853 mContext.sendBroadcastAsUser(verificationIntent, user); 854 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 855 "Sending IntentFilter verification broadcast"); 856 } 857 858 public void receiveVerificationResponse(int verificationId) { 859 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 860 861 final boolean verified = ivs.isVerified(); 862 863 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 864 final int count = filters.size(); 865 if (DEBUG_DOMAIN_VERIFICATION) { 866 Slog.i(TAG, "Received verification response " + verificationId 867 + " for " + count + " filters, verified=" + verified); 868 } 869 for (int n=0; n<count; n++) { 870 PackageParser.ActivityIntentInfo filter = filters.get(n); 871 filter.setVerified(verified); 872 873 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 874 + " verified with result:" + verified + " and hosts:" 875 + ivs.getHostsString()); 876 } 877 878 mIntentFilterVerificationStates.remove(verificationId); 879 880 final String packageName = ivs.getPackageName(); 881 IntentFilterVerificationInfo ivi = null; 882 883 synchronized (mPackages) { 884 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 885 } 886 if (ivi == null) { 887 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 888 + verificationId + " packageName:" + packageName); 889 return; 890 } 891 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 892 "Updating IntentFilterVerificationInfo for package " + packageName 893 +" verificationId:" + verificationId); 894 895 synchronized (mPackages) { 896 if (verified) { 897 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 898 } else { 899 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 900 } 901 scheduleWriteSettingsLocked(); 902 903 final int userId = ivs.getUserId(); 904 if (userId != UserHandle.USER_ALL) { 905 final int userStatus = 906 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 907 908 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 909 boolean needUpdate = false; 910 911 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 912 // already been set by the User thru the Disambiguation dialog 913 switch (userStatus) { 914 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 915 if (verified) { 916 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 917 } else { 918 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 919 } 920 needUpdate = true; 921 break; 922 923 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 924 if (verified) { 925 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 926 needUpdate = true; 927 } 928 break; 929 930 default: 931 // Nothing to do 932 } 933 934 if (needUpdate) { 935 mSettings.updateIntentFilterVerificationStatusLPw( 936 packageName, updatedStatus, userId); 937 scheduleWritePackageRestrictionsLocked(userId); 938 } 939 } 940 } 941 } 942 943 @Override 944 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 945 ActivityIntentInfo filter, String packageName) { 946 if (!hasValidDomains(filter)) { 947 return false; 948 } 949 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 950 if (ivs == null) { 951 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 952 packageName); 953 } 954 if (DEBUG_DOMAIN_VERIFICATION) { 955 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 956 } 957 ivs.addFilter(filter); 958 return true; 959 } 960 961 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 962 int userId, int verificationId, String packageName) { 963 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 964 verifierUid, userId, packageName); 965 ivs.setPendingState(); 966 synchronized (mPackages) { 967 mIntentFilterVerificationStates.append(verificationId, ivs); 968 mCurrentIntentFilterVerifications.add(verificationId); 969 } 970 return ivs; 971 } 972 } 973 974 private static boolean hasValidDomains(ActivityIntentInfo filter) { 975 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 976 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 977 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 978 } 979 980 // Set of pending broadcasts for aggregating enable/disable of components. 981 static class PendingPackageBroadcasts { 982 // for each user id, a map of <package name -> components within that package> 983 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 984 985 public PendingPackageBroadcasts() { 986 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 987 } 988 989 public ArrayList<String> get(int userId, String packageName) { 990 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 991 return packages.get(packageName); 992 } 993 994 public void put(int userId, String packageName, ArrayList<String> components) { 995 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 996 packages.put(packageName, components); 997 } 998 999 public void remove(int userId, String packageName) { 1000 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1001 if (packages != null) { 1002 packages.remove(packageName); 1003 } 1004 } 1005 1006 public void remove(int userId) { 1007 mUidMap.remove(userId); 1008 } 1009 1010 public int userIdCount() { 1011 return mUidMap.size(); 1012 } 1013 1014 public int userIdAt(int n) { 1015 return mUidMap.keyAt(n); 1016 } 1017 1018 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1019 return mUidMap.get(userId); 1020 } 1021 1022 public int size() { 1023 // total number of pending broadcast entries across all userIds 1024 int num = 0; 1025 for (int i = 0; i< mUidMap.size(); i++) { 1026 num += mUidMap.valueAt(i).size(); 1027 } 1028 return num; 1029 } 1030 1031 public void clear() { 1032 mUidMap.clear(); 1033 } 1034 1035 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1036 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1037 if (map == null) { 1038 map = new ArrayMap<String, ArrayList<String>>(); 1039 mUidMap.put(userId, map); 1040 } 1041 return map; 1042 } 1043 } 1044 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1045 1046 // Service Connection to remote media container service to copy 1047 // package uri's from external media onto secure containers 1048 // or internal storage. 1049 private IMediaContainerService mContainerService = null; 1050 1051 static final int SEND_PENDING_BROADCAST = 1; 1052 static final int MCS_BOUND = 3; 1053 static final int END_COPY = 4; 1054 static final int INIT_COPY = 5; 1055 static final int MCS_UNBIND = 6; 1056 static final int START_CLEANING_PACKAGE = 7; 1057 static final int FIND_INSTALL_LOC = 8; 1058 static final int POST_INSTALL = 9; 1059 static final int MCS_RECONNECT = 10; 1060 static final int MCS_GIVE_UP = 11; 1061 static final int UPDATED_MEDIA_STATUS = 12; 1062 static final int WRITE_SETTINGS = 13; 1063 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1064 static final int PACKAGE_VERIFIED = 15; 1065 static final int CHECK_PENDING_VERIFICATION = 16; 1066 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1067 static final int INTENT_FILTER_VERIFIED = 18; 1068 static final int WRITE_PACKAGE_LIST = 19; 1069 static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20; 1070 1071 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1072 1073 // Delay time in millisecs 1074 static final int BROADCAST_DELAY = 10 * 1000; 1075 1076 static UserManagerService sUserManager; 1077 1078 // Stores a list of users whose package restrictions file needs to be updated 1079 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1080 1081 final private DefaultContainerConnection mDefContainerConn = 1082 new DefaultContainerConnection(); 1083 class DefaultContainerConnection implements ServiceConnection { 1084 public void onServiceConnected(ComponentName name, IBinder service) { 1085 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1086 final IMediaContainerService imcs = IMediaContainerService.Stub 1087 .asInterface(Binder.allowBlocking(service)); 1088 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1089 } 1090 1091 public void onServiceDisconnected(ComponentName name) { 1092 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1093 } 1094 } 1095 1096 // Recordkeeping of restore-after-install operations that are currently in flight 1097 // between the Package Manager and the Backup Manager 1098 static class PostInstallData { 1099 public InstallArgs args; 1100 public PackageInstalledInfo res; 1101 1102 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1103 args = _a; 1104 res = _r; 1105 } 1106 } 1107 1108 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1109 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1110 1111 // XML tags for backup/restore of various bits of state 1112 private static final String TAG_PREFERRED_BACKUP = "pa"; 1113 private static final String TAG_DEFAULT_APPS = "da"; 1114 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1115 1116 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1117 private static final String TAG_ALL_GRANTS = "rt-grants"; 1118 private static final String TAG_GRANT = "grant"; 1119 private static final String ATTR_PACKAGE_NAME = "pkg"; 1120 1121 private static final String TAG_PERMISSION = "perm"; 1122 private static final String ATTR_PERMISSION_NAME = "name"; 1123 private static final String ATTR_IS_GRANTED = "g"; 1124 private static final String ATTR_USER_SET = "set"; 1125 private static final String ATTR_USER_FIXED = "fixed"; 1126 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1127 1128 // System/policy permission grants are not backed up 1129 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1130 FLAG_PERMISSION_POLICY_FIXED 1131 | FLAG_PERMISSION_SYSTEM_FIXED 1132 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1133 1134 // And we back up these user-adjusted states 1135 private static final int USER_RUNTIME_GRANT_MASK = 1136 FLAG_PERMISSION_USER_SET 1137 | FLAG_PERMISSION_USER_FIXED 1138 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1139 1140 final @Nullable String mRequiredVerifierPackage; 1141 final @NonNull String mRequiredInstallerPackage; 1142 final @NonNull String mRequiredUninstallerPackage; 1143 final @Nullable String mSetupWizardPackage; 1144 final @Nullable String mStorageManagerPackage; 1145 final @NonNull String mServicesSystemSharedLibraryPackageName; 1146 final @NonNull String mSharedSystemSharedLibraryPackageName; 1147 1148 final boolean mPermissionReviewRequired; 1149 1150 private final PackageUsage mPackageUsage = new PackageUsage(); 1151 private final CompilerStats mCompilerStats = new CompilerStats(); 1152 1153 class PackageHandler extends Handler { 1154 private boolean mBound = false; 1155 final ArrayList<HandlerParams> mPendingInstalls = 1156 new ArrayList<HandlerParams>(); 1157 1158 private boolean connectToService() { 1159 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1160 " DefaultContainerService"); 1161 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1162 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1163 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1164 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1165 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1166 mBound = true; 1167 return true; 1168 } 1169 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1170 return false; 1171 } 1172 1173 private void disconnectService() { 1174 mContainerService = null; 1175 mBound = false; 1176 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1177 mContext.unbindService(mDefContainerConn); 1178 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1179 } 1180 1181 PackageHandler(Looper looper) { 1182 super(looper); 1183 } 1184 1185 public void handleMessage(Message msg) { 1186 try { 1187 doHandleMessage(msg); 1188 } finally { 1189 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1190 } 1191 } 1192 1193 void doHandleMessage(Message msg) { 1194 switch (msg.what) { 1195 case INIT_COPY: { 1196 HandlerParams params = (HandlerParams) msg.obj; 1197 int idx = mPendingInstalls.size(); 1198 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1199 // If a bind was already initiated we dont really 1200 // need to do anything. The pending install 1201 // will be processed later on. 1202 if (!mBound) { 1203 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1204 System.identityHashCode(mHandler)); 1205 // If this is the only one pending we might 1206 // have to bind to the service again. 1207 if (!connectToService()) { 1208 Slog.e(TAG, "Failed to bind to media container service"); 1209 params.serviceError(); 1210 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1211 System.identityHashCode(mHandler)); 1212 if (params.traceMethod != null) { 1213 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1214 params.traceCookie); 1215 } 1216 return; 1217 } else { 1218 // Once we bind to the service, the first 1219 // pending request will be processed. 1220 mPendingInstalls.add(idx, params); 1221 } 1222 } else { 1223 mPendingInstalls.add(idx, params); 1224 // Already bound to the service. Just make 1225 // sure we trigger off processing the first request. 1226 if (idx == 0) { 1227 mHandler.sendEmptyMessage(MCS_BOUND); 1228 } 1229 } 1230 break; 1231 } 1232 case MCS_BOUND: { 1233 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1234 if (msg.obj != null) { 1235 mContainerService = (IMediaContainerService) msg.obj; 1236 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1237 System.identityHashCode(mHandler)); 1238 } 1239 if (mContainerService == null) { 1240 if (!mBound) { 1241 // Something seriously wrong since we are not bound and we are not 1242 // waiting for connection. Bail out. 1243 Slog.e(TAG, "Cannot bind to media container service"); 1244 for (HandlerParams params : mPendingInstalls) { 1245 // Indicate service bind error 1246 params.serviceError(); 1247 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1248 System.identityHashCode(params)); 1249 if (params.traceMethod != null) { 1250 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1251 params.traceMethod, params.traceCookie); 1252 } 1253 return; 1254 } 1255 mPendingInstalls.clear(); 1256 } else { 1257 Slog.w(TAG, "Waiting to connect to media container service"); 1258 } 1259 } else if (mPendingInstalls.size() > 0) { 1260 HandlerParams params = mPendingInstalls.get(0); 1261 if (params != null) { 1262 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1263 System.identityHashCode(params)); 1264 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1265 if (params.startCopy()) { 1266 // We are done... look for more work or to 1267 // go idle. 1268 if (DEBUG_SD_INSTALL) Log.i(TAG, 1269 "Checking for more work or unbind..."); 1270 // Delete pending install 1271 if (mPendingInstalls.size() > 0) { 1272 mPendingInstalls.remove(0); 1273 } 1274 if (mPendingInstalls.size() == 0) { 1275 if (mBound) { 1276 if (DEBUG_SD_INSTALL) Log.i(TAG, 1277 "Posting delayed MCS_UNBIND"); 1278 removeMessages(MCS_UNBIND); 1279 Message ubmsg = obtainMessage(MCS_UNBIND); 1280 // Unbind after a little delay, to avoid 1281 // continual thrashing. 1282 sendMessageDelayed(ubmsg, 10000); 1283 } 1284 } else { 1285 // There are more pending requests in queue. 1286 // Just post MCS_BOUND message to trigger processing 1287 // of next pending install. 1288 if (DEBUG_SD_INSTALL) Log.i(TAG, 1289 "Posting MCS_BOUND for next work"); 1290 mHandler.sendEmptyMessage(MCS_BOUND); 1291 } 1292 } 1293 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1294 } 1295 } else { 1296 // Should never happen ideally. 1297 Slog.w(TAG, "Empty queue"); 1298 } 1299 break; 1300 } 1301 case MCS_RECONNECT: { 1302 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1303 if (mPendingInstalls.size() > 0) { 1304 if (mBound) { 1305 disconnectService(); 1306 } 1307 if (!connectToService()) { 1308 Slog.e(TAG, "Failed to bind to media container service"); 1309 for (HandlerParams params : mPendingInstalls) { 1310 // Indicate service bind error 1311 params.serviceError(); 1312 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1313 System.identityHashCode(params)); 1314 } 1315 mPendingInstalls.clear(); 1316 } 1317 } 1318 break; 1319 } 1320 case MCS_UNBIND: { 1321 // If there is no actual work left, then time to unbind. 1322 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1323 1324 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1325 if (mBound) { 1326 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1327 1328 disconnectService(); 1329 } 1330 } else if (mPendingInstalls.size() > 0) { 1331 // There are more pending requests in queue. 1332 // Just post MCS_BOUND message to trigger processing 1333 // of next pending install. 1334 mHandler.sendEmptyMessage(MCS_BOUND); 1335 } 1336 1337 break; 1338 } 1339 case MCS_GIVE_UP: { 1340 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1341 HandlerParams params = mPendingInstalls.remove(0); 1342 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1343 System.identityHashCode(params)); 1344 break; 1345 } 1346 case SEND_PENDING_BROADCAST: { 1347 String packages[]; 1348 ArrayList<String> components[]; 1349 int size = 0; 1350 int uids[]; 1351 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1352 synchronized (mPackages) { 1353 if (mPendingBroadcasts == null) { 1354 return; 1355 } 1356 size = mPendingBroadcasts.size(); 1357 if (size <= 0) { 1358 // Nothing to be done. Just return 1359 return; 1360 } 1361 packages = new String[size]; 1362 components = new ArrayList[size]; 1363 uids = new int[size]; 1364 int i = 0; // filling out the above arrays 1365 1366 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1367 int packageUserId = mPendingBroadcasts.userIdAt(n); 1368 Iterator<Map.Entry<String, ArrayList<String>>> it 1369 = mPendingBroadcasts.packagesForUserId(packageUserId) 1370 .entrySet().iterator(); 1371 while (it.hasNext() && i < size) { 1372 Map.Entry<String, ArrayList<String>> ent = it.next(); 1373 packages[i] = ent.getKey(); 1374 components[i] = ent.getValue(); 1375 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1376 uids[i] = (ps != null) 1377 ? UserHandle.getUid(packageUserId, ps.appId) 1378 : -1; 1379 i++; 1380 } 1381 } 1382 size = i; 1383 mPendingBroadcasts.clear(); 1384 } 1385 // Send broadcasts 1386 for (int i = 0; i < size; i++) { 1387 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1388 } 1389 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1390 break; 1391 } 1392 case START_CLEANING_PACKAGE: { 1393 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1394 final String packageName = (String)msg.obj; 1395 final int userId = msg.arg1; 1396 final boolean andCode = msg.arg2 != 0; 1397 synchronized (mPackages) { 1398 if (userId == UserHandle.USER_ALL) { 1399 int[] users = sUserManager.getUserIds(); 1400 for (int user : users) { 1401 mSettings.addPackageToCleanLPw( 1402 new PackageCleanItem(user, packageName, andCode)); 1403 } 1404 } else { 1405 mSettings.addPackageToCleanLPw( 1406 new PackageCleanItem(userId, packageName, andCode)); 1407 } 1408 } 1409 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1410 startCleaningPackages(); 1411 } break; 1412 case POST_INSTALL: { 1413 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1414 1415 PostInstallData data = mRunningInstalls.get(msg.arg1); 1416 final boolean didRestore = (msg.arg2 != 0); 1417 mRunningInstalls.delete(msg.arg1); 1418 1419 if (data != null) { 1420 InstallArgs args = data.args; 1421 PackageInstalledInfo parentRes = data.res; 1422 1423 final boolean grantPermissions = (args.installFlags 1424 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1425 final boolean killApp = (args.installFlags 1426 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1427 final String[] grantedPermissions = args.installGrantPermissions; 1428 1429 // Handle the parent package 1430 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1431 grantedPermissions, didRestore, args.installerPackageName, 1432 args.observer); 1433 1434 // Handle the child packages 1435 final int childCount = (parentRes.addedChildPackages != null) 1436 ? parentRes.addedChildPackages.size() : 0; 1437 for (int i = 0; i < childCount; i++) { 1438 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1439 handlePackagePostInstall(childRes, grantPermissions, killApp, 1440 grantedPermissions, false, args.installerPackageName, 1441 args.observer); 1442 } 1443 1444 // Log tracing if needed 1445 if (args.traceMethod != null) { 1446 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1447 args.traceCookie); 1448 } 1449 } else { 1450 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1451 } 1452 1453 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1454 } break; 1455 case UPDATED_MEDIA_STATUS: { 1456 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1457 boolean reportStatus = msg.arg1 == 1; 1458 boolean doGc = msg.arg2 == 1; 1459 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1460 if (doGc) { 1461 // Force a gc to clear up stale containers. 1462 Runtime.getRuntime().gc(); 1463 } 1464 if (msg.obj != null) { 1465 @SuppressWarnings("unchecked") 1466 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1467 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1468 // Unload containers 1469 unloadAllContainers(args); 1470 } 1471 if (reportStatus) { 1472 try { 1473 if (DEBUG_SD_INSTALL) Log.i(TAG, 1474 "Invoking StorageManagerService call back"); 1475 PackageHelper.getStorageManager().finishMediaUpdate(); 1476 } catch (RemoteException e) { 1477 Log.e(TAG, "StorageManagerService not running?"); 1478 } 1479 } 1480 } break; 1481 case WRITE_SETTINGS: { 1482 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1483 synchronized (mPackages) { 1484 removeMessages(WRITE_SETTINGS); 1485 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1486 mSettings.writeLPr(); 1487 mDirtyUsers.clear(); 1488 } 1489 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1490 } break; 1491 case WRITE_PACKAGE_RESTRICTIONS: { 1492 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1493 synchronized (mPackages) { 1494 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1495 for (int userId : mDirtyUsers) { 1496 mSettings.writePackageRestrictionsLPr(userId); 1497 } 1498 mDirtyUsers.clear(); 1499 } 1500 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1501 } break; 1502 case WRITE_PACKAGE_LIST: { 1503 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1504 synchronized (mPackages) { 1505 removeMessages(WRITE_PACKAGE_LIST); 1506 mSettings.writePackageListLPr(msg.arg1); 1507 } 1508 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1509 } break; 1510 case CHECK_PENDING_VERIFICATION: { 1511 final int verificationId = msg.arg1; 1512 final PackageVerificationState state = mPendingVerification.get(verificationId); 1513 1514 if ((state != null) && !state.timeoutExtended()) { 1515 final InstallArgs args = state.getInstallArgs(); 1516 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1517 1518 Slog.i(TAG, "Verification timed out for " + originUri); 1519 mPendingVerification.remove(verificationId); 1520 1521 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1522 1523 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1524 Slog.i(TAG, "Continuing with installation of " + originUri); 1525 state.setVerifierResponse(Binder.getCallingUid(), 1526 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1527 broadcastPackageVerified(verificationId, originUri, 1528 PackageManager.VERIFICATION_ALLOW, 1529 state.getInstallArgs().getUser()); 1530 try { 1531 ret = args.copyApk(mContainerService, true); 1532 } catch (RemoteException e) { 1533 Slog.e(TAG, "Could not contact the ContainerService"); 1534 } 1535 } else { 1536 broadcastPackageVerified(verificationId, originUri, 1537 PackageManager.VERIFICATION_REJECT, 1538 state.getInstallArgs().getUser()); 1539 } 1540 1541 Trace.asyncTraceEnd( 1542 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1543 1544 processPendingInstall(args, ret); 1545 mHandler.sendEmptyMessage(MCS_UNBIND); 1546 } 1547 break; 1548 } 1549 case PACKAGE_VERIFIED: { 1550 final int verificationId = msg.arg1; 1551 1552 final PackageVerificationState state = mPendingVerification.get(verificationId); 1553 if (state == null) { 1554 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1555 break; 1556 } 1557 1558 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1559 1560 state.setVerifierResponse(response.callerUid, response.code); 1561 1562 if (state.isVerificationComplete()) { 1563 mPendingVerification.remove(verificationId); 1564 1565 final InstallArgs args = state.getInstallArgs(); 1566 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1567 1568 int ret; 1569 if (state.isInstallAllowed()) { 1570 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1571 broadcastPackageVerified(verificationId, originUri, 1572 response.code, state.getInstallArgs().getUser()); 1573 try { 1574 ret = args.copyApk(mContainerService, true); 1575 } catch (RemoteException e) { 1576 Slog.e(TAG, "Could not contact the ContainerService"); 1577 } 1578 } else { 1579 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1580 } 1581 1582 Trace.asyncTraceEnd( 1583 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1584 1585 processPendingInstall(args, ret); 1586 mHandler.sendEmptyMessage(MCS_UNBIND); 1587 } 1588 1589 break; 1590 } 1591 case START_INTENT_FILTER_VERIFICATIONS: { 1592 IFVerificationParams params = (IFVerificationParams) msg.obj; 1593 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1594 params.replacing, params.pkg); 1595 break; 1596 } 1597 case INTENT_FILTER_VERIFIED: { 1598 final int verificationId = msg.arg1; 1599 1600 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1601 verificationId); 1602 if (state == null) { 1603 Slog.w(TAG, "Invalid IntentFilter verification token " 1604 + verificationId + " received"); 1605 break; 1606 } 1607 1608 final int userId = state.getUserId(); 1609 1610 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1611 "Processing IntentFilter verification with token:" 1612 + verificationId + " and userId:" + userId); 1613 1614 final IntentFilterVerificationResponse response = 1615 (IntentFilterVerificationResponse) msg.obj; 1616 1617 state.setVerifierResponse(response.callerUid, response.code); 1618 1619 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1620 "IntentFilter verification with token:" + verificationId 1621 + " and userId:" + userId 1622 + " is settings verifier response with response code:" 1623 + response.code); 1624 1625 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1626 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1627 + response.getFailedDomainsString()); 1628 } 1629 1630 if (state.isVerificationComplete()) { 1631 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1632 } else { 1633 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1634 "IntentFilter verification with token:" + verificationId 1635 + " was not said to be complete"); 1636 } 1637 1638 break; 1639 } 1640 case EPHEMERAL_RESOLUTION_PHASE_TWO: { 1641 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1642 mEphemeralResolverConnection, 1643 (EphemeralRequest) msg.obj, 1644 mEphemeralInstallerActivity, 1645 mHandler); 1646 } 1647 } 1648 } 1649 } 1650 1651 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1652 boolean killApp, String[] grantedPermissions, 1653 boolean launchedForRestore, String installerPackage, 1654 IPackageInstallObserver2 installObserver) { 1655 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1656 // Send the removed broadcasts 1657 if (res.removedInfo != null) { 1658 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1659 } 1660 1661 // Now that we successfully installed the package, grant runtime 1662 // permissions if requested before broadcasting the install. 1663 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1664 >= Build.VERSION_CODES.M) { 1665 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1666 } 1667 1668 final boolean update = res.removedInfo != null 1669 && res.removedInfo.removedPackage != null; 1670 1671 // If this is the first time we have child packages for a disabled privileged 1672 // app that had no children, we grant requested runtime permissions to the new 1673 // children if the parent on the system image had them already granted. 1674 if (res.pkg.parentPackage != null) { 1675 synchronized (mPackages) { 1676 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1677 } 1678 } 1679 1680 synchronized (mPackages) { 1681 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1682 } 1683 1684 final String packageName = res.pkg.applicationInfo.packageName; 1685 1686 // Determine the set of users who are adding this package for 1687 // the first time vs. those who are seeing an update. 1688 int[] firstUsers = EMPTY_INT_ARRAY; 1689 int[] updateUsers = EMPTY_INT_ARRAY; 1690 if (res.origUsers == null || res.origUsers.length == 0) { 1691 firstUsers = res.newUsers; 1692 } else { 1693 for (int newUser : res.newUsers) { 1694 boolean isNew = true; 1695 for (int origUser : res.origUsers) { 1696 if (origUser == newUser) { 1697 isNew = false; 1698 break; 1699 } 1700 } 1701 if (isNew) { 1702 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1703 } else { 1704 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1705 } 1706 } 1707 } 1708 1709 // Send installed broadcasts if the install/update is not ephemeral 1710 if (!isEphemeral(res.pkg)) { 1711 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1712 1713 // Send added for users that see the package for the first time 1714 // sendPackageAddedForNewUsers also deals with system apps 1715 int appId = UserHandle.getAppId(res.uid); 1716 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1717 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1718 1719 // Send added for users that don't see the package for the first time 1720 Bundle extras = new Bundle(1); 1721 extras.putInt(Intent.EXTRA_UID, res.uid); 1722 if (update) { 1723 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1724 } 1725 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1726 extras, 0 /*flags*/, null /*targetPackage*/, 1727 null /*finishedReceiver*/, updateUsers); 1728 1729 // Send replaced for users that don't see the package for the first time 1730 if (update) { 1731 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1732 packageName, extras, 0 /*flags*/, 1733 null /*targetPackage*/, null /*finishedReceiver*/, 1734 updateUsers); 1735 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1736 null /*package*/, null /*extras*/, 0 /*flags*/, 1737 packageName /*targetPackage*/, 1738 null /*finishedReceiver*/, updateUsers); 1739 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1740 // First-install and we did a restore, so we're responsible for the 1741 // first-launch broadcast. 1742 if (DEBUG_BACKUP) { 1743 Slog.i(TAG, "Post-restore of " + packageName 1744 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1745 } 1746 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1747 } 1748 1749 // Send broadcast package appeared if forward locked/external for all users 1750 // treat asec-hosted packages like removable media on upgrade 1751 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1752 if (DEBUG_INSTALL) { 1753 Slog.i(TAG, "upgrading pkg " + res.pkg 1754 + " is ASEC-hosted -> AVAILABLE"); 1755 } 1756 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1757 ArrayList<String> pkgList = new ArrayList<>(1); 1758 pkgList.add(packageName); 1759 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1760 } 1761 } 1762 1763 // Work that needs to happen on first install within each user 1764 if (firstUsers != null && firstUsers.length > 0) { 1765 synchronized (mPackages) { 1766 for (int userId : firstUsers) { 1767 // If this app is a browser and it's newly-installed for some 1768 // users, clear any default-browser state in those users. The 1769 // app's nature doesn't depend on the user, so we can just check 1770 // its browser nature in any user and generalize. 1771 if (packageIsBrowser(packageName, userId)) { 1772 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1773 } 1774 1775 // We may also need to apply pending (restored) runtime 1776 // permission grants within these users. 1777 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1778 } 1779 } 1780 } 1781 1782 // Log current value of "unknown sources" setting 1783 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1784 getUnknownSourcesSettings()); 1785 1786 // Force a gc to clear up things 1787 Runtime.getRuntime().gc(); 1788 1789 // Remove the replaced package's older resources safely now 1790 // We delete after a gc for applications on sdcard. 1791 if (res.removedInfo != null && res.removedInfo.args != null) { 1792 synchronized (mInstallLock) { 1793 res.removedInfo.args.doPostDeleteLI(true); 1794 } 1795 } 1796 } 1797 1798 // If someone is watching installs - notify them 1799 if (installObserver != null) { 1800 try { 1801 Bundle extras = extrasForInstallResult(res); 1802 installObserver.onPackageInstalled(res.name, res.returnCode, 1803 res.returnMsg, extras); 1804 } catch (RemoteException e) { 1805 Slog.i(TAG, "Observer no longer exists."); 1806 } 1807 } 1808 } 1809 1810 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1811 PackageParser.Package pkg) { 1812 if (pkg.parentPackage == null) { 1813 return; 1814 } 1815 if (pkg.requestedPermissions == null) { 1816 return; 1817 } 1818 final PackageSetting disabledSysParentPs = mSettings 1819 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1820 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1821 || !disabledSysParentPs.isPrivileged() 1822 || (disabledSysParentPs.childPackageNames != null 1823 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1824 return; 1825 } 1826 final int[] allUserIds = sUserManager.getUserIds(); 1827 final int permCount = pkg.requestedPermissions.size(); 1828 for (int i = 0; i < permCount; i++) { 1829 String permission = pkg.requestedPermissions.get(i); 1830 BasePermission bp = mSettings.mPermissions.get(permission); 1831 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1832 continue; 1833 } 1834 for (int userId : allUserIds) { 1835 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1836 permission, userId)) { 1837 grantRuntimePermission(pkg.packageName, permission, userId); 1838 } 1839 } 1840 } 1841 } 1842 1843 private StorageEventListener mStorageListener = new StorageEventListener() { 1844 @Override 1845 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1846 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1847 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1848 final String volumeUuid = vol.getFsUuid(); 1849 1850 // Clean up any users or apps that were removed or recreated 1851 // while this volume was missing 1852 reconcileUsers(volumeUuid); 1853 reconcileApps(volumeUuid); 1854 1855 // Clean up any install sessions that expired or were 1856 // cancelled while this volume was missing 1857 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1858 1859 loadPrivatePackages(vol); 1860 1861 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1862 unloadPrivatePackages(vol); 1863 } 1864 } 1865 1866 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1867 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1868 updateExternalMediaStatus(true, false); 1869 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1870 updateExternalMediaStatus(false, false); 1871 } 1872 } 1873 } 1874 1875 @Override 1876 public void onVolumeForgotten(String fsUuid) { 1877 if (TextUtils.isEmpty(fsUuid)) { 1878 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1879 return; 1880 } 1881 1882 // Remove any apps installed on the forgotten volume 1883 synchronized (mPackages) { 1884 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1885 for (PackageSetting ps : packages) { 1886 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1887 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1888 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1889 1890 // Try very hard to release any references to this package 1891 // so we don't risk the system server being killed due to 1892 // open FDs 1893 AttributeCache.instance().removePackage(ps.name); 1894 } 1895 1896 mSettings.onVolumeForgotten(fsUuid); 1897 mSettings.writeLPr(); 1898 } 1899 } 1900 }; 1901 1902 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1903 String[] grantedPermissions) { 1904 for (int userId : userIds) { 1905 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1906 } 1907 1908 // We could have touched GID membership, so flush out packages.list 1909 synchronized (mPackages) { 1910 mSettings.writePackageListLPr(); 1911 } 1912 } 1913 1914 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1915 String[] grantedPermissions) { 1916 SettingBase sb = (SettingBase) pkg.mExtras; 1917 if (sb == null) { 1918 return; 1919 } 1920 1921 PermissionsState permissionsState = sb.getPermissionsState(); 1922 1923 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1924 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1925 1926 for (String permission : pkg.requestedPermissions) { 1927 final BasePermission bp; 1928 synchronized (mPackages) { 1929 bp = mSettings.mPermissions.get(permission); 1930 } 1931 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1932 && (grantedPermissions == null 1933 || ArrayUtils.contains(grantedPermissions, permission))) { 1934 final int flags = permissionsState.getPermissionFlags(permission, userId); 1935 // Installer cannot change immutable permissions. 1936 if ((flags & immutableFlags) == 0) { 1937 grantRuntimePermission(pkg.packageName, permission, userId); 1938 } 1939 } 1940 } 1941 } 1942 1943 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1944 Bundle extras = null; 1945 switch (res.returnCode) { 1946 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1947 extras = new Bundle(); 1948 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1949 res.origPermission); 1950 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1951 res.origPackage); 1952 break; 1953 } 1954 case PackageManager.INSTALL_SUCCEEDED: { 1955 extras = new Bundle(); 1956 extras.putBoolean(Intent.EXTRA_REPLACING, 1957 res.removedInfo != null && res.removedInfo.removedPackage != null); 1958 break; 1959 } 1960 } 1961 return extras; 1962 } 1963 1964 void scheduleWriteSettingsLocked() { 1965 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1966 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1967 } 1968 } 1969 1970 void scheduleWritePackageListLocked(int userId) { 1971 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 1972 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 1973 msg.arg1 = userId; 1974 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 1975 } 1976 } 1977 1978 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1979 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1980 scheduleWritePackageRestrictionsLocked(userId); 1981 } 1982 1983 void scheduleWritePackageRestrictionsLocked(int userId) { 1984 final int[] userIds = (userId == UserHandle.USER_ALL) 1985 ? sUserManager.getUserIds() : new int[]{userId}; 1986 for (int nextUserId : userIds) { 1987 if (!sUserManager.exists(nextUserId)) return; 1988 mDirtyUsers.add(nextUserId); 1989 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1990 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1991 } 1992 } 1993 } 1994 1995 public static PackageManagerService main(Context context, Installer installer, 1996 boolean factoryTest, boolean onlyCore) { 1997 // Self-check for initial settings. 1998 PackageManagerServiceCompilerMapping.checkProperties(); 1999 2000 PackageManagerService m = new PackageManagerService(context, installer, 2001 factoryTest, onlyCore); 2002 m.enableSystemUserPackages(); 2003 ServiceManager.addService("package", m); 2004 return m; 2005 } 2006 2007 private void enableSystemUserPackages() { 2008 if (!UserManager.isSplitSystemUser()) { 2009 return; 2010 } 2011 // For system user, enable apps based on the following conditions: 2012 // - app is whitelisted or belong to one of these groups: 2013 // -- system app which has no launcher icons 2014 // -- system app which has INTERACT_ACROSS_USERS permission 2015 // -- system IME app 2016 // - app is not in the blacklist 2017 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2018 Set<String> enableApps = new ArraySet<>(); 2019 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2020 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2021 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2022 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2023 enableApps.addAll(wlApps); 2024 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2025 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2026 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2027 enableApps.removeAll(blApps); 2028 Log.i(TAG, "Applications installed for system user: " + enableApps); 2029 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2030 UserHandle.SYSTEM); 2031 final int allAppsSize = allAps.size(); 2032 synchronized (mPackages) { 2033 for (int i = 0; i < allAppsSize; i++) { 2034 String pName = allAps.get(i); 2035 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2036 // Should not happen, but we shouldn't be failing if it does 2037 if (pkgSetting == null) { 2038 continue; 2039 } 2040 boolean install = enableApps.contains(pName); 2041 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2042 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2043 + " for system user"); 2044 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2045 } 2046 } 2047 } 2048 } 2049 2050 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2051 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2052 Context.DISPLAY_SERVICE); 2053 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2054 } 2055 2056 /** 2057 * Requests that files preopted on a secondary system partition be copied to the data partition 2058 * if possible. Note that the actual copying of the files is accomplished by init for security 2059 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2060 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2061 */ 2062 private static void requestCopyPreoptedFiles() { 2063 final int WAIT_TIME_MS = 100; 2064 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2065 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2066 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2067 // We will wait for up to 100 seconds. 2068 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2069 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2070 try { 2071 Thread.sleep(WAIT_TIME_MS); 2072 } catch (InterruptedException e) { 2073 // Do nothing 2074 } 2075 if (SystemClock.uptimeMillis() > timeEnd) { 2076 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2077 Slog.wtf(TAG, "cppreopt did not finish!"); 2078 break; 2079 } 2080 } 2081 } 2082 } 2083 2084 public PackageManagerService(Context context, Installer installer, 2085 boolean factoryTest, boolean onlyCore) { 2086 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2087 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2088 SystemClock.uptimeMillis()); 2089 2090 if (mSdkVersion <= 0) { 2091 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2092 } 2093 2094 mContext = context; 2095 2096 mPermissionReviewRequired = context.getResources().getBoolean( 2097 R.bool.config_permissionReviewRequired); 2098 2099 mFactoryTest = factoryTest; 2100 mOnlyCore = onlyCore; 2101 mMetrics = new DisplayMetrics(); 2102 mSettings = new Settings(mPackages); 2103 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2104 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2105 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2106 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2107 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2108 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2109 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2110 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2111 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2112 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2113 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2114 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2115 2116 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2117 if (separateProcesses != null && separateProcesses.length() > 0) { 2118 if ("*".equals(separateProcesses)) { 2119 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2120 mSeparateProcesses = null; 2121 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2122 } else { 2123 mDefParseFlags = 0; 2124 mSeparateProcesses = separateProcesses.split(","); 2125 Slog.w(TAG, "Running with debug.separate_processes: " 2126 + separateProcesses); 2127 } 2128 } else { 2129 mDefParseFlags = 0; 2130 mSeparateProcesses = null; 2131 } 2132 2133 mInstaller = installer; 2134 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2135 "*dexopt*"); 2136 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2137 2138 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2139 FgThread.get().getLooper()); 2140 2141 getDefaultDisplayMetrics(context, mMetrics); 2142 2143 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2144 SystemConfig systemConfig = SystemConfig.getInstance(); 2145 mGlobalGids = systemConfig.getGlobalGids(); 2146 mSystemPermissions = systemConfig.getSystemPermissions(); 2147 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2148 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2149 2150 mProtectedPackages = new ProtectedPackages(mContext); 2151 2152 synchronized (mInstallLock) { 2153 // writer 2154 synchronized (mPackages) { 2155 mHandlerThread = new ServiceThread(TAG, 2156 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2157 mHandlerThread.start(); 2158 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2159 mProcessLoggingHandler = new ProcessLoggingHandler(); 2160 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2161 2162 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2163 2164 File dataDir = Environment.getDataDirectory(); 2165 mAppInstallDir = new File(dataDir, "app"); 2166 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2167 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2168 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2169 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2170 2171 sUserManager = new UserManagerService(context, this, mPackages); 2172 2173 // Propagate permission configuration in to package manager. 2174 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2175 = systemConfig.getPermissions(); 2176 for (int i=0; i<permConfig.size(); i++) { 2177 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2178 BasePermission bp = mSettings.mPermissions.get(perm.name); 2179 if (bp == null) { 2180 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2181 mSettings.mPermissions.put(perm.name, bp); 2182 } 2183 if (perm.gids != null) { 2184 bp.setGids(perm.gids, perm.perUser); 2185 } 2186 } 2187 2188 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2189 for (int i=0; i<libConfig.size(); i++) { 2190 mSharedLibraries.put(libConfig.keyAt(i), 2191 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2192 } 2193 2194 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2195 2196 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2197 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2198 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2199 2200 if (mFirstBoot) { 2201 requestCopyPreoptedFiles(); 2202 } 2203 2204 String customResolverActivity = Resources.getSystem().getString( 2205 R.string.config_customResolverActivity); 2206 if (TextUtils.isEmpty(customResolverActivity)) { 2207 customResolverActivity = null; 2208 } else { 2209 mCustomResolverComponentName = ComponentName.unflattenFromString( 2210 customResolverActivity); 2211 } 2212 2213 long startTime = SystemClock.uptimeMillis(); 2214 2215 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2216 startTime); 2217 2218 // Set flag to monitor and not change apk file paths when 2219 // scanning install directories. 2220 final int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2221 2222 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2223 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2224 2225 if (bootClassPath == null) { 2226 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2227 } 2228 2229 if (systemServerClassPath == null) { 2230 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2231 } 2232 2233 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2234 final String[] dexCodeInstructionSets = 2235 getDexCodeInstructionSets( 2236 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2237 2238 /** 2239 * Ensure all external libraries have had dexopt run on them. 2240 */ 2241 if (mSharedLibraries.size() > 0) { 2242 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2243 // NOTE: For now, we're compiling these system "shared libraries" 2244 // (and framework jars) into all available architectures. It's possible 2245 // to compile them only when we come across an app that uses them (there's 2246 // already logic for that in scanPackageLI) but that adds some complexity. 2247 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2248 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2249 final String lib = libEntry.path; 2250 if (lib == null) { 2251 continue; 2252 } 2253 2254 try { 2255 // Shared libraries do not have profiles so we perform a full 2256 // AOT compilation (if needed). 2257 int dexoptNeeded = DexFile.getDexOptNeeded( 2258 lib, dexCodeInstructionSet, 2259 getCompilerFilterForReason(REASON_SHARED_APK), 2260 false /* newProfile */); 2261 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2262 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2263 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2264 getCompilerFilterForReason(REASON_SHARED_APK), 2265 StorageManager.UUID_PRIVATE_INTERNAL, 2266 SKIP_SHARED_LIBRARY_CHECK); 2267 } 2268 } catch (FileNotFoundException e) { 2269 Slog.w(TAG, "Library not found: " + lib); 2270 } catch (IOException | InstallerException e) { 2271 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2272 + e.getMessage()); 2273 } 2274 } 2275 } 2276 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2277 } 2278 2279 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2280 2281 final VersionInfo ver = mSettings.getInternalVersion(); 2282 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2283 2284 // when upgrading from pre-M, promote system app permissions from install to runtime 2285 mPromoteSystemApps = 2286 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2287 2288 // When upgrading from pre-N, we need to handle package extraction like first boot, 2289 // as there is no profiling data available. 2290 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2291 2292 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2293 2294 // save off the names of pre-existing system packages prior to scanning; we don't 2295 // want to automatically grant runtime permissions for new system apps 2296 if (mPromoteSystemApps) { 2297 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2298 while (pkgSettingIter.hasNext()) { 2299 PackageSetting ps = pkgSettingIter.next(); 2300 if (isSystemApp(ps)) { 2301 mExistingSystemPackages.add(ps.name); 2302 } 2303 } 2304 } 2305 2306 // Collect vendor overlay packages. (Do this before scanning any apps.) 2307 // For security and version matching reason, only consider 2308 // overlay packages if they reside in the right directory. 2309 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2310 if (overlayThemeDir.isEmpty()) { 2311 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2312 } 2313 if (!overlayThemeDir.isEmpty()) { 2314 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2315 | PackageParser.PARSE_IS_SYSTEM 2316 | PackageParser.PARSE_IS_SYSTEM_DIR 2317 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2318 } 2319 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2320 | PackageParser.PARSE_IS_SYSTEM 2321 | PackageParser.PARSE_IS_SYSTEM_DIR 2322 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2323 2324 // Find base frameworks (resource packages without code). 2325 scanDirTracedLI(frameworkDir, mDefParseFlags 2326 | PackageParser.PARSE_IS_SYSTEM 2327 | PackageParser.PARSE_IS_SYSTEM_DIR 2328 | PackageParser.PARSE_IS_PRIVILEGED, 2329 scanFlags | SCAN_NO_DEX, 0); 2330 2331 // Collected privileged system packages. 2332 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2333 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2334 | PackageParser.PARSE_IS_SYSTEM 2335 | PackageParser.PARSE_IS_SYSTEM_DIR 2336 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2337 2338 // Collect ordinary system packages. 2339 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2340 scanDirTracedLI(systemAppDir, mDefParseFlags 2341 | PackageParser.PARSE_IS_SYSTEM 2342 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2343 2344 // Collect all vendor packages. 2345 File vendorAppDir = new File("/vendor/app"); 2346 try { 2347 vendorAppDir = vendorAppDir.getCanonicalFile(); 2348 } catch (IOException e) { 2349 // failed to look up canonical path, continue with original one 2350 } 2351 scanDirTracedLI(vendorAppDir, mDefParseFlags 2352 | PackageParser.PARSE_IS_SYSTEM 2353 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2354 2355 // Collect all OEM packages. 2356 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2357 scanDirTracedLI(oemAppDir, mDefParseFlags 2358 | PackageParser.PARSE_IS_SYSTEM 2359 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2360 2361 // Prune any system packages that no longer exist. 2362 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2363 if (!mOnlyCore) { 2364 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2365 while (psit.hasNext()) { 2366 PackageSetting ps = psit.next(); 2367 2368 /* 2369 * If this is not a system app, it can't be a 2370 * disable system app. 2371 */ 2372 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2373 continue; 2374 } 2375 2376 /* 2377 * If the package is scanned, it's not erased. 2378 */ 2379 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2380 if (scannedPkg != null) { 2381 /* 2382 * If the system app is both scanned and in the 2383 * disabled packages list, then it must have been 2384 * added via OTA. Remove it from the currently 2385 * scanned package so the previously user-installed 2386 * application can be scanned. 2387 */ 2388 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2389 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2390 + ps.name + "; removing system app. Last known codePath=" 2391 + ps.codePathString + ", installStatus=" + ps.installStatus 2392 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2393 + scannedPkg.mVersionCode); 2394 removePackageLI(scannedPkg, true); 2395 mExpectingBetter.put(ps.name, ps.codePath); 2396 } 2397 2398 continue; 2399 } 2400 2401 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2402 psit.remove(); 2403 logCriticalInfo(Log.WARN, "System package " + ps.name 2404 + " no longer exists; it's data will be wiped"); 2405 // Actual deletion of code and data will be handled by later 2406 // reconciliation step 2407 } else { 2408 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2409 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2410 possiblyDeletedUpdatedSystemApps.add(ps.name); 2411 } 2412 } 2413 } 2414 } 2415 2416 //look for any incomplete package installations 2417 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2418 for (int i = 0; i < deletePkgsList.size(); i++) { 2419 // Actual deletion of code and data will be handled by later 2420 // reconciliation step 2421 final String packageName = deletePkgsList.get(i).name; 2422 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2423 synchronized (mPackages) { 2424 mSettings.removePackageLPw(packageName); 2425 } 2426 } 2427 2428 //delete tmp files 2429 deleteTempPackageFiles(); 2430 2431 // Remove any shared userIDs that have no associated packages 2432 mSettings.pruneSharedUsersLPw(); 2433 2434 if (!mOnlyCore) { 2435 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2436 SystemClock.uptimeMillis()); 2437 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2438 2439 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2440 | PackageParser.PARSE_FORWARD_LOCK, 2441 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2442 2443 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2444 | PackageParser.PARSE_IS_EPHEMERAL, 2445 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2446 2447 /** 2448 * Remove disable package settings for any updated system 2449 * apps that were removed via an OTA. If they're not a 2450 * previously-updated app, remove them completely. 2451 * Otherwise, just revoke their system-level permissions. 2452 */ 2453 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2454 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2455 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2456 2457 String msg; 2458 if (deletedPkg == null) { 2459 msg = "Updated system package " + deletedAppName 2460 + " no longer exists; it's data will be wiped"; 2461 // Actual deletion of code and data will be handled by later 2462 // reconciliation step 2463 } else { 2464 msg = "Updated system app + " + deletedAppName 2465 + " no longer present; removing system privileges for " 2466 + deletedAppName; 2467 2468 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2469 2470 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2471 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2472 } 2473 logCriticalInfo(Log.WARN, msg); 2474 } 2475 2476 /** 2477 * Make sure all system apps that we expected to appear on 2478 * the userdata partition actually showed up. If they never 2479 * appeared, crawl back and revive the system version. 2480 */ 2481 for (int i = 0; i < mExpectingBetter.size(); i++) { 2482 final String packageName = mExpectingBetter.keyAt(i); 2483 if (!mPackages.containsKey(packageName)) { 2484 final File scanFile = mExpectingBetter.valueAt(i); 2485 2486 logCriticalInfo(Log.WARN, "Expected better " + packageName 2487 + " but never showed up; reverting to system"); 2488 2489 int reparseFlags = mDefParseFlags; 2490 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2491 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2492 | PackageParser.PARSE_IS_SYSTEM_DIR 2493 | PackageParser.PARSE_IS_PRIVILEGED; 2494 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2495 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2496 | PackageParser.PARSE_IS_SYSTEM_DIR; 2497 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2498 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2499 | PackageParser.PARSE_IS_SYSTEM_DIR; 2500 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2501 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2502 | PackageParser.PARSE_IS_SYSTEM_DIR; 2503 } else { 2504 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2505 continue; 2506 } 2507 2508 mSettings.enableSystemPackageLPw(packageName); 2509 2510 try { 2511 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2512 } catch (PackageManagerException e) { 2513 Slog.e(TAG, "Failed to parse original system package: " 2514 + e.getMessage()); 2515 } 2516 } 2517 } 2518 } 2519 mExpectingBetter.clear(); 2520 2521 // Resolve the storage manager. 2522 mStorageManagerPackage = getStorageManagerPackageName(); 2523 2524 // Resolve protected action filters. Only the setup wizard is allowed to 2525 // have a high priority filter for these actions. 2526 mSetupWizardPackage = getSetupWizardPackageName(); 2527 if (mProtectedFilters.size() > 0) { 2528 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2529 Slog.i(TAG, "No setup wizard;" 2530 + " All protected intents capped to priority 0"); 2531 } 2532 for (ActivityIntentInfo filter : mProtectedFilters) { 2533 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2534 if (DEBUG_FILTERS) { 2535 Slog.i(TAG, "Found setup wizard;" 2536 + " allow priority " + filter.getPriority() + ";" 2537 + " package: " + filter.activity.info.packageName 2538 + " activity: " + filter.activity.className 2539 + " priority: " + filter.getPriority()); 2540 } 2541 // skip setup wizard; allow it to keep the high priority filter 2542 continue; 2543 } 2544 Slog.w(TAG, "Protected action; cap priority to 0;" 2545 + " package: " + filter.activity.info.packageName 2546 + " activity: " + filter.activity.className 2547 + " origPrio: " + filter.getPriority()); 2548 filter.setPriority(0); 2549 } 2550 } 2551 mDeferProtectedFilters = false; 2552 mProtectedFilters.clear(); 2553 2554 // Now that we know all of the shared libraries, update all clients to have 2555 // the correct library paths. 2556 updateAllSharedLibrariesLPw(); 2557 2558 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2559 // NOTE: We ignore potential failures here during a system scan (like 2560 // the rest of the commands above) because there's precious little we 2561 // can do about it. A settings error is reported, though. 2562 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2563 } 2564 2565 // Now that we know all the packages we are keeping, 2566 // read and update their last usage times. 2567 mPackageUsage.read(mPackages); 2568 mCompilerStats.read(); 2569 2570 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2571 SystemClock.uptimeMillis()); 2572 Slog.i(TAG, "Time to scan packages: " 2573 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2574 + " seconds"); 2575 2576 // If the platform SDK has changed since the last time we booted, 2577 // we need to re-grant app permission to catch any new ones that 2578 // appear. This is really a hack, and means that apps can in some 2579 // cases get permissions that the user didn't initially explicitly 2580 // allow... it would be nice to have some better way to handle 2581 // this situation. 2582 int updateFlags = UPDATE_PERMISSIONS_ALL; 2583 if (ver.sdkVersion != mSdkVersion) { 2584 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2585 + mSdkVersion + "; regranting permissions for internal storage"); 2586 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2587 } 2588 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2589 ver.sdkVersion = mSdkVersion; 2590 2591 // If this is the first boot or an update from pre-M, and it is a normal 2592 // boot, then we need to initialize the default preferred apps across 2593 // all defined users. 2594 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2595 for (UserInfo user : sUserManager.getUsers(true)) { 2596 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2597 applyFactoryDefaultBrowserLPw(user.id); 2598 primeDomainVerificationsLPw(user.id); 2599 } 2600 } 2601 2602 // Prepare storage for system user really early during boot, 2603 // since core system apps like SettingsProvider and SystemUI 2604 // can't wait for user to start 2605 final int storageFlags; 2606 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2607 storageFlags = StorageManager.FLAG_STORAGE_DE; 2608 } else { 2609 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2610 } 2611 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2612 storageFlags, true /* migrateAppData */); 2613 2614 // If this is first boot after an OTA, and a normal boot, then 2615 // we need to clear code cache directories. 2616 // Note that we do *not* clear the application profiles. These remain valid 2617 // across OTAs and are used to drive profile verification (post OTA) and 2618 // profile compilation (without waiting to collect a fresh set of profiles). 2619 if (mIsUpgrade && !onlyCore) { 2620 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2621 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2622 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2623 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2624 // No apps are running this early, so no need to freeze 2625 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2626 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2627 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2628 } 2629 } 2630 ver.fingerprint = Build.FINGERPRINT; 2631 } 2632 2633 checkDefaultBrowser(); 2634 2635 // clear only after permissions and other defaults have been updated 2636 mExistingSystemPackages.clear(); 2637 mPromoteSystemApps = false; 2638 2639 // All the changes are done during package scanning. 2640 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2641 2642 // can downgrade to reader 2643 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2644 mSettings.writeLPr(); 2645 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2646 2647 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2648 // early on (before the package manager declares itself as early) because other 2649 // components in the system server might ask for package contexts for these apps. 2650 // 2651 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2652 // (i.e, that the data partition is unavailable). 2653 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2654 long start = System.nanoTime(); 2655 List<PackageParser.Package> coreApps = new ArrayList<>(); 2656 for (PackageParser.Package pkg : mPackages.values()) { 2657 if (pkg.coreApp) { 2658 coreApps.add(pkg); 2659 } 2660 } 2661 2662 int[] stats = performDexOptUpgrade(coreApps, false, 2663 getCompilerFilterForReason(REASON_CORE_APP)); 2664 2665 final int elapsedTimeSeconds = 2666 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2667 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2668 2669 if (DEBUG_DEXOPT) { 2670 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2671 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2672 } 2673 2674 2675 // TODO: Should we log these stats to tron too ? 2676 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2677 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2678 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2679 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2680 } 2681 2682 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2683 SystemClock.uptimeMillis()); 2684 2685 if (!mOnlyCore) { 2686 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2687 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2688 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2689 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2690 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2691 mIntentFilterVerifierComponent); 2692 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2693 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2694 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2695 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2696 } else { 2697 mRequiredVerifierPackage = null; 2698 mRequiredInstallerPackage = null; 2699 mRequiredUninstallerPackage = null; 2700 mIntentFilterVerifierComponent = null; 2701 mIntentFilterVerifier = null; 2702 mServicesSystemSharedLibraryPackageName = null; 2703 mSharedSystemSharedLibraryPackageName = null; 2704 } 2705 2706 mInstallerService = new PackageInstallerService(context, this); 2707 2708 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2709 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2710 // both the installer and resolver must be present to enable ephemeral 2711 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2712 if (DEBUG_EPHEMERAL) { 2713 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2714 + " installer:" + ephemeralInstallerComponent); 2715 } 2716 mEphemeralResolverComponent = ephemeralResolverComponent; 2717 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2718 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2719 mEphemeralResolverConnection = 2720 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2721 } else { 2722 if (DEBUG_EPHEMERAL) { 2723 final String missingComponent = 2724 (ephemeralResolverComponent == null) 2725 ? (ephemeralInstallerComponent == null) 2726 ? "resolver and installer" 2727 : "resolver" 2728 : "installer"; 2729 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2730 } 2731 mEphemeralResolverComponent = null; 2732 mEphemeralInstallerComponent = null; 2733 mEphemeralResolverConnection = null; 2734 } 2735 2736 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2737 } // synchronized (mPackages) 2738 } // synchronized (mInstallLock) 2739 2740 // Now after opening every single application zip, make sure they 2741 // are all flushed. Not really needed, but keeps things nice and 2742 // tidy. 2743 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2744 Runtime.getRuntime().gc(); 2745 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2746 2747 // The initial scanning above does many calls into installd while 2748 // holding the mPackages lock, but we're mostly interested in yelling 2749 // once we have a booted system. 2750 mInstaller.setWarnIfHeld(mPackages); 2751 2752 // Expose private service for system components to use. 2753 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2754 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2755 } 2756 2757 @Override 2758 public boolean isFirstBoot() { 2759 return mFirstBoot; 2760 } 2761 2762 @Override 2763 public boolean isOnlyCoreApps() { 2764 return mOnlyCore; 2765 } 2766 2767 @Override 2768 public boolean isUpgrade() { 2769 return mIsUpgrade; 2770 } 2771 2772 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2773 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2774 2775 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2776 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2777 UserHandle.USER_SYSTEM); 2778 if (matches.size() == 1) { 2779 return matches.get(0).getComponentInfo().packageName; 2780 } else if (matches.size() == 0) { 2781 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2782 return null; 2783 } 2784 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2785 } 2786 2787 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2788 synchronized (mPackages) { 2789 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2790 if (libraryEntry == null) { 2791 throw new IllegalStateException("Missing required shared library:" + libraryName); 2792 } 2793 return libraryEntry.apk; 2794 } 2795 } 2796 2797 private @NonNull String getRequiredInstallerLPr() { 2798 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2799 intent.addCategory(Intent.CATEGORY_DEFAULT); 2800 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2801 2802 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2803 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2804 UserHandle.USER_SYSTEM); 2805 if (matches.size() == 1) { 2806 ResolveInfo resolveInfo = matches.get(0); 2807 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2808 throw new RuntimeException("The installer must be a privileged app"); 2809 } 2810 return matches.get(0).getComponentInfo().packageName; 2811 } else { 2812 throw new RuntimeException("There must be exactly one installer; found " + matches); 2813 } 2814 } 2815 2816 private @NonNull String getRequiredUninstallerLPr() { 2817 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2818 intent.addCategory(Intent.CATEGORY_DEFAULT); 2819 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2820 2821 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2822 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2823 UserHandle.USER_SYSTEM); 2824 if (resolveInfo == null || 2825 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2826 throw new RuntimeException("There must be exactly one uninstaller; found " 2827 + resolveInfo); 2828 } 2829 return resolveInfo.getComponentInfo().packageName; 2830 } 2831 2832 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2833 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2834 2835 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2836 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2837 UserHandle.USER_SYSTEM); 2838 ResolveInfo best = null; 2839 final int N = matches.size(); 2840 for (int i = 0; i < N; i++) { 2841 final ResolveInfo cur = matches.get(i); 2842 final String packageName = cur.getComponentInfo().packageName; 2843 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2844 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2845 continue; 2846 } 2847 2848 if (best == null || cur.priority > best.priority) { 2849 best = cur; 2850 } 2851 } 2852 2853 if (best != null) { 2854 return best.getComponentInfo().getComponentName(); 2855 } else { 2856 throw new RuntimeException("There must be at least one intent filter verifier"); 2857 } 2858 } 2859 2860 private @Nullable ComponentName getEphemeralResolverLPr() { 2861 final String[] packageArray = 2862 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2863 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2864 if (DEBUG_EPHEMERAL) { 2865 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2866 } 2867 return null; 2868 } 2869 2870 final int resolveFlags = 2871 MATCH_DIRECT_BOOT_AWARE 2872 | MATCH_DIRECT_BOOT_UNAWARE 2873 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2874 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2875 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2876 resolveFlags, UserHandle.USER_SYSTEM); 2877 2878 final int N = resolvers.size(); 2879 if (N == 0) { 2880 if (DEBUG_EPHEMERAL) { 2881 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2882 } 2883 return null; 2884 } 2885 2886 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2887 for (int i = 0; i < N; i++) { 2888 final ResolveInfo info = resolvers.get(i); 2889 2890 if (info.serviceInfo == null) { 2891 continue; 2892 } 2893 2894 final String packageName = info.serviceInfo.packageName; 2895 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2896 if (DEBUG_EPHEMERAL) { 2897 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2898 + " pkg: " + packageName + ", info:" + info); 2899 } 2900 continue; 2901 } 2902 2903 if (DEBUG_EPHEMERAL) { 2904 Slog.v(TAG, "Ephemeral resolver found;" 2905 + " pkg: " + packageName + ", info:" + info); 2906 } 2907 return new ComponentName(packageName, info.serviceInfo.name); 2908 } 2909 if (DEBUG_EPHEMERAL) { 2910 Slog.v(TAG, "Ephemeral resolver NOT found"); 2911 } 2912 return null; 2913 } 2914 2915 private @Nullable ComponentName getEphemeralInstallerLPr() { 2916 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2917 intent.addCategory(Intent.CATEGORY_DEFAULT); 2918 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2919 2920 final int resolveFlags = 2921 MATCH_DIRECT_BOOT_AWARE 2922 | MATCH_DIRECT_BOOT_UNAWARE 2923 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2924 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2925 resolveFlags, UserHandle.USER_SYSTEM); 2926 if (matches.size() == 0) { 2927 return null; 2928 } else if (matches.size() == 1) { 2929 return matches.get(0).getComponentInfo().getComponentName(); 2930 } else { 2931 throw new RuntimeException( 2932 "There must be at most one ephemeral installer; found " + matches); 2933 } 2934 } 2935 2936 private void primeDomainVerificationsLPw(int userId) { 2937 if (DEBUG_DOMAIN_VERIFICATION) { 2938 Slog.d(TAG, "Priming domain verifications in user " + userId); 2939 } 2940 2941 SystemConfig systemConfig = SystemConfig.getInstance(); 2942 ArraySet<String> packages = systemConfig.getLinkedApps(); 2943 2944 for (String packageName : packages) { 2945 PackageParser.Package pkg = mPackages.get(packageName); 2946 if (pkg != null) { 2947 if (!pkg.isSystemApp()) { 2948 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2949 continue; 2950 } 2951 2952 ArraySet<String> domains = null; 2953 for (PackageParser.Activity a : pkg.activities) { 2954 for (ActivityIntentInfo filter : a.intents) { 2955 if (hasValidDomains(filter)) { 2956 if (domains == null) { 2957 domains = new ArraySet<String>(); 2958 } 2959 domains.addAll(filter.getHostsList()); 2960 } 2961 } 2962 } 2963 2964 if (domains != null && domains.size() > 0) { 2965 if (DEBUG_DOMAIN_VERIFICATION) { 2966 Slog.v(TAG, " + " + packageName); 2967 } 2968 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2969 // state w.r.t. the formal app-linkage "no verification attempted" state; 2970 // and then 'always' in the per-user state actually used for intent resolution. 2971 final IntentFilterVerificationInfo ivi; 2972 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 2973 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2974 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2975 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2976 } else { 2977 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2978 + "' does not handle web links"); 2979 } 2980 } else { 2981 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2982 } 2983 } 2984 2985 scheduleWritePackageRestrictionsLocked(userId); 2986 scheduleWriteSettingsLocked(); 2987 } 2988 2989 private void applyFactoryDefaultBrowserLPw(int userId) { 2990 // The default browser app's package name is stored in a string resource, 2991 // with a product-specific overlay used for vendor customization. 2992 String browserPkg = mContext.getResources().getString( 2993 com.android.internal.R.string.default_browser); 2994 if (!TextUtils.isEmpty(browserPkg)) { 2995 // non-empty string => required to be a known package 2996 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2997 if (ps == null) { 2998 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2999 browserPkg = null; 3000 } else { 3001 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3002 } 3003 } 3004 3005 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3006 // default. If there's more than one, just leave everything alone. 3007 if (browserPkg == null) { 3008 calculateDefaultBrowserLPw(userId); 3009 } 3010 } 3011 3012 private void calculateDefaultBrowserLPw(int userId) { 3013 List<String> allBrowsers = resolveAllBrowserApps(userId); 3014 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3015 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3016 } 3017 3018 private List<String> resolveAllBrowserApps(int userId) { 3019 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3020 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3021 PackageManager.MATCH_ALL, userId); 3022 3023 final int count = list.size(); 3024 List<String> result = new ArrayList<String>(count); 3025 for (int i=0; i<count; i++) { 3026 ResolveInfo info = list.get(i); 3027 if (info.activityInfo == null 3028 || !info.handleAllWebDataURI 3029 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3030 || result.contains(info.activityInfo.packageName)) { 3031 continue; 3032 } 3033 result.add(info.activityInfo.packageName); 3034 } 3035 3036 return result; 3037 } 3038 3039 private boolean packageIsBrowser(String packageName, int userId) { 3040 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3041 PackageManager.MATCH_ALL, userId); 3042 final int N = list.size(); 3043 for (int i = 0; i < N; i++) { 3044 ResolveInfo info = list.get(i); 3045 if (packageName.equals(info.activityInfo.packageName)) { 3046 return true; 3047 } 3048 } 3049 return false; 3050 } 3051 3052 private void checkDefaultBrowser() { 3053 final int myUserId = UserHandle.myUserId(); 3054 final String packageName = getDefaultBrowserPackageName(myUserId); 3055 if (packageName != null) { 3056 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3057 if (info == null) { 3058 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3059 synchronized (mPackages) { 3060 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3061 } 3062 } 3063 } 3064 } 3065 3066 @Override 3067 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3068 throws RemoteException { 3069 try { 3070 return super.onTransact(code, data, reply, flags); 3071 } catch (RuntimeException e) { 3072 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3073 Slog.wtf(TAG, "Package Manager Crash", e); 3074 } 3075 throw e; 3076 } 3077 } 3078 3079 static int[] appendInts(int[] cur, int[] add) { 3080 if (add == null) return cur; 3081 if (cur == null) return add; 3082 final int N = add.length; 3083 for (int i=0; i<N; i++) { 3084 cur = appendInt(cur, add[i]); 3085 } 3086 return cur; 3087 } 3088 3089 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3090 if (!sUserManager.exists(userId)) return null; 3091 if (ps == null) { 3092 return null; 3093 } 3094 final PackageParser.Package p = ps.pkg; 3095 if (p == null) { 3096 return null; 3097 } 3098 3099 final PermissionsState permissionsState = ps.getPermissionsState(); 3100 3101 // Compute GIDs only if requested 3102 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3103 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3104 // Compute granted permissions only if package has requested permissions 3105 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3106 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3107 final PackageUserState state = ps.readUserState(userId); 3108 3109 return PackageParser.generatePackageInfo(p, gids, flags, 3110 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3111 } 3112 3113 @Override 3114 public void checkPackageStartable(String packageName, int userId) { 3115 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3116 3117 synchronized (mPackages) { 3118 final PackageSetting ps = mSettings.mPackages.get(packageName); 3119 if (ps == null) { 3120 throw new SecurityException("Package " + packageName + " was not found!"); 3121 } 3122 3123 if (!ps.getInstalled(userId)) { 3124 throw new SecurityException( 3125 "Package " + packageName + " was not installed for user " + userId + "!"); 3126 } 3127 3128 if (mSafeMode && !ps.isSystem()) { 3129 throw new SecurityException("Package " + packageName + " not a system app!"); 3130 } 3131 3132 if (mFrozenPackages.contains(packageName)) { 3133 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3134 } 3135 3136 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3137 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3138 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3139 } 3140 } 3141 } 3142 3143 @Override 3144 public boolean isPackageAvailable(String packageName, int userId) { 3145 if (!sUserManager.exists(userId)) return false; 3146 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3147 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3148 synchronized (mPackages) { 3149 PackageParser.Package p = mPackages.get(packageName); 3150 if (p != null) { 3151 final PackageSetting ps = (PackageSetting) p.mExtras; 3152 if (ps != null) { 3153 final PackageUserState state = ps.readUserState(userId); 3154 if (state != null) { 3155 return PackageParser.isAvailable(state); 3156 } 3157 } 3158 } 3159 } 3160 return false; 3161 } 3162 3163 @Override 3164 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3165 if (!sUserManager.exists(userId)) return null; 3166 flags = updateFlagsForPackage(flags, userId, packageName); 3167 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3168 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3169 // reader 3170 synchronized (mPackages) { 3171 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3172 PackageParser.Package p = null; 3173 if (matchFactoryOnly) { 3174 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3175 if (ps != null) { 3176 return generatePackageInfo(ps, flags, userId); 3177 } 3178 } 3179 if (p == null) { 3180 p = mPackages.get(packageName); 3181 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3182 return null; 3183 } 3184 } 3185 if (DEBUG_PACKAGE_INFO) 3186 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3187 if (p != null) { 3188 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3189 } 3190 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3191 final PackageSetting ps = mSettings.mPackages.get(packageName); 3192 return generatePackageInfo(ps, flags, userId); 3193 } 3194 } 3195 return null; 3196 } 3197 3198 @Override 3199 public String[] currentToCanonicalPackageNames(String[] names) { 3200 String[] out = new String[names.length]; 3201 // reader 3202 synchronized (mPackages) { 3203 for (int i=names.length-1; i>=0; i--) { 3204 PackageSetting ps = mSettings.mPackages.get(names[i]); 3205 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3206 } 3207 } 3208 return out; 3209 } 3210 3211 @Override 3212 public String[] canonicalToCurrentPackageNames(String[] names) { 3213 String[] out = new String[names.length]; 3214 // reader 3215 synchronized (mPackages) { 3216 for (int i=names.length-1; i>=0; i--) { 3217 String cur = mSettings.getRenamedPackageLPr(names[i]); 3218 out[i] = cur != null ? cur : names[i]; 3219 } 3220 } 3221 return out; 3222 } 3223 3224 @Override 3225 public int getPackageUid(String packageName, int flags, int userId) { 3226 if (!sUserManager.exists(userId)) return -1; 3227 flags = updateFlagsForPackage(flags, userId, packageName); 3228 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3229 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3230 3231 // reader 3232 synchronized (mPackages) { 3233 final PackageParser.Package p = mPackages.get(packageName); 3234 if (p != null && p.isMatch(flags)) { 3235 return UserHandle.getUid(userId, p.applicationInfo.uid); 3236 } 3237 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3238 final PackageSetting ps = mSettings.mPackages.get(packageName); 3239 if (ps != null && ps.isMatch(flags)) { 3240 return UserHandle.getUid(userId, ps.appId); 3241 } 3242 } 3243 } 3244 3245 return -1; 3246 } 3247 3248 @Override 3249 public int[] getPackageGids(String packageName, int flags, int userId) { 3250 if (!sUserManager.exists(userId)) return null; 3251 flags = updateFlagsForPackage(flags, userId, packageName); 3252 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3253 false /* requireFullPermission */, false /* checkShell */, 3254 "getPackageGids"); 3255 3256 // reader 3257 synchronized (mPackages) { 3258 final PackageParser.Package p = mPackages.get(packageName); 3259 if (p != null && p.isMatch(flags)) { 3260 PackageSetting ps = (PackageSetting) p.mExtras; 3261 return ps.getPermissionsState().computeGids(userId); 3262 } 3263 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3264 final PackageSetting ps = mSettings.mPackages.get(packageName); 3265 if (ps != null && ps.isMatch(flags)) { 3266 return ps.getPermissionsState().computeGids(userId); 3267 } 3268 } 3269 } 3270 3271 return null; 3272 } 3273 3274 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3275 if (bp.perm != null) { 3276 return PackageParser.generatePermissionInfo(bp.perm, flags); 3277 } 3278 PermissionInfo pi = new PermissionInfo(); 3279 pi.name = bp.name; 3280 pi.packageName = bp.sourcePackage; 3281 pi.nonLocalizedLabel = bp.name; 3282 pi.protectionLevel = bp.protectionLevel; 3283 return pi; 3284 } 3285 3286 @Override 3287 public PermissionInfo getPermissionInfo(String name, int flags) { 3288 // reader 3289 synchronized (mPackages) { 3290 final BasePermission p = mSettings.mPermissions.get(name); 3291 if (p != null) { 3292 return generatePermissionInfo(p, flags); 3293 } 3294 return null; 3295 } 3296 } 3297 3298 @Override 3299 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3300 int flags) { 3301 // reader 3302 synchronized (mPackages) { 3303 if (group != null && !mPermissionGroups.containsKey(group)) { 3304 // This is thrown as NameNotFoundException 3305 return null; 3306 } 3307 3308 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3309 for (BasePermission p : mSettings.mPermissions.values()) { 3310 if (group == null) { 3311 if (p.perm == null || p.perm.info.group == null) { 3312 out.add(generatePermissionInfo(p, flags)); 3313 } 3314 } else { 3315 if (p.perm != null && group.equals(p.perm.info.group)) { 3316 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3317 } 3318 } 3319 } 3320 return new ParceledListSlice<>(out); 3321 } 3322 } 3323 3324 @Override 3325 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3326 // reader 3327 synchronized (mPackages) { 3328 return PackageParser.generatePermissionGroupInfo( 3329 mPermissionGroups.get(name), flags); 3330 } 3331 } 3332 3333 @Override 3334 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3335 // reader 3336 synchronized (mPackages) { 3337 final int N = mPermissionGroups.size(); 3338 ArrayList<PermissionGroupInfo> out 3339 = new ArrayList<PermissionGroupInfo>(N); 3340 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3341 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3342 } 3343 return new ParceledListSlice<>(out); 3344 } 3345 } 3346 3347 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3348 int userId) { 3349 if (!sUserManager.exists(userId)) return null; 3350 PackageSetting ps = mSettings.mPackages.get(packageName); 3351 if (ps != null) { 3352 if (ps.pkg == null) { 3353 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3354 if (pInfo != null) { 3355 return pInfo.applicationInfo; 3356 } 3357 return null; 3358 } 3359 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3360 ps.readUserState(userId), userId); 3361 } 3362 return null; 3363 } 3364 3365 @Override 3366 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3367 if (!sUserManager.exists(userId)) return null; 3368 flags = updateFlagsForApplication(flags, userId, packageName); 3369 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3370 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3371 // writer 3372 synchronized (mPackages) { 3373 PackageParser.Package p = mPackages.get(packageName); 3374 if (DEBUG_PACKAGE_INFO) Log.v( 3375 TAG, "getApplicationInfo " + packageName 3376 + ": " + p); 3377 if (p != null) { 3378 PackageSetting ps = mSettings.mPackages.get(packageName); 3379 if (ps == null) return null; 3380 // Note: isEnabledLP() does not apply here - always return info 3381 return PackageParser.generateApplicationInfo( 3382 p, flags, ps.readUserState(userId), userId); 3383 } 3384 if ("android".equals(packageName)||"system".equals(packageName)) { 3385 return mAndroidApplication; 3386 } 3387 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3388 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3389 } 3390 } 3391 return null; 3392 } 3393 3394 @Override 3395 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3396 final IPackageDataObserver observer) { 3397 mContext.enforceCallingOrSelfPermission( 3398 android.Manifest.permission.CLEAR_APP_CACHE, null); 3399 // Queue up an async operation since clearing cache may take a little while. 3400 mHandler.post(new Runnable() { 3401 public void run() { 3402 mHandler.removeCallbacks(this); 3403 boolean success = true; 3404 synchronized (mInstallLock) { 3405 try { 3406 mInstaller.freeCache(volumeUuid, freeStorageSize); 3407 } catch (InstallerException e) { 3408 Slog.w(TAG, "Couldn't clear application caches: " + e); 3409 success = false; 3410 } 3411 } 3412 if (observer != null) { 3413 try { 3414 observer.onRemoveCompleted(null, success); 3415 } catch (RemoteException e) { 3416 Slog.w(TAG, "RemoveException when invoking call back"); 3417 } 3418 } 3419 } 3420 }); 3421 } 3422 3423 @Override 3424 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3425 final IntentSender pi) { 3426 mContext.enforceCallingOrSelfPermission( 3427 android.Manifest.permission.CLEAR_APP_CACHE, null); 3428 // Queue up an async operation since clearing cache may take a little while. 3429 mHandler.post(new Runnable() { 3430 public void run() { 3431 mHandler.removeCallbacks(this); 3432 boolean success = true; 3433 synchronized (mInstallLock) { 3434 try { 3435 mInstaller.freeCache(volumeUuid, freeStorageSize); 3436 } catch (InstallerException e) { 3437 Slog.w(TAG, "Couldn't clear application caches: " + e); 3438 success = false; 3439 } 3440 } 3441 if(pi != null) { 3442 try { 3443 // Callback via pending intent 3444 int code = success ? 1 : 0; 3445 pi.sendIntent(null, code, null, 3446 null, null); 3447 } catch (SendIntentException e1) { 3448 Slog.i(TAG, "Failed to send pending intent"); 3449 } 3450 } 3451 } 3452 }); 3453 } 3454 3455 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3456 synchronized (mInstallLock) { 3457 try { 3458 mInstaller.freeCache(volumeUuid, freeStorageSize); 3459 } catch (InstallerException e) { 3460 throw new IOException("Failed to free enough space", e); 3461 } 3462 } 3463 } 3464 3465 /** 3466 * Update given flags based on encryption status of current user. 3467 */ 3468 private int updateFlags(int flags, int userId) { 3469 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3470 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3471 // Caller expressed an explicit opinion about what encryption 3472 // aware/unaware components they want to see, so fall through and 3473 // give them what they want 3474 } else { 3475 // Caller expressed no opinion, so match based on user state 3476 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3477 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3478 } else { 3479 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3480 } 3481 } 3482 return flags; 3483 } 3484 3485 private UserManagerInternal getUserManagerInternal() { 3486 if (mUserManagerInternal == null) { 3487 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3488 } 3489 return mUserManagerInternal; 3490 } 3491 3492 /** 3493 * Update given flags when being used to request {@link PackageInfo}. 3494 */ 3495 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3496 boolean triaged = true; 3497 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3498 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3499 // Caller is asking for component details, so they'd better be 3500 // asking for specific encryption matching behavior, or be triaged 3501 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3502 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3503 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3504 triaged = false; 3505 } 3506 } 3507 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3508 | PackageManager.MATCH_SYSTEM_ONLY 3509 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3510 triaged = false; 3511 } 3512 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3513 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3514 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3515 } 3516 return updateFlags(flags, userId); 3517 } 3518 3519 /** 3520 * Update given flags when being used to request {@link ApplicationInfo}. 3521 */ 3522 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3523 return updateFlagsForPackage(flags, userId, cookie); 3524 } 3525 3526 /** 3527 * Update given flags when being used to request {@link ComponentInfo}. 3528 */ 3529 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3530 if (cookie instanceof Intent) { 3531 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3532 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3533 } 3534 } 3535 3536 boolean triaged = true; 3537 // Caller is asking for component details, so they'd better be 3538 // asking for specific encryption matching behavior, or be triaged 3539 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3540 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3541 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3542 triaged = false; 3543 } 3544 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3545 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3546 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3547 } 3548 3549 return updateFlags(flags, userId); 3550 } 3551 3552 /** 3553 * Update given flags when being used to request {@link ResolveInfo}. 3554 */ 3555 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3556 // Safe mode means we shouldn't match any third-party components 3557 if (mSafeMode) { 3558 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3559 } 3560 3561 return updateFlagsForComponent(flags, userId, cookie); 3562 } 3563 3564 @Override 3565 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3566 if (!sUserManager.exists(userId)) return null; 3567 flags = updateFlagsForComponent(flags, userId, component); 3568 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3569 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3570 synchronized (mPackages) { 3571 PackageParser.Activity a = mActivities.mActivities.get(component); 3572 3573 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3574 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3575 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3576 if (ps == null) return null; 3577 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3578 userId); 3579 } 3580 if (mResolveComponentName.equals(component)) { 3581 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3582 new PackageUserState(), userId); 3583 } 3584 } 3585 return null; 3586 } 3587 3588 @Override 3589 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3590 String resolvedType) { 3591 synchronized (mPackages) { 3592 if (component.equals(mResolveComponentName)) { 3593 // The resolver supports EVERYTHING! 3594 return true; 3595 } 3596 PackageParser.Activity a = mActivities.mActivities.get(component); 3597 if (a == null) { 3598 return false; 3599 } 3600 for (int i=0; i<a.intents.size(); i++) { 3601 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3602 intent.getData(), intent.getCategories(), TAG) >= 0) { 3603 return true; 3604 } 3605 } 3606 return false; 3607 } 3608 } 3609 3610 @Override 3611 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3612 if (!sUserManager.exists(userId)) return null; 3613 flags = updateFlagsForComponent(flags, userId, component); 3614 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3615 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3616 synchronized (mPackages) { 3617 PackageParser.Activity a = mReceivers.mActivities.get(component); 3618 if (DEBUG_PACKAGE_INFO) Log.v( 3619 TAG, "getReceiverInfo " + component + ": " + a); 3620 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3621 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3622 if (ps == null) return null; 3623 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3624 userId); 3625 } 3626 } 3627 return null; 3628 } 3629 3630 @Override 3631 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3632 if (!sUserManager.exists(userId)) return null; 3633 flags = updateFlagsForComponent(flags, userId, component); 3634 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3635 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3636 synchronized (mPackages) { 3637 PackageParser.Service s = mServices.mServices.get(component); 3638 if (DEBUG_PACKAGE_INFO) Log.v( 3639 TAG, "getServiceInfo " + component + ": " + s); 3640 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3641 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3642 if (ps == null) return null; 3643 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3644 userId); 3645 } 3646 } 3647 return null; 3648 } 3649 3650 @Override 3651 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3652 if (!sUserManager.exists(userId)) return null; 3653 flags = updateFlagsForComponent(flags, userId, component); 3654 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3655 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3656 synchronized (mPackages) { 3657 PackageParser.Provider p = mProviders.mProviders.get(component); 3658 if (DEBUG_PACKAGE_INFO) Log.v( 3659 TAG, "getProviderInfo " + component + ": " + p); 3660 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3661 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3662 if (ps == null) return null; 3663 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3664 userId); 3665 } 3666 } 3667 return null; 3668 } 3669 3670 @Override 3671 public String[] getSystemSharedLibraryNames() { 3672 Set<String> libSet; 3673 synchronized (mPackages) { 3674 libSet = mSharedLibraries.keySet(); 3675 int size = libSet.size(); 3676 if (size > 0) { 3677 String[] libs = new String[size]; 3678 libSet.toArray(libs); 3679 return libs; 3680 } 3681 } 3682 return null; 3683 } 3684 3685 @Override 3686 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3687 synchronized (mPackages) { 3688 return mServicesSystemSharedLibraryPackageName; 3689 } 3690 } 3691 3692 @Override 3693 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3694 synchronized (mPackages) { 3695 return mSharedSystemSharedLibraryPackageName; 3696 } 3697 } 3698 3699 @Override 3700 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3701 synchronized (mPackages) { 3702 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3703 3704 final FeatureInfo fi = new FeatureInfo(); 3705 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3706 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3707 res.add(fi); 3708 3709 return new ParceledListSlice<>(res); 3710 } 3711 } 3712 3713 @Override 3714 public boolean hasSystemFeature(String name, int version) { 3715 synchronized (mPackages) { 3716 final FeatureInfo feat = mAvailableFeatures.get(name); 3717 if (feat == null) { 3718 return false; 3719 } else { 3720 return feat.version >= version; 3721 } 3722 } 3723 } 3724 3725 @Override 3726 public int checkPermission(String permName, String pkgName, int userId) { 3727 if (!sUserManager.exists(userId)) { 3728 return PackageManager.PERMISSION_DENIED; 3729 } 3730 3731 synchronized (mPackages) { 3732 final PackageParser.Package p = mPackages.get(pkgName); 3733 if (p != null && p.mExtras != null) { 3734 final PackageSetting ps = (PackageSetting) p.mExtras; 3735 final PermissionsState permissionsState = ps.getPermissionsState(); 3736 if (permissionsState.hasPermission(permName, userId)) { 3737 return PackageManager.PERMISSION_GRANTED; 3738 } 3739 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3740 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3741 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3742 return PackageManager.PERMISSION_GRANTED; 3743 } 3744 } 3745 } 3746 3747 return PackageManager.PERMISSION_DENIED; 3748 } 3749 3750 @Override 3751 public int checkUidPermission(String permName, int uid) { 3752 final int userId = UserHandle.getUserId(uid); 3753 3754 if (!sUserManager.exists(userId)) { 3755 return PackageManager.PERMISSION_DENIED; 3756 } 3757 3758 synchronized (mPackages) { 3759 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3760 if (obj != null) { 3761 final SettingBase ps = (SettingBase) obj; 3762 final PermissionsState permissionsState = ps.getPermissionsState(); 3763 if (permissionsState.hasPermission(permName, userId)) { 3764 return PackageManager.PERMISSION_GRANTED; 3765 } 3766 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3767 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3768 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3769 return PackageManager.PERMISSION_GRANTED; 3770 } 3771 } else { 3772 ArraySet<String> perms = mSystemPermissions.get(uid); 3773 if (perms != null) { 3774 if (perms.contains(permName)) { 3775 return PackageManager.PERMISSION_GRANTED; 3776 } 3777 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3778 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3779 return PackageManager.PERMISSION_GRANTED; 3780 } 3781 } 3782 } 3783 } 3784 3785 return PackageManager.PERMISSION_DENIED; 3786 } 3787 3788 @Override 3789 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3790 if (UserHandle.getCallingUserId() != userId) { 3791 mContext.enforceCallingPermission( 3792 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3793 "isPermissionRevokedByPolicy for user " + userId); 3794 } 3795 3796 if (checkPermission(permission, packageName, userId) 3797 == PackageManager.PERMISSION_GRANTED) { 3798 return false; 3799 } 3800 3801 final long identity = Binder.clearCallingIdentity(); 3802 try { 3803 final int flags = getPermissionFlags(permission, packageName, userId); 3804 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3805 } finally { 3806 Binder.restoreCallingIdentity(identity); 3807 } 3808 } 3809 3810 @Override 3811 public String getPermissionControllerPackageName() { 3812 synchronized (mPackages) { 3813 return mRequiredInstallerPackage; 3814 } 3815 } 3816 3817 /** 3818 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3819 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3820 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3821 * @param message the message to log on security exception 3822 */ 3823 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3824 boolean checkShell, String message) { 3825 if (userId < 0) { 3826 throw new IllegalArgumentException("Invalid userId " + userId); 3827 } 3828 if (checkShell) { 3829 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3830 } 3831 if (userId == UserHandle.getUserId(callingUid)) return; 3832 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3833 if (requireFullPermission) { 3834 mContext.enforceCallingOrSelfPermission( 3835 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3836 } else { 3837 try { 3838 mContext.enforceCallingOrSelfPermission( 3839 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3840 } catch (SecurityException se) { 3841 mContext.enforceCallingOrSelfPermission( 3842 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3843 } 3844 } 3845 } 3846 } 3847 3848 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3849 if (callingUid == Process.SHELL_UID) { 3850 if (userHandle >= 0 3851 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3852 throw new SecurityException("Shell does not have permission to access user " 3853 + userHandle); 3854 } else if (userHandle < 0) { 3855 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3856 + Debug.getCallers(3)); 3857 } 3858 } 3859 } 3860 3861 private BasePermission findPermissionTreeLP(String permName) { 3862 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3863 if (permName.startsWith(bp.name) && 3864 permName.length() > bp.name.length() && 3865 permName.charAt(bp.name.length()) == '.') { 3866 return bp; 3867 } 3868 } 3869 return null; 3870 } 3871 3872 private BasePermission checkPermissionTreeLP(String permName) { 3873 if (permName != null) { 3874 BasePermission bp = findPermissionTreeLP(permName); 3875 if (bp != null) { 3876 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3877 return bp; 3878 } 3879 throw new SecurityException("Calling uid " 3880 + Binder.getCallingUid() 3881 + " is not allowed to add to permission tree " 3882 + bp.name + " owned by uid " + bp.uid); 3883 } 3884 } 3885 throw new SecurityException("No permission tree found for " + permName); 3886 } 3887 3888 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3889 if (s1 == null) { 3890 return s2 == null; 3891 } 3892 if (s2 == null) { 3893 return false; 3894 } 3895 if (s1.getClass() != s2.getClass()) { 3896 return false; 3897 } 3898 return s1.equals(s2); 3899 } 3900 3901 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3902 if (pi1.icon != pi2.icon) return false; 3903 if (pi1.logo != pi2.logo) return false; 3904 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3905 if (!compareStrings(pi1.name, pi2.name)) return false; 3906 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3907 // We'll take care of setting this one. 3908 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3909 // These are not currently stored in settings. 3910 //if (!compareStrings(pi1.group, pi2.group)) return false; 3911 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3912 //if (pi1.labelRes != pi2.labelRes) return false; 3913 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3914 return true; 3915 } 3916 3917 int permissionInfoFootprint(PermissionInfo info) { 3918 int size = info.name.length(); 3919 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3920 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3921 return size; 3922 } 3923 3924 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3925 int size = 0; 3926 for (BasePermission perm : mSettings.mPermissions.values()) { 3927 if (perm.uid == tree.uid) { 3928 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3929 } 3930 } 3931 return size; 3932 } 3933 3934 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3935 // We calculate the max size of permissions defined by this uid and throw 3936 // if that plus the size of 'info' would exceed our stated maximum. 3937 if (tree.uid != Process.SYSTEM_UID) { 3938 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3939 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3940 throw new SecurityException("Permission tree size cap exceeded"); 3941 } 3942 } 3943 } 3944 3945 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3946 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3947 throw new SecurityException("Label must be specified in permission"); 3948 } 3949 BasePermission tree = checkPermissionTreeLP(info.name); 3950 BasePermission bp = mSettings.mPermissions.get(info.name); 3951 boolean added = bp == null; 3952 boolean changed = true; 3953 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3954 if (added) { 3955 enforcePermissionCapLocked(info, tree); 3956 bp = new BasePermission(info.name, tree.sourcePackage, 3957 BasePermission.TYPE_DYNAMIC); 3958 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3959 throw new SecurityException( 3960 "Not allowed to modify non-dynamic permission " 3961 + info.name); 3962 } else { 3963 if (bp.protectionLevel == fixedLevel 3964 && bp.perm.owner.equals(tree.perm.owner) 3965 && bp.uid == tree.uid 3966 && comparePermissionInfos(bp.perm.info, info)) { 3967 changed = false; 3968 } 3969 } 3970 bp.protectionLevel = fixedLevel; 3971 info = new PermissionInfo(info); 3972 info.protectionLevel = fixedLevel; 3973 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3974 bp.perm.info.packageName = tree.perm.info.packageName; 3975 bp.uid = tree.uid; 3976 if (added) { 3977 mSettings.mPermissions.put(info.name, bp); 3978 } 3979 if (changed) { 3980 if (!async) { 3981 mSettings.writeLPr(); 3982 } else { 3983 scheduleWriteSettingsLocked(); 3984 } 3985 } 3986 return added; 3987 } 3988 3989 @Override 3990 public boolean addPermission(PermissionInfo info) { 3991 synchronized (mPackages) { 3992 return addPermissionLocked(info, false); 3993 } 3994 } 3995 3996 @Override 3997 public boolean addPermissionAsync(PermissionInfo info) { 3998 synchronized (mPackages) { 3999 return addPermissionLocked(info, true); 4000 } 4001 } 4002 4003 @Override 4004 public void removePermission(String name) { 4005 synchronized (mPackages) { 4006 checkPermissionTreeLP(name); 4007 BasePermission bp = mSettings.mPermissions.get(name); 4008 if (bp != null) { 4009 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4010 throw new SecurityException( 4011 "Not allowed to modify non-dynamic permission " 4012 + name); 4013 } 4014 mSettings.mPermissions.remove(name); 4015 mSettings.writeLPr(); 4016 } 4017 } 4018 } 4019 4020 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4021 BasePermission bp) { 4022 int index = pkg.requestedPermissions.indexOf(bp.name); 4023 if (index == -1) { 4024 throw new SecurityException("Package " + pkg.packageName 4025 + " has not requested permission " + bp.name); 4026 } 4027 if (!bp.isRuntime() && !bp.isDevelopment()) { 4028 throw new SecurityException("Permission " + bp.name 4029 + " is not a changeable permission type"); 4030 } 4031 } 4032 4033 @Override 4034 public void grantRuntimePermission(String packageName, String name, final int userId) { 4035 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4036 } 4037 4038 private void grantRuntimePermission(String packageName, String name, final int userId, 4039 boolean overridePolicy) { 4040 if (!sUserManager.exists(userId)) { 4041 Log.e(TAG, "No such user:" + userId); 4042 return; 4043 } 4044 4045 mContext.enforceCallingOrSelfPermission( 4046 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4047 "grantRuntimePermission"); 4048 4049 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4050 true /* requireFullPermission */, true /* checkShell */, 4051 "grantRuntimePermission"); 4052 4053 final int uid; 4054 final SettingBase sb; 4055 4056 synchronized (mPackages) { 4057 final PackageParser.Package pkg = mPackages.get(packageName); 4058 if (pkg == null) { 4059 throw new IllegalArgumentException("Unknown package: " + packageName); 4060 } 4061 4062 final BasePermission bp = mSettings.mPermissions.get(name); 4063 if (bp == null) { 4064 throw new IllegalArgumentException("Unknown permission: " + name); 4065 } 4066 4067 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4068 4069 // If a permission review is required for legacy apps we represent 4070 // their permissions as always granted runtime ones since we need 4071 // to keep the review required permission flag per user while an 4072 // install permission's state is shared across all users. 4073 if (mPermissionReviewRequired 4074 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4075 && bp.isRuntime()) { 4076 return; 4077 } 4078 4079 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4080 sb = (SettingBase) pkg.mExtras; 4081 if (sb == null) { 4082 throw new IllegalArgumentException("Unknown package: " + packageName); 4083 } 4084 4085 final PermissionsState permissionsState = sb.getPermissionsState(); 4086 4087 final int flags = permissionsState.getPermissionFlags(name, userId); 4088 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4089 throw new SecurityException("Cannot grant system fixed permission " 4090 + name + " for package " + packageName); 4091 } 4092 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4093 throw new SecurityException("Cannot grant policy fixed permission " 4094 + name + " for package " + packageName); 4095 } 4096 4097 if (bp.isDevelopment()) { 4098 // Development permissions must be handled specially, since they are not 4099 // normal runtime permissions. For now they apply to all users. 4100 if (permissionsState.grantInstallPermission(bp) != 4101 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4102 scheduleWriteSettingsLocked(); 4103 } 4104 return; 4105 } 4106 4107 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 4108 throw new SecurityException("Cannot grant non-ephemeral permission" 4109 + name + " for package " + packageName); 4110 } 4111 4112 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4113 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4114 return; 4115 } 4116 4117 final int result = permissionsState.grantRuntimePermission(bp, userId); 4118 switch (result) { 4119 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4120 return; 4121 } 4122 4123 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4124 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4125 mHandler.post(new Runnable() { 4126 @Override 4127 public void run() { 4128 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4129 } 4130 }); 4131 } 4132 break; 4133 } 4134 4135 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4136 4137 // Not critical if that is lost - app has to request again. 4138 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4139 } 4140 4141 // Only need to do this if user is initialized. Otherwise it's a new user 4142 // and there are no processes running as the user yet and there's no need 4143 // to make an expensive call to remount processes for the changed permissions. 4144 if (READ_EXTERNAL_STORAGE.equals(name) 4145 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4146 final long token = Binder.clearCallingIdentity(); 4147 try { 4148 if (sUserManager.isInitialized(userId)) { 4149 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4150 StorageManagerInternal.class); 4151 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4152 } 4153 } finally { 4154 Binder.restoreCallingIdentity(token); 4155 } 4156 } 4157 } 4158 4159 @Override 4160 public void revokeRuntimePermission(String packageName, String name, int userId) { 4161 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4162 } 4163 4164 private void revokeRuntimePermission(String packageName, String name, int userId, 4165 boolean overridePolicy) { 4166 if (!sUserManager.exists(userId)) { 4167 Log.e(TAG, "No such user:" + userId); 4168 return; 4169 } 4170 4171 mContext.enforceCallingOrSelfPermission( 4172 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4173 "revokeRuntimePermission"); 4174 4175 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4176 true /* requireFullPermission */, true /* checkShell */, 4177 "revokeRuntimePermission"); 4178 4179 final int appId; 4180 4181 synchronized (mPackages) { 4182 final PackageParser.Package pkg = mPackages.get(packageName); 4183 if (pkg == null) { 4184 throw new IllegalArgumentException("Unknown package: " + packageName); 4185 } 4186 4187 final BasePermission bp = mSettings.mPermissions.get(name); 4188 if (bp == null) { 4189 throw new IllegalArgumentException("Unknown permission: " + name); 4190 } 4191 4192 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4193 4194 // If a permission review is required for legacy apps we represent 4195 // their permissions as always granted runtime ones since we need 4196 // to keep the review required permission flag per user while an 4197 // install permission's state is shared across all users. 4198 if (mPermissionReviewRequired 4199 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4200 && bp.isRuntime()) { 4201 return; 4202 } 4203 4204 SettingBase sb = (SettingBase) pkg.mExtras; 4205 if (sb == null) { 4206 throw new IllegalArgumentException("Unknown package: " + packageName); 4207 } 4208 4209 final PermissionsState permissionsState = sb.getPermissionsState(); 4210 4211 final int flags = permissionsState.getPermissionFlags(name, userId); 4212 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4213 throw new SecurityException("Cannot revoke system fixed permission " 4214 + name + " for package " + packageName); 4215 } 4216 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4217 throw new SecurityException("Cannot revoke policy fixed permission " 4218 + name + " for package " + packageName); 4219 } 4220 4221 if (bp.isDevelopment()) { 4222 // Development permissions must be handled specially, since they are not 4223 // normal runtime permissions. For now they apply to all users. 4224 if (permissionsState.revokeInstallPermission(bp) != 4225 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4226 scheduleWriteSettingsLocked(); 4227 } 4228 return; 4229 } 4230 4231 if (permissionsState.revokeRuntimePermission(bp, userId) == 4232 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4233 return; 4234 } 4235 4236 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4237 4238 // Critical, after this call app should never have the permission. 4239 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4240 4241 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4242 } 4243 4244 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4245 } 4246 4247 @Override 4248 public void resetRuntimePermissions() { 4249 mContext.enforceCallingOrSelfPermission( 4250 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4251 "revokeRuntimePermission"); 4252 4253 int callingUid = Binder.getCallingUid(); 4254 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4255 mContext.enforceCallingOrSelfPermission( 4256 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4257 "resetRuntimePermissions"); 4258 } 4259 4260 synchronized (mPackages) { 4261 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4262 for (int userId : UserManagerService.getInstance().getUserIds()) { 4263 final int packageCount = mPackages.size(); 4264 for (int i = 0; i < packageCount; i++) { 4265 PackageParser.Package pkg = mPackages.valueAt(i); 4266 if (!(pkg.mExtras instanceof PackageSetting)) { 4267 continue; 4268 } 4269 PackageSetting ps = (PackageSetting) pkg.mExtras; 4270 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4271 } 4272 } 4273 } 4274 } 4275 4276 @Override 4277 public int getPermissionFlags(String name, String packageName, int userId) { 4278 if (!sUserManager.exists(userId)) { 4279 return 0; 4280 } 4281 4282 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4283 4284 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4285 true /* requireFullPermission */, false /* checkShell */, 4286 "getPermissionFlags"); 4287 4288 synchronized (mPackages) { 4289 final PackageParser.Package pkg = mPackages.get(packageName); 4290 if (pkg == null) { 4291 return 0; 4292 } 4293 4294 final BasePermission bp = mSettings.mPermissions.get(name); 4295 if (bp == null) { 4296 return 0; 4297 } 4298 4299 SettingBase sb = (SettingBase) pkg.mExtras; 4300 if (sb == null) { 4301 return 0; 4302 } 4303 4304 PermissionsState permissionsState = sb.getPermissionsState(); 4305 return permissionsState.getPermissionFlags(name, userId); 4306 } 4307 } 4308 4309 @Override 4310 public void updatePermissionFlags(String name, String packageName, int flagMask, 4311 int flagValues, int userId) { 4312 if (!sUserManager.exists(userId)) { 4313 return; 4314 } 4315 4316 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4317 4318 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4319 true /* requireFullPermission */, true /* checkShell */, 4320 "updatePermissionFlags"); 4321 4322 // Only the system can change these flags and nothing else. 4323 if (getCallingUid() != Process.SYSTEM_UID) { 4324 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4325 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4326 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4327 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4328 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4329 } 4330 4331 synchronized (mPackages) { 4332 final PackageParser.Package pkg = mPackages.get(packageName); 4333 if (pkg == null) { 4334 throw new IllegalArgumentException("Unknown package: " + packageName); 4335 } 4336 4337 final BasePermission bp = mSettings.mPermissions.get(name); 4338 if (bp == null) { 4339 throw new IllegalArgumentException("Unknown permission: " + name); 4340 } 4341 4342 SettingBase sb = (SettingBase) pkg.mExtras; 4343 if (sb == null) { 4344 throw new IllegalArgumentException("Unknown package: " + packageName); 4345 } 4346 4347 PermissionsState permissionsState = sb.getPermissionsState(); 4348 4349 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4350 4351 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4352 // Install and runtime permissions are stored in different places, 4353 // so figure out what permission changed and persist the change. 4354 if (permissionsState.getInstallPermissionState(name) != null) { 4355 scheduleWriteSettingsLocked(); 4356 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4357 || hadState) { 4358 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4359 } 4360 } 4361 } 4362 } 4363 4364 /** 4365 * Update the permission flags for all packages and runtime permissions of a user in order 4366 * to allow device or profile owner to remove POLICY_FIXED. 4367 */ 4368 @Override 4369 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4370 if (!sUserManager.exists(userId)) { 4371 return; 4372 } 4373 4374 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4375 4376 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4377 true /* requireFullPermission */, true /* checkShell */, 4378 "updatePermissionFlagsForAllApps"); 4379 4380 // Only the system can change system fixed flags. 4381 if (getCallingUid() != Process.SYSTEM_UID) { 4382 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4383 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4384 } 4385 4386 synchronized (mPackages) { 4387 boolean changed = false; 4388 final int packageCount = mPackages.size(); 4389 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4390 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4391 SettingBase sb = (SettingBase) pkg.mExtras; 4392 if (sb == null) { 4393 continue; 4394 } 4395 PermissionsState permissionsState = sb.getPermissionsState(); 4396 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4397 userId, flagMask, flagValues); 4398 } 4399 if (changed) { 4400 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4401 } 4402 } 4403 } 4404 4405 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4406 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4407 != PackageManager.PERMISSION_GRANTED 4408 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4409 != PackageManager.PERMISSION_GRANTED) { 4410 throw new SecurityException(message + " requires " 4411 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4412 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4413 } 4414 } 4415 4416 @Override 4417 public boolean shouldShowRequestPermissionRationale(String permissionName, 4418 String packageName, int userId) { 4419 if (UserHandle.getCallingUserId() != userId) { 4420 mContext.enforceCallingPermission( 4421 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4422 "canShowRequestPermissionRationale for user " + userId); 4423 } 4424 4425 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4426 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4427 return false; 4428 } 4429 4430 if (checkPermission(permissionName, packageName, userId) 4431 == PackageManager.PERMISSION_GRANTED) { 4432 return false; 4433 } 4434 4435 final int flags; 4436 4437 final long identity = Binder.clearCallingIdentity(); 4438 try { 4439 flags = getPermissionFlags(permissionName, 4440 packageName, userId); 4441 } finally { 4442 Binder.restoreCallingIdentity(identity); 4443 } 4444 4445 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4446 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4447 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4448 4449 if ((flags & fixedFlags) != 0) { 4450 return false; 4451 } 4452 4453 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4454 } 4455 4456 @Override 4457 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4458 mContext.enforceCallingOrSelfPermission( 4459 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4460 "addOnPermissionsChangeListener"); 4461 4462 synchronized (mPackages) { 4463 mOnPermissionChangeListeners.addListenerLocked(listener); 4464 } 4465 } 4466 4467 @Override 4468 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4469 synchronized (mPackages) { 4470 mOnPermissionChangeListeners.removeListenerLocked(listener); 4471 } 4472 } 4473 4474 @Override 4475 public boolean isProtectedBroadcast(String actionName) { 4476 synchronized (mPackages) { 4477 if (mProtectedBroadcasts.contains(actionName)) { 4478 return true; 4479 } else if (actionName != null) { 4480 // TODO: remove these terrible hacks 4481 if (actionName.startsWith("android.net.netmon.lingerExpired") 4482 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4483 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4484 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4485 return true; 4486 } 4487 } 4488 } 4489 return false; 4490 } 4491 4492 @Override 4493 public int checkSignatures(String pkg1, String pkg2) { 4494 synchronized (mPackages) { 4495 final PackageParser.Package p1 = mPackages.get(pkg1); 4496 final PackageParser.Package p2 = mPackages.get(pkg2); 4497 if (p1 == null || p1.mExtras == null 4498 || p2 == null || p2.mExtras == null) { 4499 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4500 } 4501 return compareSignatures(p1.mSignatures, p2.mSignatures); 4502 } 4503 } 4504 4505 @Override 4506 public int checkUidSignatures(int uid1, int uid2) { 4507 // Map to base uids. 4508 uid1 = UserHandle.getAppId(uid1); 4509 uid2 = UserHandle.getAppId(uid2); 4510 // reader 4511 synchronized (mPackages) { 4512 Signature[] s1; 4513 Signature[] s2; 4514 Object obj = mSettings.getUserIdLPr(uid1); 4515 if (obj != null) { 4516 if (obj instanceof SharedUserSetting) { 4517 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4518 } else if (obj instanceof PackageSetting) { 4519 s1 = ((PackageSetting)obj).signatures.mSignatures; 4520 } else { 4521 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4522 } 4523 } else { 4524 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4525 } 4526 obj = mSettings.getUserIdLPr(uid2); 4527 if (obj != null) { 4528 if (obj instanceof SharedUserSetting) { 4529 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4530 } else if (obj instanceof PackageSetting) { 4531 s2 = ((PackageSetting)obj).signatures.mSignatures; 4532 } else { 4533 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4534 } 4535 } else { 4536 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4537 } 4538 return compareSignatures(s1, s2); 4539 } 4540 } 4541 4542 /** 4543 * This method should typically only be used when granting or revoking 4544 * permissions, since the app may immediately restart after this call. 4545 * <p> 4546 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4547 * guard your work against the app being relaunched. 4548 */ 4549 private void killUid(int appId, int userId, String reason) { 4550 final long identity = Binder.clearCallingIdentity(); 4551 try { 4552 IActivityManager am = ActivityManager.getService(); 4553 if (am != null) { 4554 try { 4555 am.killUid(appId, userId, reason); 4556 } catch (RemoteException e) { 4557 /* ignore - same process */ 4558 } 4559 } 4560 } finally { 4561 Binder.restoreCallingIdentity(identity); 4562 } 4563 } 4564 4565 /** 4566 * Compares two sets of signatures. Returns: 4567 * <br /> 4568 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4569 * <br /> 4570 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4571 * <br /> 4572 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4573 * <br /> 4574 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4575 * <br /> 4576 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4577 */ 4578 static int compareSignatures(Signature[] s1, Signature[] s2) { 4579 if (s1 == null) { 4580 return s2 == null 4581 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4582 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4583 } 4584 4585 if (s2 == null) { 4586 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4587 } 4588 4589 if (s1.length != s2.length) { 4590 return PackageManager.SIGNATURE_NO_MATCH; 4591 } 4592 4593 // Since both signature sets are of size 1, we can compare without HashSets. 4594 if (s1.length == 1) { 4595 return s1[0].equals(s2[0]) ? 4596 PackageManager.SIGNATURE_MATCH : 4597 PackageManager.SIGNATURE_NO_MATCH; 4598 } 4599 4600 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4601 for (Signature sig : s1) { 4602 set1.add(sig); 4603 } 4604 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4605 for (Signature sig : s2) { 4606 set2.add(sig); 4607 } 4608 // Make sure s2 contains all signatures in s1. 4609 if (set1.equals(set2)) { 4610 return PackageManager.SIGNATURE_MATCH; 4611 } 4612 return PackageManager.SIGNATURE_NO_MATCH; 4613 } 4614 4615 /** 4616 * If the database version for this type of package (internal storage or 4617 * external storage) is less than the version where package signatures 4618 * were updated, return true. 4619 */ 4620 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4621 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4622 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4623 } 4624 4625 /** 4626 * Used for backward compatibility to make sure any packages with 4627 * certificate chains get upgraded to the new style. {@code existingSigs} 4628 * will be in the old format (since they were stored on disk from before the 4629 * system upgrade) and {@code scannedSigs} will be in the newer format. 4630 */ 4631 private int compareSignaturesCompat(PackageSignatures existingSigs, 4632 PackageParser.Package scannedPkg) { 4633 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4634 return PackageManager.SIGNATURE_NO_MATCH; 4635 } 4636 4637 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4638 for (Signature sig : existingSigs.mSignatures) { 4639 existingSet.add(sig); 4640 } 4641 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4642 for (Signature sig : scannedPkg.mSignatures) { 4643 try { 4644 Signature[] chainSignatures = sig.getChainSignatures(); 4645 for (Signature chainSig : chainSignatures) { 4646 scannedCompatSet.add(chainSig); 4647 } 4648 } catch (CertificateEncodingException e) { 4649 scannedCompatSet.add(sig); 4650 } 4651 } 4652 /* 4653 * Make sure the expanded scanned set contains all signatures in the 4654 * existing one. 4655 */ 4656 if (scannedCompatSet.equals(existingSet)) { 4657 // Migrate the old signatures to the new scheme. 4658 existingSigs.assignSignatures(scannedPkg.mSignatures); 4659 // The new KeySets will be re-added later in the scanning process. 4660 synchronized (mPackages) { 4661 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4662 } 4663 return PackageManager.SIGNATURE_MATCH; 4664 } 4665 return PackageManager.SIGNATURE_NO_MATCH; 4666 } 4667 4668 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4669 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4670 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4671 } 4672 4673 private int compareSignaturesRecover(PackageSignatures existingSigs, 4674 PackageParser.Package scannedPkg) { 4675 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4676 return PackageManager.SIGNATURE_NO_MATCH; 4677 } 4678 4679 String msg = null; 4680 try { 4681 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4682 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4683 + scannedPkg.packageName); 4684 return PackageManager.SIGNATURE_MATCH; 4685 } 4686 } catch (CertificateException e) { 4687 msg = e.getMessage(); 4688 } 4689 4690 logCriticalInfo(Log.INFO, 4691 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4692 return PackageManager.SIGNATURE_NO_MATCH; 4693 } 4694 4695 @Override 4696 public List<String> getAllPackages() { 4697 synchronized (mPackages) { 4698 return new ArrayList<String>(mPackages.keySet()); 4699 } 4700 } 4701 4702 @Override 4703 public String[] getPackagesForUid(int uid) { 4704 final int userId = UserHandle.getUserId(uid); 4705 uid = UserHandle.getAppId(uid); 4706 // reader 4707 synchronized (mPackages) { 4708 Object obj = mSettings.getUserIdLPr(uid); 4709 if (obj instanceof SharedUserSetting) { 4710 final SharedUserSetting sus = (SharedUserSetting) obj; 4711 final int N = sus.packages.size(); 4712 String[] res = new String[N]; 4713 final Iterator<PackageSetting> it = sus.packages.iterator(); 4714 int i = 0; 4715 while (it.hasNext()) { 4716 PackageSetting ps = it.next(); 4717 if (ps.getInstalled(userId)) { 4718 res[i++] = ps.name; 4719 } else { 4720 res = ArrayUtils.removeElement(String.class, res, res[i]); 4721 } 4722 } 4723 return res; 4724 } else if (obj instanceof PackageSetting) { 4725 final PackageSetting ps = (PackageSetting) obj; 4726 return new String[] { ps.name }; 4727 } 4728 } 4729 return null; 4730 } 4731 4732 @Override 4733 public String getNameForUid(int uid) { 4734 // reader 4735 synchronized (mPackages) { 4736 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4737 if (obj instanceof SharedUserSetting) { 4738 final SharedUserSetting sus = (SharedUserSetting) obj; 4739 return sus.name + ":" + sus.userId; 4740 } else if (obj instanceof PackageSetting) { 4741 final PackageSetting ps = (PackageSetting) obj; 4742 return ps.name; 4743 } 4744 } 4745 return null; 4746 } 4747 4748 @Override 4749 public int getUidForSharedUser(String sharedUserName) { 4750 if(sharedUserName == null) { 4751 return -1; 4752 } 4753 // reader 4754 synchronized (mPackages) { 4755 SharedUserSetting suid; 4756 try { 4757 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4758 if (suid != null) { 4759 return suid.userId; 4760 } 4761 } catch (PackageManagerException ignore) { 4762 // can't happen, but, still need to catch it 4763 } 4764 return -1; 4765 } 4766 } 4767 4768 @Override 4769 public int getFlagsForUid(int uid) { 4770 synchronized (mPackages) { 4771 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4772 if (obj instanceof SharedUserSetting) { 4773 final SharedUserSetting sus = (SharedUserSetting) obj; 4774 return sus.pkgFlags; 4775 } else if (obj instanceof PackageSetting) { 4776 final PackageSetting ps = (PackageSetting) obj; 4777 return ps.pkgFlags; 4778 } 4779 } 4780 return 0; 4781 } 4782 4783 @Override 4784 public int getPrivateFlagsForUid(int uid) { 4785 synchronized (mPackages) { 4786 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4787 if (obj instanceof SharedUserSetting) { 4788 final SharedUserSetting sus = (SharedUserSetting) obj; 4789 return sus.pkgPrivateFlags; 4790 } else if (obj instanceof PackageSetting) { 4791 final PackageSetting ps = (PackageSetting) obj; 4792 return ps.pkgPrivateFlags; 4793 } 4794 } 4795 return 0; 4796 } 4797 4798 @Override 4799 public boolean isUidPrivileged(int uid) { 4800 uid = UserHandle.getAppId(uid); 4801 // reader 4802 synchronized (mPackages) { 4803 Object obj = mSettings.getUserIdLPr(uid); 4804 if (obj instanceof SharedUserSetting) { 4805 final SharedUserSetting sus = (SharedUserSetting) obj; 4806 final Iterator<PackageSetting> it = sus.packages.iterator(); 4807 while (it.hasNext()) { 4808 if (it.next().isPrivileged()) { 4809 return true; 4810 } 4811 } 4812 } else if (obj instanceof PackageSetting) { 4813 final PackageSetting ps = (PackageSetting) obj; 4814 return ps.isPrivileged(); 4815 } 4816 } 4817 return false; 4818 } 4819 4820 @Override 4821 public String[] getAppOpPermissionPackages(String permissionName) { 4822 synchronized (mPackages) { 4823 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4824 if (pkgs == null) { 4825 return null; 4826 } 4827 return pkgs.toArray(new String[pkgs.size()]); 4828 } 4829 } 4830 4831 @Override 4832 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4833 int flags, int userId) { 4834 try { 4835 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4836 4837 if (!sUserManager.exists(userId)) return null; 4838 flags = updateFlagsForResolve(flags, userId, intent); 4839 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4840 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4841 4842 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4843 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4844 flags, userId); 4845 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4846 4847 final ResolveInfo bestChoice = 4848 chooseBestActivity(intent, resolvedType, flags, query, userId); 4849 return bestChoice; 4850 } finally { 4851 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4852 } 4853 } 4854 4855 @Override 4856 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4857 IntentFilter filter, int match, ComponentName activity) { 4858 final int userId = UserHandle.getCallingUserId(); 4859 if (DEBUG_PREFERRED) { 4860 Log.v(TAG, "setLastChosenActivity intent=" + intent 4861 + " resolvedType=" + resolvedType 4862 + " flags=" + flags 4863 + " filter=" + filter 4864 + " match=" + match 4865 + " activity=" + activity); 4866 filter.dump(new PrintStreamPrinter(System.out), " "); 4867 } 4868 intent.setComponent(null); 4869 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4870 userId); 4871 // Find any earlier preferred or last chosen entries and nuke them 4872 findPreferredActivity(intent, resolvedType, 4873 flags, query, 0, false, true, false, userId); 4874 // Add the new activity as the last chosen for this filter 4875 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4876 "Setting last chosen"); 4877 } 4878 4879 @Override 4880 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4881 final int userId = UserHandle.getCallingUserId(); 4882 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4883 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4884 userId); 4885 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4886 false, false, false, userId); 4887 } 4888 4889 private boolean isEphemeralDisabled() { 4890 // ephemeral apps have been disabled across the board 4891 if (DISABLE_EPHEMERAL_APPS) { 4892 return true; 4893 } 4894 // system isn't up yet; can't read settings, so, assume no ephemeral apps 4895 if (!mSystemReady) { 4896 return true; 4897 } 4898 // we can't get a content resolver until the system is ready; these checks must happen last 4899 final ContentResolver resolver = mContext.getContentResolver(); 4900 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 4901 return true; 4902 } 4903 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 4904 } 4905 4906 private boolean isEphemeralAllowed( 4907 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 4908 boolean skipPackageCheck) { 4909 // Short circuit and return early if possible. 4910 if (isEphemeralDisabled()) { 4911 return false; 4912 } 4913 final int callingUser = UserHandle.getCallingUserId(); 4914 if (callingUser != UserHandle.USER_SYSTEM) { 4915 return false; 4916 } 4917 if (mEphemeralResolverConnection == null) { 4918 return false; 4919 } 4920 if (intent.getComponent() != null) { 4921 return false; 4922 } 4923 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 4924 return false; 4925 } 4926 if (!skipPackageCheck && intent.getPackage() != null) { 4927 return false; 4928 } 4929 final boolean isWebUri = hasWebURI(intent); 4930 if (!isWebUri || intent.getData().getHost() == null) { 4931 return false; 4932 } 4933 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4934 synchronized (mPackages) { 4935 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 4936 for (int n = 0; n < count; n++) { 4937 ResolveInfo info = resolvedActivities.get(n); 4938 String packageName = info.activityInfo.packageName; 4939 PackageSetting ps = mSettings.mPackages.get(packageName); 4940 if (ps != null) { 4941 // Try to get the status from User settings first 4942 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4943 int status = (int) (packedStatus >> 32); 4944 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4945 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4946 if (DEBUG_EPHEMERAL) { 4947 Slog.v(TAG, "DENY ephemeral apps;" 4948 + " pkg: " + packageName + ", status: " + status); 4949 } 4950 return false; 4951 } 4952 } 4953 } 4954 } 4955 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4956 return true; 4957 } 4958 4959 private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 4960 Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage, 4961 int userId) { 4962 final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO, 4963 new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent, 4964 callingPackage, userId)); 4965 mHandler.sendMessage(msg); 4966 } 4967 4968 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4969 int flags, List<ResolveInfo> query, int userId) { 4970 if (query != null) { 4971 final int N = query.size(); 4972 if (N == 1) { 4973 return query.get(0); 4974 } else if (N > 1) { 4975 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4976 // If there is more than one activity with the same priority, 4977 // then let the user decide between them. 4978 ResolveInfo r0 = query.get(0); 4979 ResolveInfo r1 = query.get(1); 4980 if (DEBUG_INTENT_MATCHING || debug) { 4981 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4982 + r1.activityInfo.name + "=" + r1.priority); 4983 } 4984 // If the first activity has a higher priority, or a different 4985 // default, then it is always desirable to pick it. 4986 if (r0.priority != r1.priority 4987 || r0.preferredOrder != r1.preferredOrder 4988 || r0.isDefault != r1.isDefault) { 4989 return query.get(0); 4990 } 4991 // If we have saved a preference for a preferred activity for 4992 // this Intent, use that. 4993 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4994 flags, query, r0.priority, true, false, debug, userId); 4995 if (ri != null) { 4996 return ri; 4997 } 4998 ri = new ResolveInfo(mResolveInfo); 4999 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5000 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5001 // If all of the options come from the same package, show the application's 5002 // label and icon instead of the generic resolver's. 5003 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5004 // and then throw away the ResolveInfo itself, meaning that the caller loses 5005 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5006 // a fallback for this case; we only set the target package's resources on 5007 // the ResolveInfo, not the ActivityInfo. 5008 final String intentPackage = intent.getPackage(); 5009 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5010 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5011 ri.resolvePackageName = intentPackage; 5012 if (userNeedsBadging(userId)) { 5013 ri.noResourceId = true; 5014 } else { 5015 ri.icon = appi.icon; 5016 } 5017 ri.iconResourceId = appi.icon; 5018 ri.labelRes = appi.labelRes; 5019 } 5020 ri.activityInfo.applicationInfo = new ApplicationInfo( 5021 ri.activityInfo.applicationInfo); 5022 if (userId != 0) { 5023 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5024 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5025 } 5026 // Make sure that the resolver is displayable in car mode 5027 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5028 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5029 return ri; 5030 } 5031 } 5032 return null; 5033 } 5034 5035 /** 5036 * Return true if the given list is not empty and all of its contents have 5037 * an activityInfo with the given package name. 5038 */ 5039 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5040 if (ArrayUtils.isEmpty(list)) { 5041 return false; 5042 } 5043 for (int i = 0, N = list.size(); i < N; i++) { 5044 final ResolveInfo ri = list.get(i); 5045 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5046 if (ai == null || !packageName.equals(ai.packageName)) { 5047 return false; 5048 } 5049 } 5050 return true; 5051 } 5052 5053 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5054 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5055 final int N = query.size(); 5056 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5057 .get(userId); 5058 // Get the list of persistent preferred activities that handle the intent 5059 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5060 List<PersistentPreferredActivity> pprefs = ppir != null 5061 ? ppir.queryIntent(intent, resolvedType, 5062 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5063 : null; 5064 if (pprefs != null && pprefs.size() > 0) { 5065 final int M = pprefs.size(); 5066 for (int i=0; i<M; i++) { 5067 final PersistentPreferredActivity ppa = pprefs.get(i); 5068 if (DEBUG_PREFERRED || debug) { 5069 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5070 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5071 + "\n component=" + ppa.mComponent); 5072 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5073 } 5074 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5075 flags | MATCH_DISABLED_COMPONENTS, userId); 5076 if (DEBUG_PREFERRED || debug) { 5077 Slog.v(TAG, "Found persistent preferred activity:"); 5078 if (ai != null) { 5079 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5080 } else { 5081 Slog.v(TAG, " null"); 5082 } 5083 } 5084 if (ai == null) { 5085 // This previously registered persistent preferred activity 5086 // component is no longer known. Ignore it and do NOT remove it. 5087 continue; 5088 } 5089 for (int j=0; j<N; j++) { 5090 final ResolveInfo ri = query.get(j); 5091 if (!ri.activityInfo.applicationInfo.packageName 5092 .equals(ai.applicationInfo.packageName)) { 5093 continue; 5094 } 5095 if (!ri.activityInfo.name.equals(ai.name)) { 5096 continue; 5097 } 5098 // Found a persistent preference that can handle the intent. 5099 if (DEBUG_PREFERRED || debug) { 5100 Slog.v(TAG, "Returning persistent preferred activity: " + 5101 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5102 } 5103 return ri; 5104 } 5105 } 5106 } 5107 return null; 5108 } 5109 5110 // TODO: handle preferred activities missing while user has amnesia 5111 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5112 List<ResolveInfo> query, int priority, boolean always, 5113 boolean removeMatches, boolean debug, int userId) { 5114 if (!sUserManager.exists(userId)) return null; 5115 flags = updateFlagsForResolve(flags, userId, intent); 5116 // writer 5117 synchronized (mPackages) { 5118 if (intent.getSelector() != null) { 5119 intent = intent.getSelector(); 5120 } 5121 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5122 5123 // Try to find a matching persistent preferred activity. 5124 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5125 debug, userId); 5126 5127 // If a persistent preferred activity matched, use it. 5128 if (pri != null) { 5129 return pri; 5130 } 5131 5132 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5133 // Get the list of preferred activities that handle the intent 5134 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5135 List<PreferredActivity> prefs = pir != null 5136 ? pir.queryIntent(intent, resolvedType, 5137 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5138 : null; 5139 if (prefs != null && prefs.size() > 0) { 5140 boolean changed = false; 5141 try { 5142 // First figure out how good the original match set is. 5143 // We will only allow preferred activities that came 5144 // from the same match quality. 5145 int match = 0; 5146 5147 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5148 5149 final int N = query.size(); 5150 for (int j=0; j<N; j++) { 5151 final ResolveInfo ri = query.get(j); 5152 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5153 + ": 0x" + Integer.toHexString(match)); 5154 if (ri.match > match) { 5155 match = ri.match; 5156 } 5157 } 5158 5159 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5160 + Integer.toHexString(match)); 5161 5162 match &= IntentFilter.MATCH_CATEGORY_MASK; 5163 final int M = prefs.size(); 5164 for (int i=0; i<M; i++) { 5165 final PreferredActivity pa = prefs.get(i); 5166 if (DEBUG_PREFERRED || debug) { 5167 Slog.v(TAG, "Checking PreferredActivity ds=" 5168 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5169 + "\n component=" + pa.mPref.mComponent); 5170 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5171 } 5172 if (pa.mPref.mMatch != match) { 5173 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5174 + Integer.toHexString(pa.mPref.mMatch)); 5175 continue; 5176 } 5177 // If it's not an "always" type preferred activity and that's what we're 5178 // looking for, skip it. 5179 if (always && !pa.mPref.mAlways) { 5180 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5181 continue; 5182 } 5183 final ActivityInfo ai = getActivityInfo( 5184 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5185 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5186 userId); 5187 if (DEBUG_PREFERRED || debug) { 5188 Slog.v(TAG, "Found preferred activity:"); 5189 if (ai != null) { 5190 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5191 } else { 5192 Slog.v(TAG, " null"); 5193 } 5194 } 5195 if (ai == null) { 5196 // This previously registered preferred activity 5197 // component is no longer known. Most likely an update 5198 // to the app was installed and in the new version this 5199 // component no longer exists. Clean it up by removing 5200 // it from the preferred activities list, and skip it. 5201 Slog.w(TAG, "Removing dangling preferred activity: " 5202 + pa.mPref.mComponent); 5203 pir.removeFilter(pa); 5204 changed = true; 5205 continue; 5206 } 5207 for (int j=0; j<N; j++) { 5208 final ResolveInfo ri = query.get(j); 5209 if (!ri.activityInfo.applicationInfo.packageName 5210 .equals(ai.applicationInfo.packageName)) { 5211 continue; 5212 } 5213 if (!ri.activityInfo.name.equals(ai.name)) { 5214 continue; 5215 } 5216 5217 if (removeMatches) { 5218 pir.removeFilter(pa); 5219 changed = true; 5220 if (DEBUG_PREFERRED) { 5221 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5222 } 5223 break; 5224 } 5225 5226 // Okay we found a previously set preferred or last chosen app. 5227 // If the result set is different from when this 5228 // was created, we need to clear it and re-ask the 5229 // user their preference, if we're looking for an "always" type entry. 5230 if (always && !pa.mPref.sameSet(query)) { 5231 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5232 + intent + " type " + resolvedType); 5233 if (DEBUG_PREFERRED) { 5234 Slog.v(TAG, "Removing preferred activity since set changed " 5235 + pa.mPref.mComponent); 5236 } 5237 pir.removeFilter(pa); 5238 // Re-add the filter as a "last chosen" entry (!always) 5239 PreferredActivity lastChosen = new PreferredActivity( 5240 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5241 pir.addFilter(lastChosen); 5242 changed = true; 5243 return null; 5244 } 5245 5246 // Yay! Either the set matched or we're looking for the last chosen 5247 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5248 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5249 return ri; 5250 } 5251 } 5252 } finally { 5253 if (changed) { 5254 if (DEBUG_PREFERRED) { 5255 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5256 } 5257 scheduleWritePackageRestrictionsLocked(userId); 5258 } 5259 } 5260 } 5261 } 5262 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5263 return null; 5264 } 5265 5266 /* 5267 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5268 */ 5269 @Override 5270 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5271 int targetUserId) { 5272 mContext.enforceCallingOrSelfPermission( 5273 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5274 List<CrossProfileIntentFilter> matches = 5275 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5276 if (matches != null) { 5277 int size = matches.size(); 5278 for (int i = 0; i < size; i++) { 5279 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5280 } 5281 } 5282 if (hasWebURI(intent)) { 5283 // cross-profile app linking works only towards the parent. 5284 final UserInfo parent = getProfileParent(sourceUserId); 5285 synchronized(mPackages) { 5286 int flags = updateFlagsForResolve(0, parent.id, intent); 5287 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5288 intent, resolvedType, flags, sourceUserId, parent.id); 5289 return xpDomainInfo != null; 5290 } 5291 } 5292 return false; 5293 } 5294 5295 private UserInfo getProfileParent(int userId) { 5296 final long identity = Binder.clearCallingIdentity(); 5297 try { 5298 return sUserManager.getProfileParent(userId); 5299 } finally { 5300 Binder.restoreCallingIdentity(identity); 5301 } 5302 } 5303 5304 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5305 String resolvedType, int userId) { 5306 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5307 if (resolver != null) { 5308 return resolver.queryIntent(intent, resolvedType, false, userId); 5309 } 5310 return null; 5311 } 5312 5313 @Override 5314 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5315 String resolvedType, int flags, int userId) { 5316 try { 5317 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5318 5319 return new ParceledListSlice<>( 5320 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5321 } finally { 5322 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5323 } 5324 } 5325 5326 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5327 String resolvedType, int flags, int userId) { 5328 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5329 flags = updateFlagsForResolve(flags, userId, intent); 5330 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5331 false /* requireFullPermission */, false /* checkShell */, 5332 "query intent activities"); 5333 ComponentName comp = intent.getComponent(); 5334 if (comp == null) { 5335 if (intent.getSelector() != null) { 5336 intent = intent.getSelector(); 5337 comp = intent.getComponent(); 5338 } 5339 } 5340 5341 if (comp != null) { 5342 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5343 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5344 if (ai != null) { 5345 final ResolveInfo ri = new ResolveInfo(); 5346 ri.activityInfo = ai; 5347 list.add(ri); 5348 } 5349 return list; 5350 } 5351 5352 // reader 5353 boolean sortResult = false; 5354 boolean addEphemeral = false; 5355 boolean matchEphemeralPackage = false; 5356 List<ResolveInfo> result; 5357 final String pkgName = intent.getPackage(); 5358 synchronized (mPackages) { 5359 if (pkgName == null) { 5360 List<CrossProfileIntentFilter> matchingFilters = 5361 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5362 // Check for results that need to skip the current profile. 5363 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5364 resolvedType, flags, userId); 5365 if (xpResolveInfo != null) { 5366 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5367 xpResult.add(xpResolveInfo); 5368 return filterIfNotSystemUser(xpResult, userId); 5369 } 5370 5371 // Check for results in the current profile. 5372 result = filterIfNotSystemUser(mActivities.queryIntent( 5373 intent, resolvedType, flags, userId), userId); 5374 addEphemeral = 5375 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5376 5377 // Check for cross profile results. 5378 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5379 xpResolveInfo = queryCrossProfileIntents( 5380 matchingFilters, intent, resolvedType, flags, userId, 5381 hasNonNegativePriorityResult); 5382 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5383 boolean isVisibleToUser = filterIfNotSystemUser( 5384 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5385 if (isVisibleToUser) { 5386 result.add(xpResolveInfo); 5387 sortResult = true; 5388 } 5389 } 5390 if (hasWebURI(intent)) { 5391 CrossProfileDomainInfo xpDomainInfo = null; 5392 final UserInfo parent = getProfileParent(userId); 5393 if (parent != null) { 5394 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5395 flags, userId, parent.id); 5396 } 5397 if (xpDomainInfo != null) { 5398 if (xpResolveInfo != null) { 5399 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5400 // in the result. 5401 result.remove(xpResolveInfo); 5402 } 5403 if (result.size() == 0 && !addEphemeral) { 5404 // No result in current profile, but found candidate in parent user. 5405 // And we are not going to add emphemeral app, so we can return the 5406 // result straight away. 5407 result.add(xpDomainInfo.resolveInfo); 5408 return result; 5409 } 5410 } else if (result.size() <= 1 && !addEphemeral) { 5411 // No result in parent user and <= 1 result in current profile, and we 5412 // are not going to add emphemeral app, so we can return the result without 5413 // further processing. 5414 return result; 5415 } 5416 // We have more than one candidate (combining results from current and parent 5417 // profile), so we need filtering and sorting. 5418 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5419 intent, flags, result, xpDomainInfo, userId); 5420 sortResult = true; 5421 } 5422 } else { 5423 final PackageParser.Package pkg = mPackages.get(pkgName); 5424 if (pkg != null) { 5425 result = filterIfNotSystemUser( 5426 mActivities.queryIntentForPackage( 5427 intent, resolvedType, flags, pkg.activities, userId), 5428 userId); 5429 } else { 5430 // the caller wants to resolve for a particular package; however, there 5431 // were no installed results, so, try to find an ephemeral result 5432 addEphemeral = isEphemeralAllowed( 5433 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5434 matchEphemeralPackage = true; 5435 result = new ArrayList<ResolveInfo>(); 5436 } 5437 } 5438 } 5439 if (addEphemeral) { 5440 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5441 final EphemeralRequest requestObject = new EphemeralRequest( 5442 null /*responseObj*/, intent /*origIntent*/, resolvedType, 5443 null /*launchIntent*/, null /*callingPackage*/, userId); 5444 final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne( 5445 mContext, mEphemeralResolverConnection, requestObject); 5446 if (intentInfo != null) { 5447 if (DEBUG_EPHEMERAL) { 5448 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5449 } 5450 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5451 ephemeralInstaller.ephemeralResponse = intentInfo; 5452 // make sure this resolver is the default 5453 ephemeralInstaller.isDefault = true; 5454 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5455 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5456 // add a non-generic filter 5457 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5458 ephemeralInstaller.filter.addDataPath( 5459 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5460 result.add(ephemeralInstaller); 5461 } 5462 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5463 } 5464 if (sortResult) { 5465 Collections.sort(result, mResolvePrioritySorter); 5466 } 5467 return result; 5468 } 5469 5470 private static class CrossProfileDomainInfo { 5471 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5472 ResolveInfo resolveInfo; 5473 /* Best domain verification status of the activities found in the other profile */ 5474 int bestDomainVerificationStatus; 5475 } 5476 5477 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5478 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5479 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5480 sourceUserId)) { 5481 return null; 5482 } 5483 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5484 resolvedType, flags, parentUserId); 5485 5486 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5487 return null; 5488 } 5489 CrossProfileDomainInfo result = null; 5490 int size = resultTargetUser.size(); 5491 for (int i = 0; i < size; i++) { 5492 ResolveInfo riTargetUser = resultTargetUser.get(i); 5493 // Intent filter verification is only for filters that specify a host. So don't return 5494 // those that handle all web uris. 5495 if (riTargetUser.handleAllWebDataURI) { 5496 continue; 5497 } 5498 String packageName = riTargetUser.activityInfo.packageName; 5499 PackageSetting ps = mSettings.mPackages.get(packageName); 5500 if (ps == null) { 5501 continue; 5502 } 5503 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5504 int status = (int)(verificationState >> 32); 5505 if (result == null) { 5506 result = new CrossProfileDomainInfo(); 5507 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5508 sourceUserId, parentUserId); 5509 result.bestDomainVerificationStatus = status; 5510 } else { 5511 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5512 result.bestDomainVerificationStatus); 5513 } 5514 } 5515 // Don't consider matches with status NEVER across profiles. 5516 if (result != null && result.bestDomainVerificationStatus 5517 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5518 return null; 5519 } 5520 return result; 5521 } 5522 5523 /** 5524 * Verification statuses are ordered from the worse to the best, except for 5525 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5526 */ 5527 private int bestDomainVerificationStatus(int status1, int status2) { 5528 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5529 return status2; 5530 } 5531 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5532 return status1; 5533 } 5534 return (int) MathUtils.max(status1, status2); 5535 } 5536 5537 private boolean isUserEnabled(int userId) { 5538 long callingId = Binder.clearCallingIdentity(); 5539 try { 5540 UserInfo userInfo = sUserManager.getUserInfo(userId); 5541 return userInfo != null && userInfo.isEnabled(); 5542 } finally { 5543 Binder.restoreCallingIdentity(callingId); 5544 } 5545 } 5546 5547 /** 5548 * Filter out activities with systemUserOnly flag set, when current user is not System. 5549 * 5550 * @return filtered list 5551 */ 5552 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5553 if (userId == UserHandle.USER_SYSTEM) { 5554 return resolveInfos; 5555 } 5556 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5557 ResolveInfo info = resolveInfos.get(i); 5558 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5559 resolveInfos.remove(i); 5560 } 5561 } 5562 return resolveInfos; 5563 } 5564 5565 /** 5566 * @param resolveInfos list of resolve infos in descending priority order 5567 * @return if the list contains a resolve info with non-negative priority 5568 */ 5569 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5570 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5571 } 5572 5573 private static boolean hasWebURI(Intent intent) { 5574 if (intent.getData() == null) { 5575 return false; 5576 } 5577 final String scheme = intent.getScheme(); 5578 if (TextUtils.isEmpty(scheme)) { 5579 return false; 5580 } 5581 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5582 } 5583 5584 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5585 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5586 int userId) { 5587 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5588 5589 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5590 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5591 candidates.size()); 5592 } 5593 5594 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5595 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5596 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5597 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5598 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5599 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5600 5601 synchronized (mPackages) { 5602 final int count = candidates.size(); 5603 // First, try to use linked apps. Partition the candidates into four lists: 5604 // one for the final results, one for the "do not use ever", one for "undefined status" 5605 // and finally one for "browser app type". 5606 for (int n=0; n<count; n++) { 5607 ResolveInfo info = candidates.get(n); 5608 String packageName = info.activityInfo.packageName; 5609 PackageSetting ps = mSettings.mPackages.get(packageName); 5610 if (ps != null) { 5611 // Add to the special match all list (Browser use case) 5612 if (info.handleAllWebDataURI) { 5613 matchAllList.add(info); 5614 continue; 5615 } 5616 // Try to get the status from User settings first 5617 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5618 int status = (int)(packedStatus >> 32); 5619 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5620 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5621 if (DEBUG_DOMAIN_VERIFICATION) { 5622 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5623 + " : linkgen=" + linkGeneration); 5624 } 5625 // Use link-enabled generation as preferredOrder, i.e. 5626 // prefer newly-enabled over earlier-enabled. 5627 info.preferredOrder = linkGeneration; 5628 alwaysList.add(info); 5629 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5630 if (DEBUG_DOMAIN_VERIFICATION) { 5631 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5632 } 5633 neverList.add(info); 5634 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5635 if (DEBUG_DOMAIN_VERIFICATION) { 5636 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5637 } 5638 alwaysAskList.add(info); 5639 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5640 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5641 if (DEBUG_DOMAIN_VERIFICATION) { 5642 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5643 } 5644 undefinedList.add(info); 5645 } 5646 } 5647 } 5648 5649 // We'll want to include browser possibilities in a few cases 5650 boolean includeBrowser = false; 5651 5652 // First try to add the "always" resolution(s) for the current user, if any 5653 if (alwaysList.size() > 0) { 5654 result.addAll(alwaysList); 5655 } else { 5656 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5657 result.addAll(undefinedList); 5658 // Maybe add one for the other profile. 5659 if (xpDomainInfo != null && ( 5660 xpDomainInfo.bestDomainVerificationStatus 5661 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5662 result.add(xpDomainInfo.resolveInfo); 5663 } 5664 includeBrowser = true; 5665 } 5666 5667 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5668 // If there were 'always' entries their preferred order has been set, so we also 5669 // back that off to make the alternatives equivalent 5670 if (alwaysAskList.size() > 0) { 5671 for (ResolveInfo i : result) { 5672 i.preferredOrder = 0; 5673 } 5674 result.addAll(alwaysAskList); 5675 includeBrowser = true; 5676 } 5677 5678 if (includeBrowser) { 5679 // Also add browsers (all of them or only the default one) 5680 if (DEBUG_DOMAIN_VERIFICATION) { 5681 Slog.v(TAG, " ...including browsers in candidate set"); 5682 } 5683 if ((matchFlags & MATCH_ALL) != 0) { 5684 result.addAll(matchAllList); 5685 } else { 5686 // Browser/generic handling case. If there's a default browser, go straight 5687 // to that (but only if there is no other higher-priority match). 5688 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5689 int maxMatchPrio = 0; 5690 ResolveInfo defaultBrowserMatch = null; 5691 final int numCandidates = matchAllList.size(); 5692 for (int n = 0; n < numCandidates; n++) { 5693 ResolveInfo info = matchAllList.get(n); 5694 // track the highest overall match priority... 5695 if (info.priority > maxMatchPrio) { 5696 maxMatchPrio = info.priority; 5697 } 5698 // ...and the highest-priority default browser match 5699 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5700 if (defaultBrowserMatch == null 5701 || (defaultBrowserMatch.priority < info.priority)) { 5702 if (debug) { 5703 Slog.v(TAG, "Considering default browser match " + info); 5704 } 5705 defaultBrowserMatch = info; 5706 } 5707 } 5708 } 5709 if (defaultBrowserMatch != null 5710 && defaultBrowserMatch.priority >= maxMatchPrio 5711 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5712 { 5713 if (debug) { 5714 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5715 } 5716 result.add(defaultBrowserMatch); 5717 } else { 5718 result.addAll(matchAllList); 5719 } 5720 } 5721 5722 // If there is nothing selected, add all candidates and remove the ones that the user 5723 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5724 if (result.size() == 0) { 5725 result.addAll(candidates); 5726 result.removeAll(neverList); 5727 } 5728 } 5729 } 5730 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5731 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5732 result.size()); 5733 for (ResolveInfo info : result) { 5734 Slog.v(TAG, " + " + info.activityInfo); 5735 } 5736 } 5737 return result; 5738 } 5739 5740 // Returns a packed value as a long: 5741 // 5742 // high 'int'-sized word: link status: undefined/ask/never/always. 5743 // low 'int'-sized word: relative priority among 'always' results. 5744 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5745 long result = ps.getDomainVerificationStatusForUser(userId); 5746 // if none available, get the master status 5747 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5748 if (ps.getIntentFilterVerificationInfo() != null) { 5749 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5750 } 5751 } 5752 return result; 5753 } 5754 5755 private ResolveInfo querySkipCurrentProfileIntents( 5756 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5757 int flags, int sourceUserId) { 5758 if (matchingFilters != null) { 5759 int size = matchingFilters.size(); 5760 for (int i = 0; i < size; i ++) { 5761 CrossProfileIntentFilter filter = matchingFilters.get(i); 5762 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5763 // Checking if there are activities in the target user that can handle the 5764 // intent. 5765 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5766 resolvedType, flags, sourceUserId); 5767 if (resolveInfo != null) { 5768 return resolveInfo; 5769 } 5770 } 5771 } 5772 } 5773 return null; 5774 } 5775 5776 // Return matching ResolveInfo in target user if any. 5777 private ResolveInfo queryCrossProfileIntents( 5778 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5779 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5780 if (matchingFilters != null) { 5781 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5782 // match the same intent. For performance reasons, it is better not to 5783 // run queryIntent twice for the same userId 5784 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5785 int size = matchingFilters.size(); 5786 for (int i = 0; i < size; i++) { 5787 CrossProfileIntentFilter filter = matchingFilters.get(i); 5788 int targetUserId = filter.getTargetUserId(); 5789 boolean skipCurrentProfile = 5790 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5791 boolean skipCurrentProfileIfNoMatchFound = 5792 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5793 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5794 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5795 // Checking if there are activities in the target user that can handle the 5796 // intent. 5797 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5798 resolvedType, flags, sourceUserId); 5799 if (resolveInfo != null) return resolveInfo; 5800 alreadyTriedUserIds.put(targetUserId, true); 5801 } 5802 } 5803 } 5804 return null; 5805 } 5806 5807 /** 5808 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5809 * will forward the intent to the filter's target user. 5810 * Otherwise, returns null. 5811 */ 5812 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5813 String resolvedType, int flags, int sourceUserId) { 5814 int targetUserId = filter.getTargetUserId(); 5815 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5816 resolvedType, flags, targetUserId); 5817 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5818 // If all the matches in the target profile are suspended, return null. 5819 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5820 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5821 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5822 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5823 targetUserId); 5824 } 5825 } 5826 } 5827 return null; 5828 } 5829 5830 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5831 int sourceUserId, int targetUserId) { 5832 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5833 long ident = Binder.clearCallingIdentity(); 5834 boolean targetIsProfile; 5835 try { 5836 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5837 } finally { 5838 Binder.restoreCallingIdentity(ident); 5839 } 5840 String className; 5841 if (targetIsProfile) { 5842 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5843 } else { 5844 className = FORWARD_INTENT_TO_PARENT; 5845 } 5846 ComponentName forwardingActivityComponentName = new ComponentName( 5847 mAndroidApplication.packageName, className); 5848 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5849 sourceUserId); 5850 if (!targetIsProfile) { 5851 forwardingActivityInfo.showUserIcon = targetUserId; 5852 forwardingResolveInfo.noResourceId = true; 5853 } 5854 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5855 forwardingResolveInfo.priority = 0; 5856 forwardingResolveInfo.preferredOrder = 0; 5857 forwardingResolveInfo.match = 0; 5858 forwardingResolveInfo.isDefault = true; 5859 forwardingResolveInfo.filter = filter; 5860 forwardingResolveInfo.targetUserId = targetUserId; 5861 return forwardingResolveInfo; 5862 } 5863 5864 @Override 5865 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5866 Intent[] specifics, String[] specificTypes, Intent intent, 5867 String resolvedType, int flags, int userId) { 5868 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5869 specificTypes, intent, resolvedType, flags, userId)); 5870 } 5871 5872 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5873 Intent[] specifics, String[] specificTypes, Intent intent, 5874 String resolvedType, int flags, int userId) { 5875 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5876 flags = updateFlagsForResolve(flags, userId, intent); 5877 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5878 false /* requireFullPermission */, false /* checkShell */, 5879 "query intent activity options"); 5880 final String resultsAction = intent.getAction(); 5881 5882 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5883 | PackageManager.GET_RESOLVED_FILTER, userId); 5884 5885 if (DEBUG_INTENT_MATCHING) { 5886 Log.v(TAG, "Query " + intent + ": " + results); 5887 } 5888 5889 int specificsPos = 0; 5890 int N; 5891 5892 // todo: note that the algorithm used here is O(N^2). This 5893 // isn't a problem in our current environment, but if we start running 5894 // into situations where we have more than 5 or 10 matches then this 5895 // should probably be changed to something smarter... 5896 5897 // First we go through and resolve each of the specific items 5898 // that were supplied, taking care of removing any corresponding 5899 // duplicate items in the generic resolve list. 5900 if (specifics != null) { 5901 for (int i=0; i<specifics.length; i++) { 5902 final Intent sintent = specifics[i]; 5903 if (sintent == null) { 5904 continue; 5905 } 5906 5907 if (DEBUG_INTENT_MATCHING) { 5908 Log.v(TAG, "Specific #" + i + ": " + sintent); 5909 } 5910 5911 String action = sintent.getAction(); 5912 if (resultsAction != null && resultsAction.equals(action)) { 5913 // If this action was explicitly requested, then don't 5914 // remove things that have it. 5915 action = null; 5916 } 5917 5918 ResolveInfo ri = null; 5919 ActivityInfo ai = null; 5920 5921 ComponentName comp = sintent.getComponent(); 5922 if (comp == null) { 5923 ri = resolveIntent( 5924 sintent, 5925 specificTypes != null ? specificTypes[i] : null, 5926 flags, userId); 5927 if (ri == null) { 5928 continue; 5929 } 5930 if (ri == mResolveInfo) { 5931 // ACK! Must do something better with this. 5932 } 5933 ai = ri.activityInfo; 5934 comp = new ComponentName(ai.applicationInfo.packageName, 5935 ai.name); 5936 } else { 5937 ai = getActivityInfo(comp, flags, userId); 5938 if (ai == null) { 5939 continue; 5940 } 5941 } 5942 5943 // Look for any generic query activities that are duplicates 5944 // of this specific one, and remove them from the results. 5945 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5946 N = results.size(); 5947 int j; 5948 for (j=specificsPos; j<N; j++) { 5949 ResolveInfo sri = results.get(j); 5950 if ((sri.activityInfo.name.equals(comp.getClassName()) 5951 && sri.activityInfo.applicationInfo.packageName.equals( 5952 comp.getPackageName())) 5953 || (action != null && sri.filter.matchAction(action))) { 5954 results.remove(j); 5955 if (DEBUG_INTENT_MATCHING) Log.v( 5956 TAG, "Removing duplicate item from " + j 5957 + " due to specific " + specificsPos); 5958 if (ri == null) { 5959 ri = sri; 5960 } 5961 j--; 5962 N--; 5963 } 5964 } 5965 5966 // Add this specific item to its proper place. 5967 if (ri == null) { 5968 ri = new ResolveInfo(); 5969 ri.activityInfo = ai; 5970 } 5971 results.add(specificsPos, ri); 5972 ri.specificIndex = i; 5973 specificsPos++; 5974 } 5975 } 5976 5977 // Now we go through the remaining generic results and remove any 5978 // duplicate actions that are found here. 5979 N = results.size(); 5980 for (int i=specificsPos; i<N-1; i++) { 5981 final ResolveInfo rii = results.get(i); 5982 if (rii.filter == null) { 5983 continue; 5984 } 5985 5986 // Iterate over all of the actions of this result's intent 5987 // filter... typically this should be just one. 5988 final Iterator<String> it = rii.filter.actionsIterator(); 5989 if (it == null) { 5990 continue; 5991 } 5992 while (it.hasNext()) { 5993 final String action = it.next(); 5994 if (resultsAction != null && resultsAction.equals(action)) { 5995 // If this action was explicitly requested, then don't 5996 // remove things that have it. 5997 continue; 5998 } 5999 for (int j=i+1; j<N; j++) { 6000 final ResolveInfo rij = results.get(j); 6001 if (rij.filter != null && rij.filter.hasAction(action)) { 6002 results.remove(j); 6003 if (DEBUG_INTENT_MATCHING) Log.v( 6004 TAG, "Removing duplicate item from " + j 6005 + " due to action " + action + " at " + i); 6006 j--; 6007 N--; 6008 } 6009 } 6010 } 6011 6012 // If the caller didn't request filter information, drop it now 6013 // so we don't have to marshall/unmarshall it. 6014 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6015 rii.filter = null; 6016 } 6017 } 6018 6019 // Filter out the caller activity if so requested. 6020 if (caller != null) { 6021 N = results.size(); 6022 for (int i=0; i<N; i++) { 6023 ActivityInfo ainfo = results.get(i).activityInfo; 6024 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6025 && caller.getClassName().equals(ainfo.name)) { 6026 results.remove(i); 6027 break; 6028 } 6029 } 6030 } 6031 6032 // If the caller didn't request filter information, 6033 // drop them now so we don't have to 6034 // marshall/unmarshall it. 6035 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6036 N = results.size(); 6037 for (int i=0; i<N; i++) { 6038 results.get(i).filter = null; 6039 } 6040 } 6041 6042 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6043 return results; 6044 } 6045 6046 @Override 6047 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6048 String resolvedType, int flags, int userId) { 6049 return new ParceledListSlice<>( 6050 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6051 } 6052 6053 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6054 String resolvedType, int flags, int userId) { 6055 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6056 flags = updateFlagsForResolve(flags, userId, intent); 6057 ComponentName comp = intent.getComponent(); 6058 if (comp == null) { 6059 if (intent.getSelector() != null) { 6060 intent = intent.getSelector(); 6061 comp = intent.getComponent(); 6062 } 6063 } 6064 if (comp != null) { 6065 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6066 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6067 if (ai != null) { 6068 ResolveInfo ri = new ResolveInfo(); 6069 ri.activityInfo = ai; 6070 list.add(ri); 6071 } 6072 return list; 6073 } 6074 6075 // reader 6076 synchronized (mPackages) { 6077 String pkgName = intent.getPackage(); 6078 if (pkgName == null) { 6079 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6080 } 6081 final PackageParser.Package pkg = mPackages.get(pkgName); 6082 if (pkg != null) { 6083 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6084 userId); 6085 } 6086 return Collections.emptyList(); 6087 } 6088 } 6089 6090 @Override 6091 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6092 if (!sUserManager.exists(userId)) return null; 6093 flags = updateFlagsForResolve(flags, userId, intent); 6094 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6095 if (query != null) { 6096 if (query.size() >= 1) { 6097 // If there is more than one service with the same priority, 6098 // just arbitrarily pick the first one. 6099 return query.get(0); 6100 } 6101 } 6102 return null; 6103 } 6104 6105 @Override 6106 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6107 String resolvedType, int flags, int userId) { 6108 return new ParceledListSlice<>( 6109 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6110 } 6111 6112 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6113 String resolvedType, int flags, int userId) { 6114 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6115 flags = updateFlagsForResolve(flags, userId, intent); 6116 ComponentName comp = intent.getComponent(); 6117 if (comp == null) { 6118 if (intent.getSelector() != null) { 6119 intent = intent.getSelector(); 6120 comp = intent.getComponent(); 6121 } 6122 } 6123 if (comp != null) { 6124 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6125 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6126 if (si != null) { 6127 final ResolveInfo ri = new ResolveInfo(); 6128 ri.serviceInfo = si; 6129 list.add(ri); 6130 } 6131 return list; 6132 } 6133 6134 // reader 6135 synchronized (mPackages) { 6136 String pkgName = intent.getPackage(); 6137 if (pkgName == null) { 6138 return mServices.queryIntent(intent, resolvedType, flags, userId); 6139 } 6140 final PackageParser.Package pkg = mPackages.get(pkgName); 6141 if (pkg != null) { 6142 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6143 userId); 6144 } 6145 return Collections.emptyList(); 6146 } 6147 } 6148 6149 @Override 6150 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6151 String resolvedType, int flags, int userId) { 6152 return new ParceledListSlice<>( 6153 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6154 } 6155 6156 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6157 Intent intent, String resolvedType, int flags, int userId) { 6158 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6159 flags = updateFlagsForResolve(flags, userId, intent); 6160 ComponentName comp = intent.getComponent(); 6161 if (comp == null) { 6162 if (intent.getSelector() != null) { 6163 intent = intent.getSelector(); 6164 comp = intent.getComponent(); 6165 } 6166 } 6167 if (comp != null) { 6168 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6169 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6170 if (pi != null) { 6171 final ResolveInfo ri = new ResolveInfo(); 6172 ri.providerInfo = pi; 6173 list.add(ri); 6174 } 6175 return list; 6176 } 6177 6178 // reader 6179 synchronized (mPackages) { 6180 String pkgName = intent.getPackage(); 6181 if (pkgName == null) { 6182 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6183 } 6184 final PackageParser.Package pkg = mPackages.get(pkgName); 6185 if (pkg != null) { 6186 return mProviders.queryIntentForPackage( 6187 intent, resolvedType, flags, pkg.providers, userId); 6188 } 6189 return Collections.emptyList(); 6190 } 6191 } 6192 6193 @Override 6194 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6195 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6196 flags = updateFlagsForPackage(flags, userId, null); 6197 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6198 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6199 true /* requireFullPermission */, false /* checkShell */, 6200 "get installed packages"); 6201 6202 // writer 6203 synchronized (mPackages) { 6204 ArrayList<PackageInfo> list; 6205 if (listUninstalled) { 6206 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6207 for (PackageSetting ps : mSettings.mPackages.values()) { 6208 final PackageInfo pi; 6209 if (ps.pkg != null) { 6210 pi = generatePackageInfo(ps, flags, userId); 6211 } else { 6212 pi = generatePackageInfo(ps, flags, userId); 6213 } 6214 if (pi != null) { 6215 list.add(pi); 6216 } 6217 } 6218 } else { 6219 list = new ArrayList<PackageInfo>(mPackages.size()); 6220 for (PackageParser.Package p : mPackages.values()) { 6221 final PackageInfo pi = 6222 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6223 if (pi != null) { 6224 list.add(pi); 6225 } 6226 } 6227 } 6228 6229 return new ParceledListSlice<PackageInfo>(list); 6230 } 6231 } 6232 6233 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6234 String[] permissions, boolean[] tmp, int flags, int userId) { 6235 int numMatch = 0; 6236 final PermissionsState permissionsState = ps.getPermissionsState(); 6237 for (int i=0; i<permissions.length; i++) { 6238 final String permission = permissions[i]; 6239 if (permissionsState.hasPermission(permission, userId)) { 6240 tmp[i] = true; 6241 numMatch++; 6242 } else { 6243 tmp[i] = false; 6244 } 6245 } 6246 if (numMatch == 0) { 6247 return; 6248 } 6249 final PackageInfo pi; 6250 if (ps.pkg != null) { 6251 pi = generatePackageInfo(ps, flags, userId); 6252 } else { 6253 pi = generatePackageInfo(ps, flags, userId); 6254 } 6255 // The above might return null in cases of uninstalled apps or install-state 6256 // skew across users/profiles. 6257 if (pi != null) { 6258 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6259 if (numMatch == permissions.length) { 6260 pi.requestedPermissions = permissions; 6261 } else { 6262 pi.requestedPermissions = new String[numMatch]; 6263 numMatch = 0; 6264 for (int i=0; i<permissions.length; i++) { 6265 if (tmp[i]) { 6266 pi.requestedPermissions[numMatch] = permissions[i]; 6267 numMatch++; 6268 } 6269 } 6270 } 6271 } 6272 list.add(pi); 6273 } 6274 } 6275 6276 @Override 6277 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6278 String[] permissions, int flags, int userId) { 6279 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6280 flags = updateFlagsForPackage(flags, userId, permissions); 6281 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6282 6283 // writer 6284 synchronized (mPackages) { 6285 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6286 boolean[] tmpBools = new boolean[permissions.length]; 6287 if (listUninstalled) { 6288 for (PackageSetting ps : mSettings.mPackages.values()) { 6289 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6290 } 6291 } else { 6292 for (PackageParser.Package pkg : mPackages.values()) { 6293 PackageSetting ps = (PackageSetting)pkg.mExtras; 6294 if (ps != null) { 6295 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6296 userId); 6297 } 6298 } 6299 } 6300 6301 return new ParceledListSlice<PackageInfo>(list); 6302 } 6303 } 6304 6305 @Override 6306 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6307 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6308 flags = updateFlagsForApplication(flags, userId, null); 6309 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6310 6311 // writer 6312 synchronized (mPackages) { 6313 ArrayList<ApplicationInfo> list; 6314 if (listUninstalled) { 6315 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6316 for (PackageSetting ps : mSettings.mPackages.values()) { 6317 ApplicationInfo ai; 6318 if (ps.pkg != null) { 6319 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6320 ps.readUserState(userId), userId); 6321 } else { 6322 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6323 } 6324 if (ai != null) { 6325 list.add(ai); 6326 } 6327 } 6328 } else { 6329 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6330 for (PackageParser.Package p : mPackages.values()) { 6331 if (p.mExtras != null) { 6332 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6333 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6334 if (ai != null) { 6335 list.add(ai); 6336 } 6337 } 6338 } 6339 } 6340 6341 return new ParceledListSlice<ApplicationInfo>(list); 6342 } 6343 } 6344 6345 @Override 6346 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6347 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6348 return null; 6349 } 6350 6351 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6352 "getEphemeralApplications"); 6353 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6354 true /* requireFullPermission */, false /* checkShell */, 6355 "getEphemeralApplications"); 6356 synchronized (mPackages) { 6357 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6358 .getEphemeralApplicationsLPw(userId); 6359 if (ephemeralApps != null) { 6360 return new ParceledListSlice<>(ephemeralApps); 6361 } 6362 } 6363 return null; 6364 } 6365 6366 @Override 6367 public boolean isEphemeralApplication(String packageName, int userId) { 6368 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6369 true /* requireFullPermission */, false /* checkShell */, 6370 "isEphemeral"); 6371 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6372 return false; 6373 } 6374 6375 if (!isCallerSameApp(packageName)) { 6376 return false; 6377 } 6378 synchronized (mPackages) { 6379 PackageParser.Package pkg = mPackages.get(packageName); 6380 if (pkg != null) { 6381 return pkg.applicationInfo.isEphemeralApp(); 6382 } 6383 } 6384 return false; 6385 } 6386 6387 @Override 6388 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6389 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6390 return null; 6391 } 6392 6393 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6394 true /* requireFullPermission */, false /* checkShell */, 6395 "getCookie"); 6396 if (!isCallerSameApp(packageName)) { 6397 return null; 6398 } 6399 synchronized (mPackages) { 6400 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6401 packageName, userId); 6402 } 6403 } 6404 6405 @Override 6406 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6407 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6408 return true; 6409 } 6410 6411 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6412 true /* requireFullPermission */, true /* checkShell */, 6413 "setCookie"); 6414 if (!isCallerSameApp(packageName)) { 6415 return false; 6416 } 6417 synchronized (mPackages) { 6418 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6419 packageName, cookie, userId); 6420 } 6421 } 6422 6423 @Override 6424 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6425 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6426 return null; 6427 } 6428 6429 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6430 "getEphemeralApplicationIcon"); 6431 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6432 true /* requireFullPermission */, false /* checkShell */, 6433 "getEphemeralApplicationIcon"); 6434 synchronized (mPackages) { 6435 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6436 packageName, userId); 6437 } 6438 } 6439 6440 private boolean isCallerSameApp(String packageName) { 6441 PackageParser.Package pkg = mPackages.get(packageName); 6442 return pkg != null 6443 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6444 } 6445 6446 @Override 6447 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6448 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6449 } 6450 6451 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6452 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6453 6454 // reader 6455 synchronized (mPackages) { 6456 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6457 final int userId = UserHandle.getCallingUserId(); 6458 while (i.hasNext()) { 6459 final PackageParser.Package p = i.next(); 6460 if (p.applicationInfo == null) continue; 6461 6462 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6463 && !p.applicationInfo.isDirectBootAware(); 6464 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6465 && p.applicationInfo.isDirectBootAware(); 6466 6467 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6468 && (!mSafeMode || isSystemApp(p)) 6469 && (matchesUnaware || matchesAware)) { 6470 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6471 if (ps != null) { 6472 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6473 ps.readUserState(userId), userId); 6474 if (ai != null) { 6475 finalList.add(ai); 6476 } 6477 } 6478 } 6479 } 6480 } 6481 6482 return finalList; 6483 } 6484 6485 @Override 6486 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6487 if (!sUserManager.exists(userId)) return null; 6488 flags = updateFlagsForComponent(flags, userId, name); 6489 // reader 6490 synchronized (mPackages) { 6491 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6492 PackageSetting ps = provider != null 6493 ? mSettings.mPackages.get(provider.owner.packageName) 6494 : null; 6495 return ps != null 6496 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6497 ? PackageParser.generateProviderInfo(provider, flags, 6498 ps.readUserState(userId), userId) 6499 : null; 6500 } 6501 } 6502 6503 /** 6504 * @deprecated 6505 */ 6506 @Deprecated 6507 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6508 // reader 6509 synchronized (mPackages) { 6510 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6511 .entrySet().iterator(); 6512 final int userId = UserHandle.getCallingUserId(); 6513 while (i.hasNext()) { 6514 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6515 PackageParser.Provider p = entry.getValue(); 6516 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6517 6518 if (ps != null && p.syncable 6519 && (!mSafeMode || (p.info.applicationInfo.flags 6520 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6521 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6522 ps.readUserState(userId), userId); 6523 if (info != null) { 6524 outNames.add(entry.getKey()); 6525 outInfo.add(info); 6526 } 6527 } 6528 } 6529 } 6530 } 6531 6532 @Override 6533 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6534 int uid, int flags) { 6535 final int userId = processName != null ? UserHandle.getUserId(uid) 6536 : UserHandle.getCallingUserId(); 6537 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6538 flags = updateFlagsForComponent(flags, userId, processName); 6539 6540 ArrayList<ProviderInfo> finalList = null; 6541 // reader 6542 synchronized (mPackages) { 6543 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6544 while (i.hasNext()) { 6545 final PackageParser.Provider p = i.next(); 6546 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6547 if (ps != null && p.info.authority != null 6548 && (processName == null 6549 || (p.info.processName.equals(processName) 6550 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6551 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6552 if (finalList == null) { 6553 finalList = new ArrayList<ProviderInfo>(3); 6554 } 6555 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6556 ps.readUserState(userId), userId); 6557 if (info != null) { 6558 finalList.add(info); 6559 } 6560 } 6561 } 6562 } 6563 6564 if (finalList != null) { 6565 Collections.sort(finalList, mProviderInitOrderSorter); 6566 return new ParceledListSlice<ProviderInfo>(finalList); 6567 } 6568 6569 return ParceledListSlice.emptyList(); 6570 } 6571 6572 @Override 6573 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6574 // reader 6575 synchronized (mPackages) { 6576 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6577 return PackageParser.generateInstrumentationInfo(i, flags); 6578 } 6579 } 6580 6581 @Override 6582 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6583 String targetPackage, int flags) { 6584 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6585 } 6586 6587 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6588 int flags) { 6589 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6590 6591 // reader 6592 synchronized (mPackages) { 6593 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6594 while (i.hasNext()) { 6595 final PackageParser.Instrumentation p = i.next(); 6596 if (targetPackage == null 6597 || targetPackage.equals(p.info.targetPackage)) { 6598 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6599 flags); 6600 if (ii != null) { 6601 finalList.add(ii); 6602 } 6603 } 6604 } 6605 } 6606 6607 return finalList; 6608 } 6609 6610 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6611 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6612 if (overlays == null) { 6613 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6614 return; 6615 } 6616 for (PackageParser.Package opkg : overlays.values()) { 6617 // Not much to do if idmap fails: we already logged the error 6618 // and we certainly don't want to abort installation of pkg simply 6619 // because an overlay didn't fit properly. For these reasons, 6620 // ignore the return value of createIdmapForPackagePairLI. 6621 createIdmapForPackagePairLI(pkg, opkg); 6622 } 6623 } 6624 6625 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6626 PackageParser.Package opkg) { 6627 if (!opkg.mTrustedOverlay) { 6628 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6629 opkg.baseCodePath + ": overlay not trusted"); 6630 return false; 6631 } 6632 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6633 if (overlaySet == null) { 6634 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6635 opkg.baseCodePath + " but target package has no known overlays"); 6636 return false; 6637 } 6638 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6639 // TODO: generate idmap for split APKs 6640 try { 6641 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6642 } catch (InstallerException e) { 6643 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6644 + opkg.baseCodePath); 6645 return false; 6646 } 6647 PackageParser.Package[] overlayArray = 6648 overlaySet.values().toArray(new PackageParser.Package[0]); 6649 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6650 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6651 return p1.mOverlayPriority - p2.mOverlayPriority; 6652 } 6653 }; 6654 Arrays.sort(overlayArray, cmp); 6655 6656 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6657 int i = 0; 6658 for (PackageParser.Package p : overlayArray) { 6659 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6660 } 6661 return true; 6662 } 6663 6664 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6665 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 6666 try { 6667 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6668 } finally { 6669 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6670 } 6671 } 6672 6673 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6674 final File[] files = dir.listFiles(); 6675 if (ArrayUtils.isEmpty(files)) { 6676 Log.d(TAG, "No files in app dir " + dir); 6677 return; 6678 } 6679 6680 if (DEBUG_PACKAGE_SCANNING) { 6681 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6682 + " flags=0x" + Integer.toHexString(parseFlags)); 6683 } 6684 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 6685 mSeparateProcesses, mOnlyCore, mMetrics); 6686 6687 // Submit files for parsing in parallel 6688 int fileCount = 0; 6689 for (File file : files) { 6690 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6691 && !PackageInstallerService.isStageName(file.getName()); 6692 if (!isPackage) { 6693 // Ignore entries which are not packages 6694 continue; 6695 } 6696 parallelPackageParser.submit(file, parseFlags); 6697 fileCount++; 6698 } 6699 6700 // Process results one by one 6701 for (; fileCount > 0; fileCount--) { 6702 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 6703 Throwable throwable = parseResult.throwable; 6704 int errorCode = PackageManager.INSTALL_SUCCEEDED; 6705 6706 if (throwable == null) { 6707 try { 6708 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 6709 currentTime, null); 6710 } catch (PackageManagerException e) { 6711 errorCode = e.error; 6712 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 6713 } 6714 } else if (throwable instanceof PackageParser.PackageParserException) { 6715 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 6716 throwable; 6717 errorCode = e.error; 6718 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 6719 } else { 6720 throw new IllegalStateException("Unexpected exception occurred while parsing " 6721 + parseResult.scanFile, throwable); 6722 } 6723 6724 // Delete invalid userdata apps 6725 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6726 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 6727 logCriticalInfo(Log.WARN, 6728 "Deleting invalid package at " + parseResult.scanFile); 6729 removeCodePathLI(parseResult.scanFile); 6730 } 6731 } 6732 parallelPackageParser.close(); 6733 } 6734 6735 private static File getSettingsProblemFile() { 6736 File dataDir = Environment.getDataDirectory(); 6737 File systemDir = new File(dataDir, "system"); 6738 File fname = new File(systemDir, "uiderrors.txt"); 6739 return fname; 6740 } 6741 6742 static void reportSettingsProblem(int priority, String msg) { 6743 logCriticalInfo(priority, msg); 6744 } 6745 6746 static void logCriticalInfo(int priority, String msg) { 6747 Slog.println(priority, TAG, msg); 6748 EventLogTags.writePmCriticalInfo(msg); 6749 try { 6750 File fname = getSettingsProblemFile(); 6751 FileOutputStream out = new FileOutputStream(fname, true); 6752 PrintWriter pw = new FastPrintWriter(out); 6753 SimpleDateFormat formatter = new SimpleDateFormat(); 6754 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6755 pw.println(dateString + ": " + msg); 6756 pw.close(); 6757 FileUtils.setPermissions( 6758 fname.toString(), 6759 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6760 -1, -1); 6761 } catch (java.io.IOException e) { 6762 } 6763 } 6764 6765 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6766 if (srcFile.isDirectory()) { 6767 final File baseFile = new File(pkg.baseCodePath); 6768 long maxModifiedTime = baseFile.lastModified(); 6769 if (pkg.splitCodePaths != null) { 6770 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6771 final File splitFile = new File(pkg.splitCodePaths[i]); 6772 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6773 } 6774 } 6775 return maxModifiedTime; 6776 } 6777 return srcFile.lastModified(); 6778 } 6779 6780 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6781 final int policyFlags) throws PackageManagerException { 6782 // When upgrading from pre-N MR1, verify the package time stamp using the package 6783 // directory and not the APK file. 6784 final long lastModifiedTime = mIsPreNMR1Upgrade 6785 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 6786 if (ps != null 6787 && ps.codePath.equals(srcFile) 6788 && ps.timeStamp == lastModifiedTime 6789 && !isCompatSignatureUpdateNeeded(pkg) 6790 && !isRecoverSignatureUpdateNeeded(pkg)) { 6791 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6792 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6793 ArraySet<PublicKey> signingKs; 6794 synchronized (mPackages) { 6795 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6796 } 6797 if (ps.signatures.mSignatures != null 6798 && ps.signatures.mSignatures.length != 0 6799 && signingKs != null) { 6800 // Optimization: reuse the existing cached certificates 6801 // if the package appears to be unchanged. 6802 pkg.mSignatures = ps.signatures.mSignatures; 6803 pkg.mSigningKeys = signingKs; 6804 return; 6805 } 6806 6807 Slog.w(TAG, "PackageSetting for " + ps.name 6808 + " is missing signatures. Collecting certs again to recover them."); 6809 } else { 6810 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 6811 } 6812 6813 try { 6814 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 6815 PackageParser.collectCertificates(pkg, policyFlags); 6816 } catch (PackageParserException e) { 6817 throw PackageManagerException.from(e); 6818 } finally { 6819 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6820 } 6821 } 6822 6823 /** 6824 * Traces a package scan. 6825 * @see #scanPackageLI(File, int, int, long, UserHandle) 6826 */ 6827 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6828 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6829 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 6830 try { 6831 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6832 } finally { 6833 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6834 } 6835 } 6836 6837 /** 6838 * Scans a package and returns the newly parsed package. 6839 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6840 */ 6841 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6842 long currentTime, UserHandle user) throws PackageManagerException { 6843 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6844 PackageParser pp = new PackageParser(); 6845 pp.setSeparateProcesses(mSeparateProcesses); 6846 pp.setOnlyCoreApps(mOnlyCore); 6847 pp.setDisplayMetrics(mMetrics); 6848 6849 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6850 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6851 } 6852 6853 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6854 final PackageParser.Package pkg; 6855 try { 6856 pkg = pp.parsePackage(scanFile, parseFlags); 6857 } catch (PackageParserException e) { 6858 throw PackageManagerException.from(e); 6859 } finally { 6860 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6861 } 6862 6863 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6864 } 6865 6866 /** 6867 * Scans a package and returns the newly parsed package. 6868 * @throws PackageManagerException on a parse error. 6869 */ 6870 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6871 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6872 throws PackageManagerException { 6873 // If the package has children and this is the first dive in the function 6874 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6875 // packages (parent and children) would be successfully scanned before the 6876 // actual scan since scanning mutates internal state and we want to atomically 6877 // install the package and its children. 6878 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6879 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6880 scanFlags |= SCAN_CHECK_ONLY; 6881 } 6882 } else { 6883 scanFlags &= ~SCAN_CHECK_ONLY; 6884 } 6885 6886 // Scan the parent 6887 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6888 scanFlags, currentTime, user); 6889 6890 // Scan the children 6891 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6892 for (int i = 0; i < childCount; i++) { 6893 PackageParser.Package childPackage = pkg.childPackages.get(i); 6894 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6895 currentTime, user); 6896 } 6897 6898 6899 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6900 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6901 } 6902 6903 return scannedPkg; 6904 } 6905 6906 /** 6907 * Scans a package and returns the newly parsed package. 6908 * @throws PackageManagerException on a parse error. 6909 */ 6910 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6911 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6912 throws PackageManagerException { 6913 PackageSetting ps = null; 6914 PackageSetting updatedPkg; 6915 // reader 6916 synchronized (mPackages) { 6917 // Look to see if we already know about this package. 6918 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 6919 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6920 // This package has been renamed to its original name. Let's 6921 // use that. 6922 ps = mSettings.getPackageLPr(oldName); 6923 } 6924 // If there was no original package, see one for the real package name. 6925 if (ps == null) { 6926 ps = mSettings.getPackageLPr(pkg.packageName); 6927 } 6928 // Check to see if this package could be hiding/updating a system 6929 // package. Must look for it either under the original or real 6930 // package name depending on our state. 6931 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6932 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6933 6934 // If this is a package we don't know about on the system partition, we 6935 // may need to remove disabled child packages on the system partition 6936 // or may need to not add child packages if the parent apk is updated 6937 // on the data partition and no longer defines this child package. 6938 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6939 // If this is a parent package for an updated system app and this system 6940 // app got an OTA update which no longer defines some of the child packages 6941 // we have to prune them from the disabled system packages. 6942 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6943 if (disabledPs != null) { 6944 final int scannedChildCount = (pkg.childPackages != null) 6945 ? pkg.childPackages.size() : 0; 6946 final int disabledChildCount = disabledPs.childPackageNames != null 6947 ? disabledPs.childPackageNames.size() : 0; 6948 for (int i = 0; i < disabledChildCount; i++) { 6949 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6950 boolean disabledPackageAvailable = false; 6951 for (int j = 0; j < scannedChildCount; j++) { 6952 PackageParser.Package childPkg = pkg.childPackages.get(j); 6953 if (childPkg.packageName.equals(disabledChildPackageName)) { 6954 disabledPackageAvailable = true; 6955 break; 6956 } 6957 } 6958 if (!disabledPackageAvailable) { 6959 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6960 } 6961 } 6962 } 6963 } 6964 } 6965 6966 boolean updatedPkgBetter = false; 6967 // First check if this is a system package that may involve an update 6968 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6969 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6970 // it needs to drop FLAG_PRIVILEGED. 6971 if (locationIsPrivileged(scanFile)) { 6972 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6973 } else { 6974 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6975 } 6976 6977 if (ps != null && !ps.codePath.equals(scanFile)) { 6978 // The path has changed from what was last scanned... check the 6979 // version of the new path against what we have stored to determine 6980 // what to do. 6981 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6982 if (pkg.mVersionCode <= ps.versionCode) { 6983 // The system package has been updated and the code path does not match 6984 // Ignore entry. Skip it. 6985 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6986 + " ignored: updated version " + ps.versionCode 6987 + " better than this " + pkg.mVersionCode); 6988 if (!updatedPkg.codePath.equals(scanFile)) { 6989 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6990 + ps.name + " changing from " + updatedPkg.codePathString 6991 + " to " + scanFile); 6992 updatedPkg.codePath = scanFile; 6993 updatedPkg.codePathString = scanFile.toString(); 6994 updatedPkg.resourcePath = scanFile; 6995 updatedPkg.resourcePathString = scanFile.toString(); 6996 } 6997 updatedPkg.pkg = pkg; 6998 updatedPkg.versionCode = pkg.mVersionCode; 6999 7000 // Update the disabled system child packages to point to the package too. 7001 final int childCount = updatedPkg.childPackageNames != null 7002 ? updatedPkg.childPackageNames.size() : 0; 7003 for (int i = 0; i < childCount; i++) { 7004 String childPackageName = updatedPkg.childPackageNames.get(i); 7005 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7006 childPackageName); 7007 if (updatedChildPkg != null) { 7008 updatedChildPkg.pkg = pkg; 7009 updatedChildPkg.versionCode = pkg.mVersionCode; 7010 } 7011 } 7012 7013 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7014 + scanFile + " ignored: updated version " + ps.versionCode 7015 + " better than this " + pkg.mVersionCode); 7016 } else { 7017 // The current app on the system partition is better than 7018 // what we have updated to on the data partition; switch 7019 // back to the system partition version. 7020 // At this point, its safely assumed that package installation for 7021 // apps in system partition will go through. If not there won't be a working 7022 // version of the app 7023 // writer 7024 synchronized (mPackages) { 7025 // Just remove the loaded entries from package lists. 7026 mPackages.remove(ps.name); 7027 } 7028 7029 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7030 + " reverting from " + ps.codePathString 7031 + ": new version " + pkg.mVersionCode 7032 + " better than installed " + ps.versionCode); 7033 7034 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7035 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7036 synchronized (mInstallLock) { 7037 args.cleanUpResourcesLI(); 7038 } 7039 synchronized (mPackages) { 7040 mSettings.enableSystemPackageLPw(ps.name); 7041 } 7042 updatedPkgBetter = true; 7043 } 7044 } 7045 } 7046 7047 if (updatedPkg != null) { 7048 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7049 // initially 7050 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7051 7052 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7053 // flag set initially 7054 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7055 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7056 } 7057 } 7058 7059 // Verify certificates against what was last scanned 7060 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7061 7062 /* 7063 * A new system app appeared, but we already had a non-system one of the 7064 * same name installed earlier. 7065 */ 7066 boolean shouldHideSystemApp = false; 7067 if (updatedPkg == null && ps != null 7068 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7069 /* 7070 * Check to make sure the signatures match first. If they don't, 7071 * wipe the installed application and its data. 7072 */ 7073 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7074 != PackageManager.SIGNATURE_MATCH) { 7075 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7076 + " signatures don't match existing userdata copy; removing"); 7077 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7078 "scanPackageInternalLI")) { 7079 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7080 } 7081 ps = null; 7082 } else { 7083 /* 7084 * If the newly-added system app is an older version than the 7085 * already installed version, hide it. It will be scanned later 7086 * and re-added like an update. 7087 */ 7088 if (pkg.mVersionCode <= ps.versionCode) { 7089 shouldHideSystemApp = true; 7090 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7091 + " but new version " + pkg.mVersionCode + " better than installed " 7092 + ps.versionCode + "; hiding system"); 7093 } else { 7094 /* 7095 * The newly found system app is a newer version that the 7096 * one previously installed. Simply remove the 7097 * already-installed application and replace it with our own 7098 * while keeping the application data. 7099 */ 7100 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7101 + " reverting from " + ps.codePathString + ": new version " 7102 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7103 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7104 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7105 synchronized (mInstallLock) { 7106 args.cleanUpResourcesLI(); 7107 } 7108 } 7109 } 7110 } 7111 7112 // The apk is forward locked (not public) if its code and resources 7113 // are kept in different files. (except for app in either system or 7114 // vendor path). 7115 // TODO grab this value from PackageSettings 7116 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7117 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7118 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7119 } 7120 } 7121 7122 // TODO: extend to support forward-locked splits 7123 String resourcePath = null; 7124 String baseResourcePath = null; 7125 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7126 if (ps != null && ps.resourcePathString != null) { 7127 resourcePath = ps.resourcePathString; 7128 baseResourcePath = ps.resourcePathString; 7129 } else { 7130 // Should not happen at all. Just log an error. 7131 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7132 } 7133 } else { 7134 resourcePath = pkg.codePath; 7135 baseResourcePath = pkg.baseCodePath; 7136 } 7137 7138 // Set application objects path explicitly. 7139 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7140 pkg.setApplicationInfoCodePath(pkg.codePath); 7141 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7142 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7143 pkg.setApplicationInfoResourcePath(resourcePath); 7144 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7145 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7146 7147 // Note that we invoke the following method only if we are about to unpack an application 7148 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7149 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7150 7151 /* 7152 * If the system app should be overridden by a previously installed 7153 * data, hide the system app now and let the /data/app scan pick it up 7154 * again. 7155 */ 7156 if (shouldHideSystemApp) { 7157 synchronized (mPackages) { 7158 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7159 } 7160 } 7161 7162 return scannedPkg; 7163 } 7164 7165 private static String fixProcessName(String defProcessName, 7166 String processName) { 7167 if (processName == null) { 7168 return defProcessName; 7169 } 7170 return processName; 7171 } 7172 7173 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7174 throws PackageManagerException { 7175 if (pkgSetting.signatures.mSignatures != null) { 7176 // Already existing package. Make sure signatures match 7177 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7178 == PackageManager.SIGNATURE_MATCH; 7179 if (!match) { 7180 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7181 == PackageManager.SIGNATURE_MATCH; 7182 } 7183 if (!match) { 7184 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7185 == PackageManager.SIGNATURE_MATCH; 7186 } 7187 if (!match) { 7188 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7189 + pkg.packageName + " signatures do not match the " 7190 + "previously installed version; ignoring!"); 7191 } 7192 } 7193 7194 // Check for shared user signatures 7195 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7196 // Already existing package. Make sure signatures match 7197 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7198 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7199 if (!match) { 7200 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7201 == PackageManager.SIGNATURE_MATCH; 7202 } 7203 if (!match) { 7204 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7205 == PackageManager.SIGNATURE_MATCH; 7206 } 7207 if (!match) { 7208 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7209 "Package " + pkg.packageName 7210 + " has no signatures that match those in shared user " 7211 + pkgSetting.sharedUser.name + "; ignoring!"); 7212 } 7213 } 7214 } 7215 7216 /** 7217 * Enforces that only the system UID or root's UID can call a method exposed 7218 * via Binder. 7219 * 7220 * @param message used as message if SecurityException is thrown 7221 * @throws SecurityException if the caller is not system or root 7222 */ 7223 private static final void enforceSystemOrRoot(String message) { 7224 final int uid = Binder.getCallingUid(); 7225 if (uid != Process.SYSTEM_UID && uid != 0) { 7226 throw new SecurityException(message); 7227 } 7228 } 7229 7230 @Override 7231 public void performFstrimIfNeeded() { 7232 enforceSystemOrRoot("Only the system can request fstrim"); 7233 7234 // Before everything else, see whether we need to fstrim. 7235 try { 7236 IStorageManager sm = PackageHelper.getStorageManager(); 7237 if (sm != null) { 7238 boolean doTrim = false; 7239 final long interval = android.provider.Settings.Global.getLong( 7240 mContext.getContentResolver(), 7241 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7242 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7243 if (interval > 0) { 7244 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 7245 if (timeSinceLast > interval) { 7246 doTrim = true; 7247 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7248 + "; running immediately"); 7249 } 7250 } 7251 if (doTrim) { 7252 final boolean dexOptDialogShown; 7253 synchronized (mPackages) { 7254 dexOptDialogShown = mDexOptDialogShown; 7255 } 7256 if (!isFirstBoot() && dexOptDialogShown) { 7257 try { 7258 ActivityManager.getService().showBootMessage( 7259 mContext.getResources().getString( 7260 R.string.android_upgrading_fstrim), true); 7261 } catch (RemoteException e) { 7262 } 7263 } 7264 sm.runMaintenance(); 7265 } 7266 } else { 7267 Slog.e(TAG, "storageManager service unavailable!"); 7268 } 7269 } catch (RemoteException e) { 7270 // Can't happen; StorageManagerService is local 7271 } 7272 } 7273 7274 @Override 7275 public void updatePackagesIfNeeded() { 7276 enforceSystemOrRoot("Only the system can request package update"); 7277 7278 // We need to re-extract after an OTA. 7279 boolean causeUpgrade = isUpgrade(); 7280 7281 // First boot or factory reset. 7282 // Note: we also handle devices that are upgrading to N right now as if it is their 7283 // first boot, as they do not have profile data. 7284 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7285 7286 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7287 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7288 7289 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7290 return; 7291 } 7292 7293 List<PackageParser.Package> pkgs; 7294 synchronized (mPackages) { 7295 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7296 } 7297 7298 final long startTime = System.nanoTime(); 7299 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7300 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7301 7302 final int elapsedTimeSeconds = 7303 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7304 7305 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7306 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7307 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7308 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7309 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7310 } 7311 7312 /** 7313 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7314 * containing statistics about the invocation. The array consists of three elements, 7315 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7316 * and {@code numberOfPackagesFailed}. 7317 */ 7318 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7319 String compilerFilter) { 7320 7321 int numberOfPackagesVisited = 0; 7322 int numberOfPackagesOptimized = 0; 7323 int numberOfPackagesSkipped = 0; 7324 int numberOfPackagesFailed = 0; 7325 final int numberOfPackagesToDexopt = pkgs.size(); 7326 7327 for (PackageParser.Package pkg : pkgs) { 7328 numberOfPackagesVisited++; 7329 7330 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7331 if (DEBUG_DEXOPT) { 7332 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7333 } 7334 numberOfPackagesSkipped++; 7335 continue; 7336 } 7337 7338 if (DEBUG_DEXOPT) { 7339 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7340 numberOfPackagesToDexopt + ": " + pkg.packageName); 7341 } 7342 7343 if (showDialog) { 7344 try { 7345 ActivityManager.getService().showBootMessage( 7346 mContext.getResources().getString(R.string.android_upgrading_apk, 7347 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7348 } catch (RemoteException e) { 7349 } 7350 synchronized (mPackages) { 7351 mDexOptDialogShown = true; 7352 } 7353 } 7354 7355 // If the OTA updates a system app which was previously preopted to a non-preopted state 7356 // the app might end up being verified at runtime. That's because by default the apps 7357 // are verify-profile but for preopted apps there's no profile. 7358 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7359 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7360 // filter (by default interpret-only). 7361 // Note that at this stage unused apps are already filtered. 7362 if (isSystemApp(pkg) && 7363 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7364 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7365 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7366 } 7367 7368 // If the OTA updates a system app which was previously preopted to a non-preopted state 7369 // the app might end up being verified at runtime. That's because by default the apps 7370 // are verify-profile but for preopted apps there's no profile. 7371 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7372 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7373 // filter (by default interpret-only). 7374 // Note that at this stage unused apps are already filtered. 7375 if (isSystemApp(pkg) && 7376 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7377 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7378 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7379 } 7380 7381 // checkProfiles is false to avoid merging profiles during boot which 7382 // might interfere with background compilation (b/28612421). 7383 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7384 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7385 // trade-off worth doing to save boot time work. 7386 int dexOptStatus = performDexOptTraced(pkg.packageName, 7387 false /* checkProfiles */, 7388 compilerFilter, 7389 false /* force */); 7390 switch (dexOptStatus) { 7391 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7392 numberOfPackagesOptimized++; 7393 break; 7394 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7395 numberOfPackagesSkipped++; 7396 break; 7397 case PackageDexOptimizer.DEX_OPT_FAILED: 7398 numberOfPackagesFailed++; 7399 break; 7400 default: 7401 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7402 break; 7403 } 7404 } 7405 7406 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7407 numberOfPackagesFailed }; 7408 } 7409 7410 @Override 7411 public void notifyPackageUse(String packageName, int reason) { 7412 synchronized (mPackages) { 7413 PackageParser.Package p = mPackages.get(packageName); 7414 if (p == null) { 7415 return; 7416 } 7417 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7418 } 7419 } 7420 7421 // TODO: this is not used nor needed. Delete it. 7422 @Override 7423 public boolean performDexOptIfNeeded(String packageName) { 7424 int dexOptStatus = performDexOptTraced(packageName, 7425 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7426 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7427 } 7428 7429 @Override 7430 public boolean performDexOpt(String packageName, 7431 boolean checkProfiles, int compileReason, boolean force) { 7432 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7433 getCompilerFilterForReason(compileReason), force); 7434 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7435 } 7436 7437 @Override 7438 public boolean performDexOptMode(String packageName, 7439 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7440 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7441 targetCompilerFilter, force); 7442 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7443 } 7444 7445 private int performDexOptTraced(String packageName, 7446 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7447 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7448 try { 7449 return performDexOptInternal(packageName, checkProfiles, 7450 targetCompilerFilter, force); 7451 } finally { 7452 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7453 } 7454 } 7455 7456 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7457 // if the package can now be considered up to date for the given filter. 7458 private int performDexOptInternal(String packageName, 7459 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7460 PackageParser.Package p; 7461 synchronized (mPackages) { 7462 p = mPackages.get(packageName); 7463 if (p == null) { 7464 // Package could not be found. Report failure. 7465 return PackageDexOptimizer.DEX_OPT_FAILED; 7466 } 7467 mPackageUsage.maybeWriteAsync(mPackages); 7468 mCompilerStats.maybeWriteAsync(); 7469 } 7470 long callingId = Binder.clearCallingIdentity(); 7471 try { 7472 synchronized (mInstallLock) { 7473 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7474 targetCompilerFilter, force); 7475 } 7476 } finally { 7477 Binder.restoreCallingIdentity(callingId); 7478 } 7479 } 7480 7481 public ArraySet<String> getOptimizablePackages() { 7482 ArraySet<String> pkgs = new ArraySet<String>(); 7483 synchronized (mPackages) { 7484 for (PackageParser.Package p : mPackages.values()) { 7485 if (PackageDexOptimizer.canOptimizePackage(p)) { 7486 pkgs.add(p.packageName); 7487 } 7488 } 7489 } 7490 return pkgs; 7491 } 7492 7493 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7494 boolean checkProfiles, String targetCompilerFilter, 7495 boolean force) { 7496 // Select the dex optimizer based on the force parameter. 7497 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7498 // allocate an object here. 7499 PackageDexOptimizer pdo = force 7500 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7501 : mPackageDexOptimizer; 7502 7503 // Optimize all dependencies first. Note: we ignore the return value and march on 7504 // on errors. 7505 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7506 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7507 if (!deps.isEmpty()) { 7508 for (PackageParser.Package depPackage : deps) { 7509 // TODO: Analyze and investigate if we (should) profile libraries. 7510 // Currently this will do a full compilation of the library by default. 7511 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7512 false /* checkProfiles */, 7513 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7514 getOrCreateCompilerPackageStats(depPackage)); 7515 } 7516 } 7517 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7518 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7519 } 7520 7521 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7522 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7523 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7524 Set<String> collectedNames = new HashSet<>(); 7525 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7526 7527 retValue.remove(p); 7528 7529 return retValue; 7530 } else { 7531 return Collections.emptyList(); 7532 } 7533 } 7534 7535 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7536 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7537 if (!collectedNames.contains(p.packageName)) { 7538 collectedNames.add(p.packageName); 7539 collected.add(p); 7540 7541 if (p.usesLibraries != null) { 7542 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7543 } 7544 if (p.usesOptionalLibraries != null) { 7545 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7546 collectedNames); 7547 } 7548 } 7549 } 7550 7551 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7552 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7553 for (String libName : libs) { 7554 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7555 if (libPkg != null) { 7556 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7557 } 7558 } 7559 } 7560 7561 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7562 synchronized (mPackages) { 7563 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7564 if (lib != null && lib.apk != null) { 7565 return mPackages.get(lib.apk); 7566 } 7567 } 7568 return null; 7569 } 7570 7571 public void shutdown() { 7572 mPackageUsage.writeNow(mPackages); 7573 mCompilerStats.writeNow(); 7574 } 7575 7576 @Override 7577 public void dumpProfiles(String packageName) { 7578 PackageParser.Package pkg; 7579 synchronized (mPackages) { 7580 pkg = mPackages.get(packageName); 7581 if (pkg == null) { 7582 throw new IllegalArgumentException("Unknown package: " + packageName); 7583 } 7584 } 7585 /* Only the shell, root, or the app user should be able to dump profiles. */ 7586 int callingUid = Binder.getCallingUid(); 7587 if (callingUid != Process.SHELL_UID && 7588 callingUid != Process.ROOT_UID && 7589 callingUid != pkg.applicationInfo.uid) { 7590 throw new SecurityException("dumpProfiles"); 7591 } 7592 7593 synchronized (mInstallLock) { 7594 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7595 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7596 try { 7597 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7598 String gid = Integer.toString(sharedGid); 7599 String codePaths = TextUtils.join(";", allCodePaths); 7600 mInstaller.dumpProfiles(gid, packageName, codePaths); 7601 } catch (InstallerException e) { 7602 Slog.w(TAG, "Failed to dump profiles", e); 7603 } 7604 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7605 } 7606 } 7607 7608 @Override 7609 public void forceDexOpt(String packageName) { 7610 enforceSystemOrRoot("forceDexOpt"); 7611 7612 PackageParser.Package pkg; 7613 synchronized (mPackages) { 7614 pkg = mPackages.get(packageName); 7615 if (pkg == null) { 7616 throw new IllegalArgumentException("Unknown package: " + packageName); 7617 } 7618 } 7619 7620 synchronized (mInstallLock) { 7621 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7622 7623 // Whoever is calling forceDexOpt wants a fully compiled package. 7624 // Don't use profiles since that may cause compilation to be skipped. 7625 final int res = performDexOptInternalWithDependenciesLI(pkg, 7626 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7627 true /* force */); 7628 7629 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7630 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7631 throw new IllegalStateException("Failed to dexopt: " + res); 7632 } 7633 } 7634 } 7635 7636 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7637 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7638 Slog.w(TAG, "Unable to update from " + oldPkg.name 7639 + " to " + newPkg.packageName 7640 + ": old package not in system partition"); 7641 return false; 7642 } else if (mPackages.get(oldPkg.name) != null) { 7643 Slog.w(TAG, "Unable to update from " + oldPkg.name 7644 + " to " + newPkg.packageName 7645 + ": old package still exists"); 7646 return false; 7647 } 7648 return true; 7649 } 7650 7651 void removeCodePathLI(File codePath) { 7652 if (codePath.isDirectory()) { 7653 try { 7654 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7655 } catch (InstallerException e) { 7656 Slog.w(TAG, "Failed to remove code path", e); 7657 } 7658 } else { 7659 codePath.delete(); 7660 } 7661 } 7662 7663 private int[] resolveUserIds(int userId) { 7664 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7665 } 7666 7667 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7668 if (pkg == null) { 7669 Slog.wtf(TAG, "Package was null!", new Throwable()); 7670 return; 7671 } 7672 clearAppDataLeafLIF(pkg, userId, flags); 7673 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7674 for (int i = 0; i < childCount; i++) { 7675 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7676 } 7677 } 7678 7679 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7680 final PackageSetting ps; 7681 synchronized (mPackages) { 7682 ps = mSettings.mPackages.get(pkg.packageName); 7683 } 7684 for (int realUserId : resolveUserIds(userId)) { 7685 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7686 try { 7687 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7688 ceDataInode); 7689 } catch (InstallerException e) { 7690 Slog.w(TAG, String.valueOf(e)); 7691 } 7692 } 7693 } 7694 7695 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7696 if (pkg == null) { 7697 Slog.wtf(TAG, "Package was null!", new Throwable()); 7698 return; 7699 } 7700 destroyAppDataLeafLIF(pkg, userId, flags); 7701 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7702 for (int i = 0; i < childCount; i++) { 7703 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7704 } 7705 } 7706 7707 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7708 final PackageSetting ps; 7709 synchronized (mPackages) { 7710 ps = mSettings.mPackages.get(pkg.packageName); 7711 } 7712 for (int realUserId : resolveUserIds(userId)) { 7713 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7714 try { 7715 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7716 ceDataInode); 7717 } catch (InstallerException e) { 7718 Slog.w(TAG, String.valueOf(e)); 7719 } 7720 } 7721 } 7722 7723 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7724 if (pkg == null) { 7725 Slog.wtf(TAG, "Package was null!", new Throwable()); 7726 return; 7727 } 7728 destroyAppProfilesLeafLIF(pkg); 7729 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7730 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7731 for (int i = 0; i < childCount; i++) { 7732 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7733 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7734 true /* removeBaseMarker */); 7735 } 7736 } 7737 7738 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7739 boolean removeBaseMarker) { 7740 if (pkg.isForwardLocked()) { 7741 return; 7742 } 7743 7744 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7745 try { 7746 path = PackageManagerServiceUtils.realpath(new File(path)); 7747 } catch (IOException e) { 7748 // TODO: Should we return early here ? 7749 Slog.w(TAG, "Failed to get canonical path", e); 7750 continue; 7751 } 7752 7753 final String useMarker = path.replace('/', '@'); 7754 for (int realUserId : resolveUserIds(userId)) { 7755 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7756 if (removeBaseMarker) { 7757 File foreignUseMark = new File(profileDir, useMarker); 7758 if (foreignUseMark.exists()) { 7759 if (!foreignUseMark.delete()) { 7760 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7761 + pkg.packageName); 7762 } 7763 } 7764 } 7765 7766 File[] markers = profileDir.listFiles(); 7767 if (markers != null) { 7768 final String searchString = "@" + pkg.packageName + "@"; 7769 // We also delete all markers that contain the package name we're 7770 // uninstalling. These are associated with secondary dex-files belonging 7771 // to the package. Reconstructing the path of these dex files is messy 7772 // in general. 7773 for (File marker : markers) { 7774 if (marker.getName().indexOf(searchString) > 0) { 7775 if (!marker.delete()) { 7776 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7777 + pkg.packageName); 7778 } 7779 } 7780 } 7781 } 7782 } 7783 } 7784 } 7785 7786 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7787 try { 7788 mInstaller.destroyAppProfiles(pkg.packageName); 7789 } catch (InstallerException e) { 7790 Slog.w(TAG, String.valueOf(e)); 7791 } 7792 } 7793 7794 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7795 if (pkg == null) { 7796 Slog.wtf(TAG, "Package was null!", new Throwable()); 7797 return; 7798 } 7799 clearAppProfilesLeafLIF(pkg); 7800 // We don't remove the base foreign use marker when clearing profiles because 7801 // we will rename it when the app is updated. Unlike the actual profile contents, 7802 // the foreign use marker is good across installs. 7803 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7804 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7805 for (int i = 0; i < childCount; i++) { 7806 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7807 } 7808 } 7809 7810 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7811 try { 7812 mInstaller.clearAppProfiles(pkg.packageName); 7813 } catch (InstallerException e) { 7814 Slog.w(TAG, String.valueOf(e)); 7815 } 7816 } 7817 7818 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7819 long lastUpdateTime) { 7820 // Set parent install/update time 7821 PackageSetting ps = (PackageSetting) pkg.mExtras; 7822 if (ps != null) { 7823 ps.firstInstallTime = firstInstallTime; 7824 ps.lastUpdateTime = lastUpdateTime; 7825 } 7826 // Set children install/update time 7827 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7828 for (int i = 0; i < childCount; i++) { 7829 PackageParser.Package childPkg = pkg.childPackages.get(i); 7830 ps = (PackageSetting) childPkg.mExtras; 7831 if (ps != null) { 7832 ps.firstInstallTime = firstInstallTime; 7833 ps.lastUpdateTime = lastUpdateTime; 7834 } 7835 } 7836 } 7837 7838 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7839 PackageParser.Package changingLib) { 7840 if (file.path != null) { 7841 usesLibraryFiles.add(file.path); 7842 return; 7843 } 7844 PackageParser.Package p = mPackages.get(file.apk); 7845 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7846 // If we are doing this while in the middle of updating a library apk, 7847 // then we need to make sure to use that new apk for determining the 7848 // dependencies here. (We haven't yet finished committing the new apk 7849 // to the package manager state.) 7850 if (p == null || p.packageName.equals(changingLib.packageName)) { 7851 p = changingLib; 7852 } 7853 } 7854 if (p != null) { 7855 usesLibraryFiles.addAll(p.getAllCodePaths()); 7856 } 7857 } 7858 7859 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 7860 PackageParser.Package changingLib) throws PackageManagerException { 7861 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7862 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7863 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7864 for (int i=0; i<N; i++) { 7865 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7866 if (file == null) { 7867 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7868 "Package " + pkg.packageName + " requires unavailable shared library " 7869 + pkg.usesLibraries.get(i) + "; failing!"); 7870 } 7871 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 7872 } 7873 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7874 for (int i=0; i<N; i++) { 7875 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7876 if (file == null) { 7877 Slog.w(TAG, "Package " + pkg.packageName 7878 + " desires unavailable shared library " 7879 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7880 } else { 7881 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 7882 } 7883 } 7884 N = usesLibraryFiles.size(); 7885 if (N > 0) { 7886 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7887 } else { 7888 pkg.usesLibraryFiles = null; 7889 } 7890 } 7891 } 7892 7893 private static boolean hasString(List<String> list, List<String> which) { 7894 if (list == null) { 7895 return false; 7896 } 7897 for (int i=list.size()-1; i>=0; i--) { 7898 for (int j=which.size()-1; j>=0; j--) { 7899 if (which.get(j).equals(list.get(i))) { 7900 return true; 7901 } 7902 } 7903 } 7904 return false; 7905 } 7906 7907 private void updateAllSharedLibrariesLPw() { 7908 for (PackageParser.Package pkg : mPackages.values()) { 7909 try { 7910 updateSharedLibrariesLPr(pkg, null); 7911 } catch (PackageManagerException e) { 7912 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7913 } 7914 } 7915 } 7916 7917 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7918 PackageParser.Package changingPkg) { 7919 ArrayList<PackageParser.Package> res = null; 7920 for (PackageParser.Package pkg : mPackages.values()) { 7921 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7922 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7923 if (res == null) { 7924 res = new ArrayList<PackageParser.Package>(); 7925 } 7926 res.add(pkg); 7927 try { 7928 updateSharedLibrariesLPr(pkg, changingPkg); 7929 } catch (PackageManagerException e) { 7930 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7931 } 7932 } 7933 } 7934 return res; 7935 } 7936 7937 /** 7938 * Derive the value of the {@code cpuAbiOverride} based on the provided 7939 * value and an optional stored value from the package settings. 7940 */ 7941 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7942 String cpuAbiOverride = null; 7943 7944 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7945 cpuAbiOverride = null; 7946 } else if (abiOverride != null) { 7947 cpuAbiOverride = abiOverride; 7948 } else if (settings != null) { 7949 cpuAbiOverride = settings.cpuAbiOverrideString; 7950 } 7951 7952 return cpuAbiOverride; 7953 } 7954 7955 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7956 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7957 throws PackageManagerException { 7958 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7959 // If the package has children and this is the first dive in the function 7960 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7961 // whether all packages (parent and children) would be successfully scanned 7962 // before the actual scan since scanning mutates internal state and we want 7963 // to atomically install the package and its children. 7964 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7965 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7966 scanFlags |= SCAN_CHECK_ONLY; 7967 } 7968 } else { 7969 scanFlags &= ~SCAN_CHECK_ONLY; 7970 } 7971 7972 final PackageParser.Package scannedPkg; 7973 try { 7974 // Scan the parent 7975 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7976 // Scan the children 7977 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7978 for (int i = 0; i < childCount; i++) { 7979 PackageParser.Package childPkg = pkg.childPackages.get(i); 7980 scanPackageLI(childPkg, policyFlags, 7981 scanFlags, currentTime, user); 7982 } 7983 } finally { 7984 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7985 } 7986 7987 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7988 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7989 } 7990 7991 return scannedPkg; 7992 } 7993 7994 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7995 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7996 boolean success = false; 7997 try { 7998 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7999 currentTime, user); 8000 success = true; 8001 return res; 8002 } finally { 8003 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8004 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8005 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8006 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8007 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8008 } 8009 } 8010 } 8011 8012 /** 8013 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8014 */ 8015 private static boolean apkHasCode(String fileName) { 8016 StrictJarFile jarFile = null; 8017 try { 8018 jarFile = new StrictJarFile(fileName, 8019 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8020 return jarFile.findEntry("classes.dex") != null; 8021 } catch (IOException ignore) { 8022 } finally { 8023 try { 8024 if (jarFile != null) { 8025 jarFile.close(); 8026 } 8027 } catch (IOException ignore) {} 8028 } 8029 return false; 8030 } 8031 8032 /** 8033 * Enforces code policy for the package. This ensures that if an APK has 8034 * declared hasCode="true" in its manifest that the APK actually contains 8035 * code. 8036 * 8037 * @throws PackageManagerException If bytecode could not be found when it should exist 8038 */ 8039 private static void assertCodePolicy(PackageParser.Package pkg) 8040 throws PackageManagerException { 8041 final boolean shouldHaveCode = 8042 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8043 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8044 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8045 "Package " + pkg.baseCodePath + " code is missing"); 8046 } 8047 8048 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8049 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8050 final boolean splitShouldHaveCode = 8051 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8052 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8053 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8054 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8055 } 8056 } 8057 } 8058 } 8059 8060 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8061 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8062 throws PackageManagerException { 8063 if (DEBUG_PACKAGE_SCANNING) { 8064 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8065 Log.d(TAG, "Scanning package " + pkg.packageName); 8066 } 8067 8068 applyPolicy(pkg, policyFlags); 8069 8070 assertPackageIsValid(pkg, policyFlags, scanFlags); 8071 8072 // Initialize package source and resource directories 8073 final File scanFile = new File(pkg.codePath); 8074 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8075 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8076 8077 SharedUserSetting suid = null; 8078 PackageSetting pkgSetting = null; 8079 8080 // Getting the package setting may have a side-effect, so if we 8081 // are only checking if scan would succeed, stash a copy of the 8082 // old setting to restore at the end. 8083 PackageSetting nonMutatedPs = null; 8084 8085 // writer 8086 synchronized (mPackages) { 8087 if (pkg.mSharedUserId != null) { 8088 // SIDE EFFECTS; may potentially allocate a new shared user 8089 suid = mSettings.getSharedUserLPw( 8090 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 8091 if (DEBUG_PACKAGE_SCANNING) { 8092 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8093 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8094 + "): packages=" + suid.packages); 8095 } 8096 } 8097 8098 // Check if we are renaming from an original package name. 8099 PackageSetting origPackage = null; 8100 String realName = null; 8101 if (pkg.mOriginalPackages != null) { 8102 // This package may need to be renamed to a previously 8103 // installed name. Let's check on that... 8104 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8105 if (pkg.mOriginalPackages.contains(renamed)) { 8106 // This package had originally been installed as the 8107 // original name, and we have already taken care of 8108 // transitioning to the new one. Just update the new 8109 // one to continue using the old name. 8110 realName = pkg.mRealPackage; 8111 if (!pkg.packageName.equals(renamed)) { 8112 // Callers into this function may have already taken 8113 // care of renaming the package; only do it here if 8114 // it is not already done. 8115 pkg.setPackageName(renamed); 8116 } 8117 } else { 8118 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8119 if ((origPackage = mSettings.getPackageLPr( 8120 pkg.mOriginalPackages.get(i))) != null) { 8121 // We do have the package already installed under its 8122 // original name... should we use it? 8123 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8124 // New package is not compatible with original. 8125 origPackage = null; 8126 continue; 8127 } else if (origPackage.sharedUser != null) { 8128 // Make sure uid is compatible between packages. 8129 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8130 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8131 + " to " + pkg.packageName + ": old uid " 8132 + origPackage.sharedUser.name 8133 + " differs from " + pkg.mSharedUserId); 8134 origPackage = null; 8135 continue; 8136 } 8137 // TODO: Add case when shared user id is added [b/28144775] 8138 } else { 8139 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8140 + pkg.packageName + " to old name " + origPackage.name); 8141 } 8142 break; 8143 } 8144 } 8145 } 8146 } 8147 8148 if (mTransferedPackages.contains(pkg.packageName)) { 8149 Slog.w(TAG, "Package " + pkg.packageName 8150 + " was transferred to another, but its .apk remains"); 8151 } 8152 8153 // See comments in nonMutatedPs declaration 8154 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8155 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8156 if (foundPs != null) { 8157 nonMutatedPs = new PackageSetting(foundPs); 8158 } 8159 } 8160 8161 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8162 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 8163 PackageManagerService.reportSettingsProblem(Log.WARN, 8164 "Package " + pkg.packageName + " shared user changed from " 8165 + (pkgSetting.sharedUser != null 8166 ? pkgSetting.sharedUser.name : "<nothing>") 8167 + " to " 8168 + (suid != null ? suid.name : "<nothing>") 8169 + "; replacing with new"); 8170 pkgSetting = null; 8171 } 8172 final PackageSetting oldPkgSetting = 8173 pkgSetting == null ? null : new PackageSetting(pkgSetting); 8174 final PackageSetting disabledPkgSetting = 8175 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8176 if (pkgSetting == null) { 8177 final String parentPackageName = (pkg.parentPackage != null) 8178 ? pkg.parentPackage.packageName : null; 8179 // REMOVE SharedUserSetting from method; update in a separate call 8180 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 8181 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 8182 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 8183 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 8184 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 8185 true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(), 8186 UserManagerService.getInstance()); 8187 // SIDE EFFECTS; updates system state; move elsewhere 8188 if (origPackage != null) { 8189 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 8190 } 8191 mSettings.addUserToSettingLPw(pkgSetting); 8192 } else { 8193 // REMOVE SharedUserSetting from method; update in a separate call 8194 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 8195 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 8196 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 8197 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 8198 UserManagerService.getInstance()); 8199 } 8200 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 8201 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 8202 8203 // SIDE EFFECTS; modifies system state; move elsewhere 8204 if (pkgSetting.origPackage != null) { 8205 // If we are first transitioning from an original package, 8206 // fix up the new package's name now. We need to do this after 8207 // looking up the package under its new name, so getPackageLP 8208 // can take care of fiddling things correctly. 8209 pkg.setPackageName(origPackage.name); 8210 8211 // File a report about this. 8212 String msg = "New package " + pkgSetting.realName 8213 + " renamed to replace old package " + pkgSetting.name; 8214 reportSettingsProblem(Log.WARN, msg); 8215 8216 // Make a note of it. 8217 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8218 mTransferedPackages.add(origPackage.name); 8219 } 8220 8221 // No longer need to retain this. 8222 pkgSetting.origPackage = null; 8223 } 8224 8225 // SIDE EFFECTS; modifies system state; move elsewhere 8226 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8227 // Make a note of it. 8228 mTransferedPackages.add(pkg.packageName); 8229 } 8230 8231 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8232 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8233 } 8234 8235 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8236 // Check all shared libraries and map to their actual file path. 8237 // We only do this here for apps not on a system dir, because those 8238 // are the only ones that can fail an install due to this. We 8239 // will take care of the system apps by updating all of their 8240 // library paths after the scan is done. 8241 updateSharedLibrariesLPr(pkg, null); 8242 } 8243 8244 if (mFoundPolicyFile) { 8245 SELinuxMMAC.assignSeinfoValue(pkg); 8246 } 8247 8248 pkg.applicationInfo.uid = pkgSetting.appId; 8249 pkg.mExtras = pkgSetting; 8250 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8251 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8252 // We just determined the app is signed correctly, so bring 8253 // over the latest parsed certs. 8254 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8255 } else { 8256 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8257 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8258 "Package " + pkg.packageName + " upgrade keys do not match the " 8259 + "previously installed version"); 8260 } else { 8261 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8262 String msg = "System package " + pkg.packageName 8263 + " signature changed; retaining data."; 8264 reportSettingsProblem(Log.WARN, msg); 8265 } 8266 } 8267 } else { 8268 try { 8269 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 8270 verifySignaturesLP(pkgSetting, pkg); 8271 // We just determined the app is signed correctly, so bring 8272 // over the latest parsed certs. 8273 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8274 } catch (PackageManagerException e) { 8275 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8276 throw e; 8277 } 8278 // The signature has changed, but this package is in the system 8279 // image... let's recover! 8280 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8281 // However... if this package is part of a shared user, but it 8282 // doesn't match the signature of the shared user, let's fail. 8283 // What this means is that you can't change the signatures 8284 // associated with an overall shared user, which doesn't seem all 8285 // that unreasonable. 8286 if (pkgSetting.sharedUser != null) { 8287 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8288 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8289 throw new PackageManagerException( 8290 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8291 "Signature mismatch for shared user: " 8292 + pkgSetting.sharedUser); 8293 } 8294 } 8295 // File a report about this. 8296 String msg = "System package " + pkg.packageName 8297 + " signature changed; retaining data."; 8298 reportSettingsProblem(Log.WARN, msg); 8299 } 8300 } 8301 8302 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8303 // This package wants to adopt ownership of permissions from 8304 // another package. 8305 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8306 final String origName = pkg.mAdoptPermissions.get(i); 8307 final PackageSetting orig = mSettings.getPackageLPr(origName); 8308 if (orig != null) { 8309 if (verifyPackageUpdateLPr(orig, pkg)) { 8310 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8311 + pkg.packageName); 8312 // SIDE EFFECTS; updates permissions system state; move elsewhere 8313 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8314 } 8315 } 8316 } 8317 } 8318 } 8319 8320 pkg.applicationInfo.processName = fixProcessName( 8321 pkg.applicationInfo.packageName, 8322 pkg.applicationInfo.processName); 8323 8324 if (pkg != mPlatformPackage) { 8325 // Get all of our default paths setup 8326 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8327 } 8328 8329 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8330 8331 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8332 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 8333 derivePackageAbi( 8334 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 8335 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8336 8337 // Some system apps still use directory structure for native libraries 8338 // in which case we might end up not detecting abi solely based on apk 8339 // structure. Try to detect abi based on directory structure. 8340 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8341 pkg.applicationInfo.primaryCpuAbi == null) { 8342 setBundledAppAbisAndRoots(pkg, pkgSetting); 8343 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8344 } 8345 } else { 8346 if ((scanFlags & SCAN_MOVE) != 0) { 8347 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8348 // but we already have this packages package info in the PackageSetting. We just 8349 // use that and derive the native library path based on the new codepath. 8350 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8351 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8352 } 8353 8354 // Set native library paths again. For moves, the path will be updated based on the 8355 // ABIs we've determined above. For non-moves, the path will be updated based on the 8356 // ABIs we determined during compilation, but the path will depend on the final 8357 // package path (after the rename away from the stage path). 8358 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8359 } 8360 8361 // This is a special case for the "system" package, where the ABI is 8362 // dictated by the zygote configuration (and init.rc). We should keep track 8363 // of this ABI so that we can deal with "normal" applications that run under 8364 // the same UID correctly. 8365 if (mPlatformPackage == pkg) { 8366 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8367 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8368 } 8369 8370 // If there's a mismatch between the abi-override in the package setting 8371 // and the abiOverride specified for the install. Warn about this because we 8372 // would've already compiled the app without taking the package setting into 8373 // account. 8374 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8375 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8376 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8377 " for package " + pkg.packageName); 8378 } 8379 } 8380 8381 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8382 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8383 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8384 8385 // Copy the derived override back to the parsed package, so that we can 8386 // update the package settings accordingly. 8387 pkg.cpuAbiOverride = cpuAbiOverride; 8388 8389 if (DEBUG_ABI_SELECTION) { 8390 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8391 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8392 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8393 } 8394 8395 // Push the derived path down into PackageSettings so we know what to 8396 // clean up at uninstall time. 8397 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8398 8399 if (DEBUG_ABI_SELECTION) { 8400 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8401 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8402 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8403 } 8404 8405 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 8406 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8407 // We don't do this here during boot because we can do it all 8408 // at once after scanning all existing packages. 8409 // 8410 // We also do this *before* we perform dexopt on this package, so that 8411 // we can avoid redundant dexopts, and also to make sure we've got the 8412 // code and package path correct. 8413 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 8414 } 8415 8416 if (mFactoryTest && pkg.requestedPermissions.contains( 8417 android.Manifest.permission.FACTORY_TEST)) { 8418 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8419 } 8420 8421 if (isSystemApp(pkg)) { 8422 pkgSetting.isOrphaned = true; 8423 } 8424 8425 // Take care of first install / last update times. 8426 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8427 if (currentTime != 0) { 8428 if (pkgSetting.firstInstallTime == 0) { 8429 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8430 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 8431 pkgSetting.lastUpdateTime = currentTime; 8432 } 8433 } else if (pkgSetting.firstInstallTime == 0) { 8434 // We need *something*. Take time time stamp of the file. 8435 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8436 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8437 if (scanFileTime != pkgSetting.timeStamp) { 8438 // A package on the system image has changed; consider this 8439 // to be an update. 8440 pkgSetting.lastUpdateTime = scanFileTime; 8441 } 8442 } 8443 pkgSetting.setTimeStamp(scanFileTime); 8444 8445 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8446 if (nonMutatedPs != null) { 8447 synchronized (mPackages) { 8448 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8449 } 8450 } 8451 } else { 8452 // Modify state for the given package setting 8453 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 8454 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 8455 } 8456 return pkg; 8457 } 8458 8459 /** 8460 * Applies policy to the parsed package based upon the given policy flags. 8461 * Ensures the package is in a good state. 8462 * <p> 8463 * Implementation detail: This method must NOT have any side effect. It would 8464 * ideally be static, but, it requires locks to read system state. 8465 */ 8466 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 8467 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8468 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8469 if (pkg.applicationInfo.isDirectBootAware()) { 8470 // we're direct boot aware; set for all components 8471 for (PackageParser.Service s : pkg.services) { 8472 s.info.encryptionAware = s.info.directBootAware = true; 8473 } 8474 for (PackageParser.Provider p : pkg.providers) { 8475 p.info.encryptionAware = p.info.directBootAware = true; 8476 } 8477 for (PackageParser.Activity a : pkg.activities) { 8478 a.info.encryptionAware = a.info.directBootAware = true; 8479 } 8480 for (PackageParser.Activity r : pkg.receivers) { 8481 r.info.encryptionAware = r.info.directBootAware = true; 8482 } 8483 } 8484 } else { 8485 // Only allow system apps to be flagged as core apps. 8486 pkg.coreApp = false; 8487 // clear flags not applicable to regular apps 8488 pkg.applicationInfo.privateFlags &= 8489 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8490 pkg.applicationInfo.privateFlags &= 8491 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8492 } 8493 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8494 8495 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8496 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8497 } 8498 8499 if (!isSystemApp(pkg)) { 8500 // Only system apps can use these features. 8501 pkg.mOriginalPackages = null; 8502 pkg.mRealPackage = null; 8503 pkg.mAdoptPermissions = null; 8504 } 8505 } 8506 8507 /** 8508 * Asserts the parsed package is valid according to teh given policy. If the 8509 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 8510 * <p> 8511 * Implementation detail: This method must NOT have any side effects. It would 8512 * ideally be static, but, it requires locks to read system state. 8513 * 8514 * @throws PackageManagerException If the package fails any of the validation checks 8515 */ 8516 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 8517 throws PackageManagerException { 8518 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8519 assertCodePolicy(pkg); 8520 } 8521 8522 if (pkg.applicationInfo.getCodePath() == null || 8523 pkg.applicationInfo.getResourcePath() == null) { 8524 // Bail out. The resource and code paths haven't been set. 8525 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8526 "Code and resource paths haven't been set correctly"); 8527 } 8528 8529 // Make sure we're not adding any bogus keyset info 8530 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8531 ksms.assertScannedPackageValid(pkg); 8532 8533 synchronized (mPackages) { 8534 // The special "android" package can only be defined once 8535 if (pkg.packageName.equals("android")) { 8536 if (mAndroidApplication != null) { 8537 Slog.w(TAG, "*************************************************"); 8538 Slog.w(TAG, "Core android package being redefined. Skipping."); 8539 Slog.w(TAG, " codePath=" + pkg.codePath); 8540 Slog.w(TAG, "*************************************************"); 8541 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8542 "Core android package being redefined. Skipping."); 8543 } 8544 } 8545 8546 // A package name must be unique; don't allow duplicates 8547 if (mPackages.containsKey(pkg.packageName) 8548 || mSharedLibraries.containsKey(pkg.packageName)) { 8549 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8550 "Application package " + pkg.packageName 8551 + " already installed. Skipping duplicate."); 8552 } 8553 8554 // Only privileged apps and updated privileged apps can add child packages. 8555 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8556 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8557 throw new PackageManagerException("Only privileged apps can add child " 8558 + "packages. Ignoring package " + pkg.packageName); 8559 } 8560 final int childCount = pkg.childPackages.size(); 8561 for (int i = 0; i < childCount; i++) { 8562 PackageParser.Package childPkg = pkg.childPackages.get(i); 8563 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8564 childPkg.packageName)) { 8565 throw new PackageManagerException("Can't override child of " 8566 + "another disabled app. Ignoring package " + pkg.packageName); 8567 } 8568 } 8569 } 8570 8571 // If we're only installing presumed-existing packages, require that the 8572 // scanned APK is both already known and at the path previously established 8573 // for it. Previously unknown packages we pick up normally, but if we have an 8574 // a priori expectation about this package's install presence, enforce it. 8575 // With a singular exception for new system packages. When an OTA contains 8576 // a new system package, we allow the codepath to change from a system location 8577 // to the user-installed location. If we don't allow this change, any newer, 8578 // user-installed version of the application will be ignored. 8579 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8580 if (mExpectingBetter.containsKey(pkg.packageName)) { 8581 logCriticalInfo(Log.WARN, 8582 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8583 } else { 8584 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 8585 if (known != null) { 8586 if (DEBUG_PACKAGE_SCANNING) { 8587 Log.d(TAG, "Examining " + pkg.codePath 8588 + " and requiring known paths " + known.codePathString 8589 + " & " + known.resourcePathString); 8590 } 8591 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8592 || !pkg.applicationInfo.getResourcePath().equals( 8593 known.resourcePathString)) { 8594 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8595 "Application package " + pkg.packageName 8596 + " found at " + pkg.applicationInfo.getCodePath() 8597 + " but expected at " + known.codePathString 8598 + "; ignoring."); 8599 } 8600 } 8601 } 8602 } 8603 8604 // Verify that this new package doesn't have any content providers 8605 // that conflict with existing packages. Only do this if the 8606 // package isn't already installed, since we don't want to break 8607 // things that are installed. 8608 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8609 final int N = pkg.providers.size(); 8610 int i; 8611 for (i=0; i<N; i++) { 8612 PackageParser.Provider p = pkg.providers.get(i); 8613 if (p.info.authority != null) { 8614 String names[] = p.info.authority.split(";"); 8615 for (int j = 0; j < names.length; j++) { 8616 if (mProvidersByAuthority.containsKey(names[j])) { 8617 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8618 final String otherPackageName = 8619 ((other != null && other.getComponentName() != null) ? 8620 other.getComponentName().getPackageName() : "?"); 8621 throw new PackageManagerException( 8622 INSTALL_FAILED_CONFLICTING_PROVIDER, 8623 "Can't install because provider name " + names[j] 8624 + " (in package " + pkg.applicationInfo.packageName 8625 + ") is already used by " + otherPackageName); 8626 } 8627 } 8628 } 8629 } 8630 } 8631 } 8632 } 8633 8634 /** 8635 * Adds a scanned package to the system. When this method is finished, the package will 8636 * be available for query, resolution, etc... 8637 */ 8638 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 8639 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 8640 final String pkgName = pkg.packageName; 8641 if (mCustomResolverComponentName != null && 8642 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8643 setUpCustomResolverActivity(pkg); 8644 } 8645 8646 if (pkg.packageName.equals("android")) { 8647 synchronized (mPackages) { 8648 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8649 // Set up information for our fall-back user intent resolution activity. 8650 mPlatformPackage = pkg; 8651 pkg.mVersionCode = mSdkVersion; 8652 mAndroidApplication = pkg.applicationInfo; 8653 8654 if (!mResolverReplaced) { 8655 mResolveActivity.applicationInfo = mAndroidApplication; 8656 mResolveActivity.name = ResolverActivity.class.getName(); 8657 mResolveActivity.packageName = mAndroidApplication.packageName; 8658 mResolveActivity.processName = "system:ui"; 8659 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8660 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8661 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8662 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8663 mResolveActivity.exported = true; 8664 mResolveActivity.enabled = true; 8665 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8666 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8667 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8668 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8669 | ActivityInfo.CONFIG_ORIENTATION 8670 | ActivityInfo.CONFIG_KEYBOARD 8671 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8672 mResolveInfo.activityInfo = mResolveActivity; 8673 mResolveInfo.priority = 0; 8674 mResolveInfo.preferredOrder = 0; 8675 mResolveInfo.match = 0; 8676 mResolveComponentName = new ComponentName( 8677 mAndroidApplication.packageName, mResolveActivity.name); 8678 } 8679 } 8680 } 8681 } 8682 8683 ArrayList<PackageParser.Package> clientLibPkgs = null; 8684 // writer 8685 synchronized (mPackages) { 8686 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8687 // Only system apps can add new shared libraries. 8688 if (pkg.libraryNames != null) { 8689 for (int i=0; i<pkg.libraryNames.size(); i++) { 8690 String name = pkg.libraryNames.get(i); 8691 boolean allowed = false; 8692 if (pkg.isUpdatedSystemApp()) { 8693 // New library entries can only be added through the 8694 // system image. This is important to get rid of a lot 8695 // of nasty edge cases: for example if we allowed a non- 8696 // system update of the app to add a library, then uninstalling 8697 // the update would make the library go away, and assumptions 8698 // we made such as through app install filtering would now 8699 // have allowed apps on the device which aren't compatible 8700 // with it. Better to just have the restriction here, be 8701 // conservative, and create many fewer cases that can negatively 8702 // impact the user experience. 8703 final PackageSetting sysPs = mSettings 8704 .getDisabledSystemPkgLPr(pkg.packageName); 8705 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8706 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8707 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8708 allowed = true; 8709 break; 8710 } 8711 } 8712 } 8713 } else { 8714 allowed = true; 8715 } 8716 if (allowed) { 8717 if (!mSharedLibraries.containsKey(name)) { 8718 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8719 } else if (!name.equals(pkg.packageName)) { 8720 Slog.w(TAG, "Package " + pkg.packageName + " library " 8721 + name + " already exists; skipping"); 8722 } 8723 } else { 8724 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8725 + name + " that is not declared on system image; skipping"); 8726 } 8727 } 8728 if ((scanFlags & SCAN_BOOTING) == 0) { 8729 // If we are not booting, we need to update any applications 8730 // that are clients of our shared library. If we are booting, 8731 // this will all be done once the scan is complete. 8732 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8733 } 8734 } 8735 } 8736 } 8737 8738 if ((scanFlags & SCAN_BOOTING) != 0) { 8739 // No apps can run during boot scan, so they don't need to be frozen 8740 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8741 // Caller asked to not kill app, so it's probably not frozen 8742 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8743 // Caller asked us to ignore frozen check for some reason; they 8744 // probably didn't know the package name 8745 } else { 8746 // We're doing major surgery on this package, so it better be frozen 8747 // right now to keep it from launching 8748 checkPackageFrozen(pkgName); 8749 } 8750 8751 // Also need to kill any apps that are dependent on the library. 8752 if (clientLibPkgs != null) { 8753 for (int i=0; i<clientLibPkgs.size(); i++) { 8754 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8755 killApplication(clientPkg.applicationInfo.packageName, 8756 clientPkg.applicationInfo.uid, "update lib"); 8757 } 8758 } 8759 8760 // writer 8761 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8762 8763 boolean createIdmapFailed = false; 8764 synchronized (mPackages) { 8765 // We don't expect installation to fail beyond this point 8766 8767 if (pkgSetting.pkg != null) { 8768 // Note that |user| might be null during the initial boot scan. If a codePath 8769 // for an app has changed during a boot scan, it's due to an app update that's 8770 // part of the system partition and marker changes must be applied to all users. 8771 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 8772 final int[] userIds = resolveUserIds(userId); 8773 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 8774 } 8775 8776 // Add the new setting to mSettings 8777 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8778 // Add the new setting to mPackages 8779 mPackages.put(pkg.applicationInfo.packageName, pkg); 8780 // Make sure we don't accidentally delete its data. 8781 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8782 while (iter.hasNext()) { 8783 PackageCleanItem item = iter.next(); 8784 if (pkgName.equals(item.packageName)) { 8785 iter.remove(); 8786 } 8787 } 8788 8789 // Add the package's KeySets to the global KeySetManagerService 8790 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8791 ksms.addScannedPackageLPw(pkg); 8792 8793 int N = pkg.providers.size(); 8794 StringBuilder r = null; 8795 int i; 8796 for (i=0; i<N; i++) { 8797 PackageParser.Provider p = pkg.providers.get(i); 8798 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8799 p.info.processName); 8800 mProviders.addProvider(p); 8801 p.syncable = p.info.isSyncable; 8802 if (p.info.authority != null) { 8803 String names[] = p.info.authority.split(";"); 8804 p.info.authority = null; 8805 for (int j = 0; j < names.length; j++) { 8806 if (j == 1 && p.syncable) { 8807 // We only want the first authority for a provider to possibly be 8808 // syncable, so if we already added this provider using a different 8809 // authority clear the syncable flag. We copy the provider before 8810 // changing it because the mProviders object contains a reference 8811 // to a provider that we don't want to change. 8812 // Only do this for the second authority since the resulting provider 8813 // object can be the same for all future authorities for this provider. 8814 p = new PackageParser.Provider(p); 8815 p.syncable = false; 8816 } 8817 if (!mProvidersByAuthority.containsKey(names[j])) { 8818 mProvidersByAuthority.put(names[j], p); 8819 if (p.info.authority == null) { 8820 p.info.authority = names[j]; 8821 } else { 8822 p.info.authority = p.info.authority + ";" + names[j]; 8823 } 8824 if (DEBUG_PACKAGE_SCANNING) { 8825 if (chatty) 8826 Log.d(TAG, "Registered content provider: " + names[j] 8827 + ", className = " + p.info.name + ", isSyncable = " 8828 + p.info.isSyncable); 8829 } 8830 } else { 8831 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8832 Slog.w(TAG, "Skipping provider name " + names[j] + 8833 " (in package " + pkg.applicationInfo.packageName + 8834 "): name already used by " 8835 + ((other != null && other.getComponentName() != null) 8836 ? other.getComponentName().getPackageName() : "?")); 8837 } 8838 } 8839 } 8840 if (chatty) { 8841 if (r == null) { 8842 r = new StringBuilder(256); 8843 } else { 8844 r.append(' '); 8845 } 8846 r.append(p.info.name); 8847 } 8848 } 8849 if (r != null) { 8850 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8851 } 8852 8853 N = pkg.services.size(); 8854 r = null; 8855 for (i=0; i<N; i++) { 8856 PackageParser.Service s = pkg.services.get(i); 8857 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8858 s.info.processName); 8859 mServices.addService(s); 8860 if (chatty) { 8861 if (r == null) { 8862 r = new StringBuilder(256); 8863 } else { 8864 r.append(' '); 8865 } 8866 r.append(s.info.name); 8867 } 8868 } 8869 if (r != null) { 8870 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8871 } 8872 8873 N = pkg.receivers.size(); 8874 r = null; 8875 for (i=0; i<N; i++) { 8876 PackageParser.Activity a = pkg.receivers.get(i); 8877 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8878 a.info.processName); 8879 mReceivers.addActivity(a, "receiver"); 8880 if (chatty) { 8881 if (r == null) { 8882 r = new StringBuilder(256); 8883 } else { 8884 r.append(' '); 8885 } 8886 r.append(a.info.name); 8887 } 8888 } 8889 if (r != null) { 8890 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8891 } 8892 8893 N = pkg.activities.size(); 8894 r = null; 8895 for (i=0; i<N; i++) { 8896 PackageParser.Activity a = pkg.activities.get(i); 8897 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8898 a.info.processName); 8899 mActivities.addActivity(a, "activity"); 8900 if (chatty) { 8901 if (r == null) { 8902 r = new StringBuilder(256); 8903 } else { 8904 r.append(' '); 8905 } 8906 r.append(a.info.name); 8907 } 8908 } 8909 if (r != null) { 8910 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8911 } 8912 8913 N = pkg.permissionGroups.size(); 8914 r = null; 8915 for (i=0; i<N; i++) { 8916 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8917 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8918 final String curPackageName = cur == null ? null : cur.info.packageName; 8919 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 8920 if (cur == null || isPackageUpdate) { 8921 mPermissionGroups.put(pg.info.name, pg); 8922 if (chatty) { 8923 if (r == null) { 8924 r = new StringBuilder(256); 8925 } else { 8926 r.append(' '); 8927 } 8928 if (isPackageUpdate) { 8929 r.append("UPD:"); 8930 } 8931 r.append(pg.info.name); 8932 } 8933 } else { 8934 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8935 + pg.info.packageName + " ignored: original from " 8936 + cur.info.packageName); 8937 if (chatty) { 8938 if (r == null) { 8939 r = new StringBuilder(256); 8940 } else { 8941 r.append(' '); 8942 } 8943 r.append("DUP:"); 8944 r.append(pg.info.name); 8945 } 8946 } 8947 } 8948 if (r != null) { 8949 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8950 } 8951 8952 N = pkg.permissions.size(); 8953 r = null; 8954 for (i=0; i<N; i++) { 8955 PackageParser.Permission p = pkg.permissions.get(i); 8956 8957 // Assume by default that we did not install this permission into the system. 8958 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8959 8960 // Now that permission groups have a special meaning, we ignore permission 8961 // groups for legacy apps to prevent unexpected behavior. In particular, 8962 // permissions for one app being granted to someone just becase they happen 8963 // to be in a group defined by another app (before this had no implications). 8964 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8965 p.group = mPermissionGroups.get(p.info.group); 8966 // Warn for a permission in an unknown group. 8967 if (p.info.group != null && p.group == null) { 8968 Slog.w(TAG, "Permission " + p.info.name + " from package " 8969 + p.info.packageName + " in an unknown group " + p.info.group); 8970 } 8971 } 8972 8973 ArrayMap<String, BasePermission> permissionMap = 8974 p.tree ? mSettings.mPermissionTrees 8975 : mSettings.mPermissions; 8976 BasePermission bp = permissionMap.get(p.info.name); 8977 8978 // Allow system apps to redefine non-system permissions 8979 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8980 final boolean currentOwnerIsSystem = (bp.perm != null 8981 && isSystemApp(bp.perm.owner)); 8982 if (isSystemApp(p.owner)) { 8983 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8984 // It's a built-in permission and no owner, take ownership now 8985 bp.packageSetting = pkgSetting; 8986 bp.perm = p; 8987 bp.uid = pkg.applicationInfo.uid; 8988 bp.sourcePackage = p.info.packageName; 8989 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8990 } else if (!currentOwnerIsSystem) { 8991 String msg = "New decl " + p.owner + " of permission " 8992 + p.info.name + " is system; overriding " + bp.sourcePackage; 8993 reportSettingsProblem(Log.WARN, msg); 8994 bp = null; 8995 } 8996 } 8997 } 8998 8999 if (bp == null) { 9000 bp = new BasePermission(p.info.name, p.info.packageName, 9001 BasePermission.TYPE_NORMAL); 9002 permissionMap.put(p.info.name, bp); 9003 } 9004 9005 if (bp.perm == null) { 9006 if (bp.sourcePackage == null 9007 || bp.sourcePackage.equals(p.info.packageName)) { 9008 BasePermission tree = findPermissionTreeLP(p.info.name); 9009 if (tree == null 9010 || tree.sourcePackage.equals(p.info.packageName)) { 9011 bp.packageSetting = pkgSetting; 9012 bp.perm = p; 9013 bp.uid = pkg.applicationInfo.uid; 9014 bp.sourcePackage = p.info.packageName; 9015 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9016 if (chatty) { 9017 if (r == null) { 9018 r = new StringBuilder(256); 9019 } else { 9020 r.append(' '); 9021 } 9022 r.append(p.info.name); 9023 } 9024 } else { 9025 Slog.w(TAG, "Permission " + p.info.name + " from package " 9026 + p.info.packageName + " ignored: base tree " 9027 + tree.name + " is from package " 9028 + tree.sourcePackage); 9029 } 9030 } else { 9031 Slog.w(TAG, "Permission " + p.info.name + " from package " 9032 + p.info.packageName + " ignored: original from " 9033 + bp.sourcePackage); 9034 } 9035 } else if (chatty) { 9036 if (r == null) { 9037 r = new StringBuilder(256); 9038 } else { 9039 r.append(' '); 9040 } 9041 r.append("DUP:"); 9042 r.append(p.info.name); 9043 } 9044 if (bp.perm == p) { 9045 bp.protectionLevel = p.info.protectionLevel; 9046 } 9047 } 9048 9049 if (r != null) { 9050 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 9051 } 9052 9053 N = pkg.instrumentation.size(); 9054 r = null; 9055 for (i=0; i<N; i++) { 9056 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9057 a.info.packageName = pkg.applicationInfo.packageName; 9058 a.info.sourceDir = pkg.applicationInfo.sourceDir; 9059 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 9060 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 9061 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 9062 a.info.dataDir = pkg.applicationInfo.dataDir; 9063 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 9064 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 9065 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 9066 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 9067 mInstrumentation.put(a.getComponentName(), a); 9068 if (chatty) { 9069 if (r == null) { 9070 r = new StringBuilder(256); 9071 } else { 9072 r.append(' '); 9073 } 9074 r.append(a.info.name); 9075 } 9076 } 9077 if (r != null) { 9078 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9079 } 9080 9081 if (pkg.protectedBroadcasts != null) { 9082 N = pkg.protectedBroadcasts.size(); 9083 for (i=0; i<N; i++) { 9084 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9085 } 9086 } 9087 9088 // Create idmap files for pairs of (packages, overlay packages). 9089 // Note: "android", ie framework-res.apk, is handled by native layers. 9090 if (pkg.mOverlayTarget != null) { 9091 // This is an overlay package. 9092 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9093 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9094 mOverlays.put(pkg.mOverlayTarget, 9095 new ArrayMap<String, PackageParser.Package>()); 9096 } 9097 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9098 map.put(pkg.packageName, pkg); 9099 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9100 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9101 createIdmapFailed = true; 9102 } 9103 } 9104 } else if (mOverlays.containsKey(pkg.packageName) && 9105 !pkg.packageName.equals("android")) { 9106 // This is a regular package, with one or more known overlay packages. 9107 createIdmapsForPackageLI(pkg); 9108 } 9109 } 9110 9111 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9112 9113 if (createIdmapFailed) { 9114 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9115 "scanPackageLI failed to createIdmap"); 9116 } 9117 } 9118 9119 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9120 PackageParser.Package update, int[] userIds) { 9121 if (existing.applicationInfo == null || update.applicationInfo == null) { 9122 // This isn't due to an app installation. 9123 return; 9124 } 9125 9126 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9127 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9128 9129 // The codePath hasn't changed, so there's nothing for us to do. 9130 if (Objects.equals(oldCodePath, newCodePath)) { 9131 return; 9132 } 9133 9134 File canonicalNewCodePath; 9135 try { 9136 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9137 } catch (IOException e) { 9138 Slog.w(TAG, "Failed to get canonical path.", e); 9139 return; 9140 } 9141 9142 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9143 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9144 // that the last component of the path (i.e, the name) doesn't need canonicalization 9145 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9146 // but may change in the future. Hopefully this function won't exist at that point. 9147 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9148 oldCodePath.getName()); 9149 9150 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9151 // with "@". 9152 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9153 if (!oldMarkerPrefix.endsWith("@")) { 9154 oldMarkerPrefix += "@"; 9155 } 9156 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9157 if (!newMarkerPrefix.endsWith("@")) { 9158 newMarkerPrefix += "@"; 9159 } 9160 9161 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9162 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9163 for (String updatedPath : updatedPaths) { 9164 String updatedPathName = new File(updatedPath).getName(); 9165 markerSuffixes.add(updatedPathName.replace('/', '@')); 9166 } 9167 9168 for (int userId : userIds) { 9169 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9170 9171 for (String markerSuffix : markerSuffixes) { 9172 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9173 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9174 if (oldForeignUseMark.exists()) { 9175 try { 9176 Os.rename(oldForeignUseMark.getAbsolutePath(), 9177 newForeignUseMark.getAbsolutePath()); 9178 } catch (ErrnoException e) { 9179 Slog.w(TAG, "Failed to rename foreign use marker", e); 9180 oldForeignUseMark.delete(); 9181 } 9182 } 9183 } 9184 } 9185 } 9186 9187 /** 9188 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9189 * is derived purely on the basis of the contents of {@code scanFile} and 9190 * {@code cpuAbiOverride}. 9191 * 9192 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9193 */ 9194 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9195 String cpuAbiOverride, boolean extractLibs, 9196 File appLib32InstallDir) 9197 throws PackageManagerException { 9198 // TODO: We can probably be smarter about this stuff. For installed apps, 9199 // we can calculate this information at install time once and for all. For 9200 // system apps, we can probably assume that this information doesn't change 9201 // after the first boot scan. As things stand, we do lots of unnecessary work. 9202 9203 // Give ourselves some initial paths; we'll come back for another 9204 // pass once we've determined ABI below. 9205 setNativeLibraryPaths(pkg, appLib32InstallDir); 9206 9207 // We would never need to extract libs for forward-locked and external packages, 9208 // since the container service will do it for us. We shouldn't attempt to 9209 // extract libs from system app when it was not updated. 9210 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9211 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9212 extractLibs = false; 9213 } 9214 9215 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9216 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9217 9218 NativeLibraryHelper.Handle handle = null; 9219 try { 9220 handle = NativeLibraryHelper.Handle.create(pkg); 9221 // TODO(multiArch): This can be null for apps that didn't go through the 9222 // usual installation process. We can calculate it again, like we 9223 // do during install time. 9224 // 9225 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9226 // unnecessary. 9227 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9228 9229 // Null out the abis so that they can be recalculated. 9230 pkg.applicationInfo.primaryCpuAbi = null; 9231 pkg.applicationInfo.secondaryCpuAbi = null; 9232 if (isMultiArch(pkg.applicationInfo)) { 9233 // Warn if we've set an abiOverride for multi-lib packages.. 9234 // By definition, we need to copy both 32 and 64 bit libraries for 9235 // such packages. 9236 if (pkg.cpuAbiOverride != null 9237 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9238 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9239 } 9240 9241 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9242 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9243 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9244 if (extractLibs) { 9245 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9246 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9247 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9248 useIsaSpecificSubdirs); 9249 } else { 9250 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9251 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9252 } 9253 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9254 } 9255 9256 maybeThrowExceptionForMultiArchCopy( 9257 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9258 9259 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9260 if (extractLibs) { 9261 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9262 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9263 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9264 useIsaSpecificSubdirs); 9265 } else { 9266 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9267 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9268 } 9269 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9270 } 9271 9272 maybeThrowExceptionForMultiArchCopy( 9273 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9274 9275 if (abi64 >= 0) { 9276 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9277 } 9278 9279 if (abi32 >= 0) { 9280 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9281 if (abi64 >= 0) { 9282 if (pkg.use32bitAbi) { 9283 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9284 pkg.applicationInfo.primaryCpuAbi = abi; 9285 } else { 9286 pkg.applicationInfo.secondaryCpuAbi = abi; 9287 } 9288 } else { 9289 pkg.applicationInfo.primaryCpuAbi = abi; 9290 } 9291 } 9292 9293 } else { 9294 String[] abiList = (cpuAbiOverride != null) ? 9295 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9296 9297 // Enable gross and lame hacks for apps that are built with old 9298 // SDK tools. We must scan their APKs for renderscript bitcode and 9299 // not launch them if it's present. Don't bother checking on devices 9300 // that don't have 64 bit support. 9301 boolean needsRenderScriptOverride = false; 9302 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9303 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9304 abiList = Build.SUPPORTED_32_BIT_ABIS; 9305 needsRenderScriptOverride = true; 9306 } 9307 9308 final int copyRet; 9309 if (extractLibs) { 9310 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9311 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9312 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9313 } else { 9314 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9315 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9316 } 9317 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9318 9319 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9320 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9321 "Error unpackaging native libs for app, errorCode=" + copyRet); 9322 } 9323 9324 if (copyRet >= 0) { 9325 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9326 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9327 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9328 } else if (needsRenderScriptOverride) { 9329 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9330 } 9331 } 9332 } catch (IOException ioe) { 9333 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9334 } finally { 9335 IoUtils.closeQuietly(handle); 9336 } 9337 9338 // Now that we've calculated the ABIs and determined if it's an internal app, 9339 // we will go ahead and populate the nativeLibraryPath. 9340 setNativeLibraryPaths(pkg, appLib32InstallDir); 9341 } 9342 9343 /** 9344 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9345 * i.e, so that all packages can be run inside a single process if required. 9346 * 9347 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9348 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9349 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9350 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9351 * updating a package that belongs to a shared user. 9352 * 9353 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9354 * adds unnecessary complexity. 9355 */ 9356 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9357 PackageParser.Package scannedPackage) { 9358 String requiredInstructionSet = null; 9359 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9360 requiredInstructionSet = VMRuntime.getInstructionSet( 9361 scannedPackage.applicationInfo.primaryCpuAbi); 9362 } 9363 9364 PackageSetting requirer = null; 9365 for (PackageSetting ps : packagesForUser) { 9366 // If packagesForUser contains scannedPackage, we skip it. This will happen 9367 // when scannedPackage is an update of an existing package. Without this check, 9368 // we will never be able to change the ABI of any package belonging to a shared 9369 // user, even if it's compatible with other packages. 9370 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9371 if (ps.primaryCpuAbiString == null) { 9372 continue; 9373 } 9374 9375 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9376 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9377 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9378 // this but there's not much we can do. 9379 String errorMessage = "Instruction set mismatch, " 9380 + ((requirer == null) ? "[caller]" : requirer) 9381 + " requires " + requiredInstructionSet + " whereas " + ps 9382 + " requires " + instructionSet; 9383 Slog.w(TAG, errorMessage); 9384 } 9385 9386 if (requiredInstructionSet == null) { 9387 requiredInstructionSet = instructionSet; 9388 requirer = ps; 9389 } 9390 } 9391 } 9392 9393 if (requiredInstructionSet != null) { 9394 String adjustedAbi; 9395 if (requirer != null) { 9396 // requirer != null implies that either scannedPackage was null or that scannedPackage 9397 // did not require an ABI, in which case we have to adjust scannedPackage to match 9398 // the ABI of the set (which is the same as requirer's ABI) 9399 adjustedAbi = requirer.primaryCpuAbiString; 9400 if (scannedPackage != null) { 9401 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9402 } 9403 } else { 9404 // requirer == null implies that we're updating all ABIs in the set to 9405 // match scannedPackage. 9406 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9407 } 9408 9409 for (PackageSetting ps : packagesForUser) { 9410 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9411 if (ps.primaryCpuAbiString != null) { 9412 continue; 9413 } 9414 9415 ps.primaryCpuAbiString = adjustedAbi; 9416 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9417 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9418 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9419 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9420 + " (requirer=" 9421 + (requirer == null ? "null" : requirer.pkg.packageName) 9422 + ", scannedPackage=" 9423 + (scannedPackage != null ? scannedPackage.packageName : "null") 9424 + ")"); 9425 try { 9426 mInstaller.rmdex(ps.codePathString, 9427 getDexCodeInstructionSet(getPreferredInstructionSet())); 9428 } catch (InstallerException ignored) { 9429 } 9430 } 9431 } 9432 } 9433 } 9434 } 9435 9436 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9437 synchronized (mPackages) { 9438 mResolverReplaced = true; 9439 // Set up information for custom user intent resolution activity. 9440 mResolveActivity.applicationInfo = pkg.applicationInfo; 9441 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9442 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9443 mResolveActivity.processName = pkg.applicationInfo.packageName; 9444 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9445 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9446 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9447 mResolveActivity.theme = 0; 9448 mResolveActivity.exported = true; 9449 mResolveActivity.enabled = true; 9450 mResolveInfo.activityInfo = mResolveActivity; 9451 mResolveInfo.priority = 0; 9452 mResolveInfo.preferredOrder = 0; 9453 mResolveInfo.match = 0; 9454 mResolveComponentName = mCustomResolverComponentName; 9455 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9456 mResolveComponentName); 9457 } 9458 } 9459 9460 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9461 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9462 9463 // Set up information for ephemeral installer activity 9464 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9465 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9466 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9467 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9468 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9469 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9470 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9471 mEphemeralInstallerActivity.theme = 0; 9472 mEphemeralInstallerActivity.exported = true; 9473 mEphemeralInstallerActivity.enabled = true; 9474 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9475 mEphemeralInstallerInfo.priority = 0; 9476 mEphemeralInstallerInfo.preferredOrder = 1; 9477 mEphemeralInstallerInfo.isDefault = true; 9478 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9479 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9480 9481 if (DEBUG_EPHEMERAL) { 9482 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9483 } 9484 } 9485 9486 private static String calculateBundledApkRoot(final String codePathString) { 9487 final File codePath = new File(codePathString); 9488 final File codeRoot; 9489 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9490 codeRoot = Environment.getRootDirectory(); 9491 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9492 codeRoot = Environment.getOemDirectory(); 9493 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9494 codeRoot = Environment.getVendorDirectory(); 9495 } else { 9496 // Unrecognized code path; take its top real segment as the apk root: 9497 // e.g. /something/app/blah.apk => /something 9498 try { 9499 File f = codePath.getCanonicalFile(); 9500 File parent = f.getParentFile(); // non-null because codePath is a file 9501 File tmp; 9502 while ((tmp = parent.getParentFile()) != null) { 9503 f = parent; 9504 parent = tmp; 9505 } 9506 codeRoot = f; 9507 Slog.w(TAG, "Unrecognized code path " 9508 + codePath + " - using " + codeRoot); 9509 } catch (IOException e) { 9510 // Can't canonicalize the code path -- shenanigans? 9511 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9512 return Environment.getRootDirectory().getPath(); 9513 } 9514 } 9515 return codeRoot.getPath(); 9516 } 9517 9518 /** 9519 * Derive and set the location of native libraries for the given package, 9520 * which varies depending on where and how the package was installed. 9521 */ 9522 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 9523 final ApplicationInfo info = pkg.applicationInfo; 9524 final String codePath = pkg.codePath; 9525 final File codeFile = new File(codePath); 9526 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9527 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9528 9529 info.nativeLibraryRootDir = null; 9530 info.nativeLibraryRootRequiresIsa = false; 9531 info.nativeLibraryDir = null; 9532 info.secondaryNativeLibraryDir = null; 9533 9534 if (isApkFile(codeFile)) { 9535 // Monolithic install 9536 if (bundledApp) { 9537 // If "/system/lib64/apkname" exists, assume that is the per-package 9538 // native library directory to use; otherwise use "/system/lib/apkname". 9539 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9540 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9541 getPrimaryInstructionSet(info)); 9542 9543 // This is a bundled system app so choose the path based on the ABI. 9544 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9545 // is just the default path. 9546 final String apkName = deriveCodePathName(codePath); 9547 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9548 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9549 apkName).getAbsolutePath(); 9550 9551 if (info.secondaryCpuAbi != null) { 9552 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9553 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9554 secondaryLibDir, apkName).getAbsolutePath(); 9555 } 9556 } else if (asecApp) { 9557 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9558 .getAbsolutePath(); 9559 } else { 9560 final String apkName = deriveCodePathName(codePath); 9561 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 9562 .getAbsolutePath(); 9563 } 9564 9565 info.nativeLibraryRootRequiresIsa = false; 9566 info.nativeLibraryDir = info.nativeLibraryRootDir; 9567 } else { 9568 // Cluster install 9569 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9570 info.nativeLibraryRootRequiresIsa = true; 9571 9572 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9573 getPrimaryInstructionSet(info)).getAbsolutePath(); 9574 9575 if (info.secondaryCpuAbi != null) { 9576 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9577 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9578 } 9579 } 9580 } 9581 9582 /** 9583 * Calculate the abis and roots for a bundled app. These can uniquely 9584 * be determined from the contents of the system partition, i.e whether 9585 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9586 * of this information, and instead assume that the system was built 9587 * sensibly. 9588 */ 9589 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9590 PackageSetting pkgSetting) { 9591 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9592 9593 // If "/system/lib64/apkname" exists, assume that is the per-package 9594 // native library directory to use; otherwise use "/system/lib/apkname". 9595 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9596 setBundledAppAbi(pkg, apkRoot, apkName); 9597 // pkgSetting might be null during rescan following uninstall of updates 9598 // to a bundled app, so accommodate that possibility. The settings in 9599 // that case will be established later from the parsed package. 9600 // 9601 // If the settings aren't null, sync them up with what we've just derived. 9602 // note that apkRoot isn't stored in the package settings. 9603 if (pkgSetting != null) { 9604 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9605 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9606 } 9607 } 9608 9609 /** 9610 * Deduces the ABI of a bundled app and sets the relevant fields on the 9611 * parsed pkg object. 9612 * 9613 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9614 * under which system libraries are installed. 9615 * @param apkName the name of the installed package. 9616 */ 9617 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9618 final File codeFile = new File(pkg.codePath); 9619 9620 final boolean has64BitLibs; 9621 final boolean has32BitLibs; 9622 if (isApkFile(codeFile)) { 9623 // Monolithic install 9624 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9625 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9626 } else { 9627 // Cluster install 9628 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9629 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9630 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9631 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9632 has64BitLibs = (new File(rootDir, isa)).exists(); 9633 } else { 9634 has64BitLibs = false; 9635 } 9636 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9637 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9638 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9639 has32BitLibs = (new File(rootDir, isa)).exists(); 9640 } else { 9641 has32BitLibs = false; 9642 } 9643 } 9644 9645 if (has64BitLibs && !has32BitLibs) { 9646 // The package has 64 bit libs, but not 32 bit libs. Its primary 9647 // ABI should be 64 bit. We can safely assume here that the bundled 9648 // native libraries correspond to the most preferred ABI in the list. 9649 9650 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9651 pkg.applicationInfo.secondaryCpuAbi = null; 9652 } else if (has32BitLibs && !has64BitLibs) { 9653 // The package has 32 bit libs but not 64 bit libs. Its primary 9654 // ABI should be 32 bit. 9655 9656 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9657 pkg.applicationInfo.secondaryCpuAbi = null; 9658 } else if (has32BitLibs && has64BitLibs) { 9659 // The application has both 64 and 32 bit bundled libraries. We check 9660 // here that the app declares multiArch support, and warn if it doesn't. 9661 // 9662 // We will be lenient here and record both ABIs. The primary will be the 9663 // ABI that's higher on the list, i.e, a device that's configured to prefer 9664 // 64 bit apps will see a 64 bit primary ABI, 9665 9666 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9667 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9668 } 9669 9670 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9671 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9672 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9673 } else { 9674 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9675 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9676 } 9677 } else { 9678 pkg.applicationInfo.primaryCpuAbi = null; 9679 pkg.applicationInfo.secondaryCpuAbi = null; 9680 } 9681 } 9682 9683 private void killApplication(String pkgName, int appId, String reason) { 9684 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9685 } 9686 9687 private void killApplication(String pkgName, int appId, int userId, String reason) { 9688 // Request the ActivityManager to kill the process(only for existing packages) 9689 // so that we do not end up in a confused state while the user is still using the older 9690 // version of the application while the new one gets installed. 9691 final long token = Binder.clearCallingIdentity(); 9692 try { 9693 IActivityManager am = ActivityManager.getService(); 9694 if (am != null) { 9695 try { 9696 am.killApplication(pkgName, appId, userId, reason); 9697 } catch (RemoteException e) { 9698 } 9699 } 9700 } finally { 9701 Binder.restoreCallingIdentity(token); 9702 } 9703 } 9704 9705 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9706 // Remove the parent package setting 9707 PackageSetting ps = (PackageSetting) pkg.mExtras; 9708 if (ps != null) { 9709 removePackageLI(ps, chatty); 9710 } 9711 // Remove the child package setting 9712 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9713 for (int i = 0; i < childCount; i++) { 9714 PackageParser.Package childPkg = pkg.childPackages.get(i); 9715 ps = (PackageSetting) childPkg.mExtras; 9716 if (ps != null) { 9717 removePackageLI(ps, chatty); 9718 } 9719 } 9720 } 9721 9722 void removePackageLI(PackageSetting ps, boolean chatty) { 9723 if (DEBUG_INSTALL) { 9724 if (chatty) 9725 Log.d(TAG, "Removing package " + ps.name); 9726 } 9727 9728 // writer 9729 synchronized (mPackages) { 9730 mPackages.remove(ps.name); 9731 final PackageParser.Package pkg = ps.pkg; 9732 if (pkg != null) { 9733 cleanPackageDataStructuresLILPw(pkg, chatty); 9734 } 9735 } 9736 } 9737 9738 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9739 if (DEBUG_INSTALL) { 9740 if (chatty) 9741 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9742 } 9743 9744 // writer 9745 synchronized (mPackages) { 9746 // Remove the parent package 9747 mPackages.remove(pkg.applicationInfo.packageName); 9748 cleanPackageDataStructuresLILPw(pkg, chatty); 9749 9750 // Remove the child packages 9751 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9752 for (int i = 0; i < childCount; i++) { 9753 PackageParser.Package childPkg = pkg.childPackages.get(i); 9754 mPackages.remove(childPkg.applicationInfo.packageName); 9755 cleanPackageDataStructuresLILPw(childPkg, chatty); 9756 } 9757 } 9758 } 9759 9760 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9761 int N = pkg.providers.size(); 9762 StringBuilder r = null; 9763 int i; 9764 for (i=0; i<N; i++) { 9765 PackageParser.Provider p = pkg.providers.get(i); 9766 mProviders.removeProvider(p); 9767 if (p.info.authority == null) { 9768 9769 /* There was another ContentProvider with this authority when 9770 * this app was installed so this authority is null, 9771 * Ignore it as we don't have to unregister the provider. 9772 */ 9773 continue; 9774 } 9775 String names[] = p.info.authority.split(";"); 9776 for (int j = 0; j < names.length; j++) { 9777 if (mProvidersByAuthority.get(names[j]) == p) { 9778 mProvidersByAuthority.remove(names[j]); 9779 if (DEBUG_REMOVE) { 9780 if (chatty) 9781 Log.d(TAG, "Unregistered content provider: " + names[j] 9782 + ", className = " + p.info.name + ", isSyncable = " 9783 + p.info.isSyncable); 9784 } 9785 } 9786 } 9787 if (DEBUG_REMOVE && chatty) { 9788 if (r == null) { 9789 r = new StringBuilder(256); 9790 } else { 9791 r.append(' '); 9792 } 9793 r.append(p.info.name); 9794 } 9795 } 9796 if (r != null) { 9797 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9798 } 9799 9800 N = pkg.services.size(); 9801 r = null; 9802 for (i=0; i<N; i++) { 9803 PackageParser.Service s = pkg.services.get(i); 9804 mServices.removeService(s); 9805 if (chatty) { 9806 if (r == null) { 9807 r = new StringBuilder(256); 9808 } else { 9809 r.append(' '); 9810 } 9811 r.append(s.info.name); 9812 } 9813 } 9814 if (r != null) { 9815 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9816 } 9817 9818 N = pkg.receivers.size(); 9819 r = null; 9820 for (i=0; i<N; i++) { 9821 PackageParser.Activity a = pkg.receivers.get(i); 9822 mReceivers.removeActivity(a, "receiver"); 9823 if (DEBUG_REMOVE && chatty) { 9824 if (r == null) { 9825 r = new StringBuilder(256); 9826 } else { 9827 r.append(' '); 9828 } 9829 r.append(a.info.name); 9830 } 9831 } 9832 if (r != null) { 9833 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9834 } 9835 9836 N = pkg.activities.size(); 9837 r = null; 9838 for (i=0; i<N; i++) { 9839 PackageParser.Activity a = pkg.activities.get(i); 9840 mActivities.removeActivity(a, "activity"); 9841 if (DEBUG_REMOVE && chatty) { 9842 if (r == null) { 9843 r = new StringBuilder(256); 9844 } else { 9845 r.append(' '); 9846 } 9847 r.append(a.info.name); 9848 } 9849 } 9850 if (r != null) { 9851 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9852 } 9853 9854 N = pkg.permissions.size(); 9855 r = null; 9856 for (i=0; i<N; i++) { 9857 PackageParser.Permission p = pkg.permissions.get(i); 9858 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9859 if (bp == null) { 9860 bp = mSettings.mPermissionTrees.get(p.info.name); 9861 } 9862 if (bp != null && bp.perm == p) { 9863 bp.perm = null; 9864 if (DEBUG_REMOVE && chatty) { 9865 if (r == null) { 9866 r = new StringBuilder(256); 9867 } else { 9868 r.append(' '); 9869 } 9870 r.append(p.info.name); 9871 } 9872 } 9873 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9874 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9875 if (appOpPkgs != null) { 9876 appOpPkgs.remove(pkg.packageName); 9877 } 9878 } 9879 } 9880 if (r != null) { 9881 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9882 } 9883 9884 N = pkg.requestedPermissions.size(); 9885 r = null; 9886 for (i=0; i<N; i++) { 9887 String perm = pkg.requestedPermissions.get(i); 9888 BasePermission bp = mSettings.mPermissions.get(perm); 9889 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9890 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9891 if (appOpPkgs != null) { 9892 appOpPkgs.remove(pkg.packageName); 9893 if (appOpPkgs.isEmpty()) { 9894 mAppOpPermissionPackages.remove(perm); 9895 } 9896 } 9897 } 9898 } 9899 if (r != null) { 9900 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9901 } 9902 9903 N = pkg.instrumentation.size(); 9904 r = null; 9905 for (i=0; i<N; i++) { 9906 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9907 mInstrumentation.remove(a.getComponentName()); 9908 if (DEBUG_REMOVE && chatty) { 9909 if (r == null) { 9910 r = new StringBuilder(256); 9911 } else { 9912 r.append(' '); 9913 } 9914 r.append(a.info.name); 9915 } 9916 } 9917 if (r != null) { 9918 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9919 } 9920 9921 r = null; 9922 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9923 // Only system apps can hold shared libraries. 9924 if (pkg.libraryNames != null) { 9925 for (i=0; i<pkg.libraryNames.size(); i++) { 9926 String name = pkg.libraryNames.get(i); 9927 SharedLibraryEntry cur = mSharedLibraries.get(name); 9928 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9929 mSharedLibraries.remove(name); 9930 if (DEBUG_REMOVE && chatty) { 9931 if (r == null) { 9932 r = new StringBuilder(256); 9933 } else { 9934 r.append(' '); 9935 } 9936 r.append(name); 9937 } 9938 } 9939 } 9940 } 9941 } 9942 if (r != null) { 9943 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9944 } 9945 } 9946 9947 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9948 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9949 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9950 return true; 9951 } 9952 } 9953 return false; 9954 } 9955 9956 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9957 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9958 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9959 9960 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9961 // Update the parent permissions 9962 updatePermissionsLPw(pkg.packageName, pkg, flags); 9963 // Update the child permissions 9964 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9965 for (int i = 0; i < childCount; i++) { 9966 PackageParser.Package childPkg = pkg.childPackages.get(i); 9967 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9968 } 9969 } 9970 9971 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9972 int flags) { 9973 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9974 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9975 } 9976 9977 private void updatePermissionsLPw(String changingPkg, 9978 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9979 // Make sure there are no dangling permission trees. 9980 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9981 while (it.hasNext()) { 9982 final BasePermission bp = it.next(); 9983 if (bp.packageSetting == null) { 9984 // We may not yet have parsed the package, so just see if 9985 // we still know about its settings. 9986 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9987 } 9988 if (bp.packageSetting == null) { 9989 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9990 + " from package " + bp.sourcePackage); 9991 it.remove(); 9992 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9993 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9994 Slog.i(TAG, "Removing old permission tree: " + bp.name 9995 + " from package " + bp.sourcePackage); 9996 flags |= UPDATE_PERMISSIONS_ALL; 9997 it.remove(); 9998 } 9999 } 10000 } 10001 10002 // Make sure all dynamic permissions have been assigned to a package, 10003 // and make sure there are no dangling permissions. 10004 it = mSettings.mPermissions.values().iterator(); 10005 while (it.hasNext()) { 10006 final BasePermission bp = it.next(); 10007 if (bp.type == BasePermission.TYPE_DYNAMIC) { 10008 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 10009 + bp.name + " pkg=" + bp.sourcePackage 10010 + " info=" + bp.pendingInfo); 10011 if (bp.packageSetting == null && bp.pendingInfo != null) { 10012 final BasePermission tree = findPermissionTreeLP(bp.name); 10013 if (tree != null && tree.perm != null) { 10014 bp.packageSetting = tree.packageSetting; 10015 bp.perm = new PackageParser.Permission(tree.perm.owner, 10016 new PermissionInfo(bp.pendingInfo)); 10017 bp.perm.info.packageName = tree.perm.info.packageName; 10018 bp.perm.info.name = bp.name; 10019 bp.uid = tree.uid; 10020 } 10021 } 10022 } 10023 if (bp.packageSetting == null) { 10024 // We may not yet have parsed the package, so just see if 10025 // we still know about its settings. 10026 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10027 } 10028 if (bp.packageSetting == null) { 10029 Slog.w(TAG, "Removing dangling permission: " + bp.name 10030 + " from package " + bp.sourcePackage); 10031 it.remove(); 10032 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10033 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10034 Slog.i(TAG, "Removing old permission: " + bp.name 10035 + " from package " + bp.sourcePackage); 10036 flags |= UPDATE_PERMISSIONS_ALL; 10037 it.remove(); 10038 } 10039 } 10040 } 10041 10042 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 10043 // Now update the permissions for all packages, in particular 10044 // replace the granted permissions of the system packages. 10045 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 10046 for (PackageParser.Package pkg : mPackages.values()) { 10047 if (pkg != pkgInfo) { 10048 // Only replace for packages on requested volume 10049 final String volumeUuid = getVolumeUuidForPackage(pkg); 10050 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 10051 && Objects.equals(replaceVolumeUuid, volumeUuid); 10052 grantPermissionsLPw(pkg, replace, changingPkg); 10053 } 10054 } 10055 } 10056 10057 if (pkgInfo != null) { 10058 // Only replace for packages on requested volume 10059 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 10060 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 10061 && Objects.equals(replaceVolumeUuid, volumeUuid); 10062 grantPermissionsLPw(pkgInfo, replace, changingPkg); 10063 } 10064 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10065 } 10066 10067 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 10068 String packageOfInterest) { 10069 // IMPORTANT: There are two types of permissions: install and runtime. 10070 // Install time permissions are granted when the app is installed to 10071 // all device users and users added in the future. Runtime permissions 10072 // are granted at runtime explicitly to specific users. Normal and signature 10073 // protected permissions are install time permissions. Dangerous permissions 10074 // are install permissions if the app's target SDK is Lollipop MR1 or older, 10075 // otherwise they are runtime permissions. This function does not manage 10076 // runtime permissions except for the case an app targeting Lollipop MR1 10077 // being upgraded to target a newer SDK, in which case dangerous permissions 10078 // are transformed from install time to runtime ones. 10079 10080 final PackageSetting ps = (PackageSetting) pkg.mExtras; 10081 if (ps == null) { 10082 return; 10083 } 10084 10085 PermissionsState permissionsState = ps.getPermissionsState(); 10086 PermissionsState origPermissions = permissionsState; 10087 10088 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10089 10090 boolean runtimePermissionsRevoked = false; 10091 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10092 10093 boolean changedInstallPermission = false; 10094 10095 if (replace) { 10096 ps.installPermissionsFixed = false; 10097 if (!ps.isSharedUser()) { 10098 origPermissions = new PermissionsState(permissionsState); 10099 permissionsState.reset(); 10100 } else { 10101 // We need to know only about runtime permission changes since the 10102 // calling code always writes the install permissions state but 10103 // the runtime ones are written only if changed. The only cases of 10104 // changed runtime permissions here are promotion of an install to 10105 // runtime and revocation of a runtime from a shared user. 10106 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10107 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10108 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10109 runtimePermissionsRevoked = true; 10110 } 10111 } 10112 } 10113 10114 permissionsState.setGlobalGids(mGlobalGids); 10115 10116 final int N = pkg.requestedPermissions.size(); 10117 for (int i=0; i<N; i++) { 10118 final String name = pkg.requestedPermissions.get(i); 10119 final BasePermission bp = mSettings.mPermissions.get(name); 10120 10121 if (DEBUG_INSTALL) { 10122 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10123 } 10124 10125 if (bp == null || bp.packageSetting == null) { 10126 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10127 Slog.w(TAG, "Unknown permission " + name 10128 + " in package " + pkg.packageName); 10129 } 10130 continue; 10131 } 10132 10133 10134 // Limit ephemeral apps to ephemeral allowed permissions. 10135 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 10136 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 10137 + pkg.packageName); 10138 continue; 10139 } 10140 10141 final String perm = bp.name; 10142 boolean allowedSig = false; 10143 int grant = GRANT_DENIED; 10144 10145 // Keep track of app op permissions. 10146 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10147 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10148 if (pkgs == null) { 10149 pkgs = new ArraySet<>(); 10150 mAppOpPermissionPackages.put(bp.name, pkgs); 10151 } 10152 pkgs.add(pkg.packageName); 10153 } 10154 10155 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10156 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10157 >= Build.VERSION_CODES.M; 10158 switch (level) { 10159 case PermissionInfo.PROTECTION_NORMAL: { 10160 // For all apps normal permissions are install time ones. 10161 grant = GRANT_INSTALL; 10162 } break; 10163 10164 case PermissionInfo.PROTECTION_DANGEROUS: { 10165 // If a permission review is required for legacy apps we represent 10166 // their permissions as always granted runtime ones since we need 10167 // to keep the review required permission flag per user while an 10168 // install permission's state is shared across all users. 10169 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 10170 // For legacy apps dangerous permissions are install time ones. 10171 grant = GRANT_INSTALL; 10172 } else if (origPermissions.hasInstallPermission(bp.name)) { 10173 // For legacy apps that became modern, install becomes runtime. 10174 grant = GRANT_UPGRADE; 10175 } else if (mPromoteSystemApps 10176 && isSystemApp(ps) 10177 && mExistingSystemPackages.contains(ps.name)) { 10178 // For legacy system apps, install becomes runtime. 10179 // We cannot check hasInstallPermission() for system apps since those 10180 // permissions were granted implicitly and not persisted pre-M. 10181 grant = GRANT_UPGRADE; 10182 } else { 10183 // For modern apps keep runtime permissions unchanged. 10184 grant = GRANT_RUNTIME; 10185 } 10186 } break; 10187 10188 case PermissionInfo.PROTECTION_SIGNATURE: { 10189 // For all apps signature permissions are install time ones. 10190 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10191 if (allowedSig) { 10192 grant = GRANT_INSTALL; 10193 } 10194 } break; 10195 } 10196 10197 if (DEBUG_INSTALL) { 10198 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10199 } 10200 10201 if (grant != GRANT_DENIED) { 10202 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10203 // If this is an existing, non-system package, then 10204 // we can't add any new permissions to it. 10205 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10206 // Except... if this is a permission that was added 10207 // to the platform (note: need to only do this when 10208 // updating the platform). 10209 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10210 grant = GRANT_DENIED; 10211 } 10212 } 10213 } 10214 10215 switch (grant) { 10216 case GRANT_INSTALL: { 10217 // Revoke this as runtime permission to handle the case of 10218 // a runtime permission being downgraded to an install one. 10219 // Also in permission review mode we keep dangerous permissions 10220 // for legacy apps 10221 for (int userId : UserManagerService.getInstance().getUserIds()) { 10222 if (origPermissions.getRuntimePermissionState( 10223 bp.name, userId) != null) { 10224 // Revoke the runtime permission and clear the flags. 10225 origPermissions.revokeRuntimePermission(bp, userId); 10226 origPermissions.updatePermissionFlags(bp, userId, 10227 PackageManager.MASK_PERMISSION_FLAGS, 0); 10228 // If we revoked a permission permission, we have to write. 10229 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10230 changedRuntimePermissionUserIds, userId); 10231 } 10232 } 10233 // Grant an install permission. 10234 if (permissionsState.grantInstallPermission(bp) != 10235 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10236 changedInstallPermission = true; 10237 } 10238 } break; 10239 10240 case GRANT_RUNTIME: { 10241 // Grant previously granted runtime permissions. 10242 for (int userId : UserManagerService.getInstance().getUserIds()) { 10243 PermissionState permissionState = origPermissions 10244 .getRuntimePermissionState(bp.name, userId); 10245 int flags = permissionState != null 10246 ? permissionState.getFlags() : 0; 10247 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10248 if (permissionsState.grantRuntimePermission(bp, userId) == 10249 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10250 // If we cannot put the permission as it was, we have to write. 10251 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10252 changedRuntimePermissionUserIds, userId); 10253 } 10254 // If the app supports runtime permissions no need for a review. 10255 if (mPermissionReviewRequired 10256 && appSupportsRuntimePermissions 10257 && (flags & PackageManager 10258 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10259 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10260 // Since we changed the flags, we have to write. 10261 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10262 changedRuntimePermissionUserIds, userId); 10263 } 10264 } else if (mPermissionReviewRequired 10265 && !appSupportsRuntimePermissions) { 10266 // For legacy apps that need a permission review, every new 10267 // runtime permission is granted but it is pending a review. 10268 // We also need to review only platform defined runtime 10269 // permissions as these are the only ones the platform knows 10270 // how to disable the API to simulate revocation as legacy 10271 // apps don't expect to run with revoked permissions. 10272 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10273 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10274 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10275 // We changed the flags, hence have to write. 10276 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10277 changedRuntimePermissionUserIds, userId); 10278 } 10279 } 10280 if (permissionsState.grantRuntimePermission(bp, userId) 10281 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10282 // We changed the permission, hence have to write. 10283 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10284 changedRuntimePermissionUserIds, userId); 10285 } 10286 } 10287 // Propagate the permission flags. 10288 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10289 } 10290 } break; 10291 10292 case GRANT_UPGRADE: { 10293 // Grant runtime permissions for a previously held install permission. 10294 PermissionState permissionState = origPermissions 10295 .getInstallPermissionState(bp.name); 10296 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10297 10298 if (origPermissions.revokeInstallPermission(bp) 10299 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10300 // We will be transferring the permission flags, so clear them. 10301 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10302 PackageManager.MASK_PERMISSION_FLAGS, 0); 10303 changedInstallPermission = true; 10304 } 10305 10306 // If the permission is not to be promoted to runtime we ignore it and 10307 // also its other flags as they are not applicable to install permissions. 10308 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10309 for (int userId : currentUserIds) { 10310 if (permissionsState.grantRuntimePermission(bp, userId) != 10311 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10312 // Transfer the permission flags. 10313 permissionsState.updatePermissionFlags(bp, userId, 10314 flags, flags); 10315 // If we granted the permission, we have to write. 10316 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10317 changedRuntimePermissionUserIds, userId); 10318 } 10319 } 10320 } 10321 } break; 10322 10323 default: { 10324 if (packageOfInterest == null 10325 || packageOfInterest.equals(pkg.packageName)) { 10326 Slog.w(TAG, "Not granting permission " + perm 10327 + " to package " + pkg.packageName 10328 + " because it was previously installed without"); 10329 } 10330 } break; 10331 } 10332 } else { 10333 if (permissionsState.revokeInstallPermission(bp) != 10334 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10335 // Also drop the permission flags. 10336 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10337 PackageManager.MASK_PERMISSION_FLAGS, 0); 10338 changedInstallPermission = true; 10339 Slog.i(TAG, "Un-granting permission " + perm 10340 + " from package " + pkg.packageName 10341 + " (protectionLevel=" + bp.protectionLevel 10342 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10343 + ")"); 10344 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10345 // Don't print warning for app op permissions, since it is fine for them 10346 // not to be granted, there is a UI for the user to decide. 10347 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10348 Slog.w(TAG, "Not granting permission " + perm 10349 + " to package " + pkg.packageName 10350 + " (protectionLevel=" + bp.protectionLevel 10351 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10352 + ")"); 10353 } 10354 } 10355 } 10356 } 10357 10358 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10359 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10360 // This is the first that we have heard about this package, so the 10361 // permissions we have now selected are fixed until explicitly 10362 // changed. 10363 ps.installPermissionsFixed = true; 10364 } 10365 10366 // Persist the runtime permissions state for users with changes. If permissions 10367 // were revoked because no app in the shared user declares them we have to 10368 // write synchronously to avoid losing runtime permissions state. 10369 for (int userId : changedRuntimePermissionUserIds) { 10370 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10371 } 10372 } 10373 10374 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10375 boolean allowed = false; 10376 final int NP = PackageParser.NEW_PERMISSIONS.length; 10377 for (int ip=0; ip<NP; ip++) { 10378 final PackageParser.NewPermissionInfo npi 10379 = PackageParser.NEW_PERMISSIONS[ip]; 10380 if (npi.name.equals(perm) 10381 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10382 allowed = true; 10383 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10384 + pkg.packageName); 10385 break; 10386 } 10387 } 10388 return allowed; 10389 } 10390 10391 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10392 BasePermission bp, PermissionsState origPermissions) { 10393 boolean privilegedPermission = (bp.protectionLevel 10394 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 10395 boolean controlPrivappPermissions = RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS; 10396 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 10397 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 10398 if (controlPrivappPermissions && privilegedPermission && pkg.isPrivilegedApp() 10399 && !platformPackage && platformPermission) { 10400 ArraySet<String> wlPermissions = SystemConfig.getInstance() 10401 .getPrivAppPermissions(pkg.packageName); 10402 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 10403 if (!whitelisted) { 10404 // Log for now. TODO Enforce permissions 10405 Slog.w(TAG, "Privileged permission " + perm + " for package " 10406 + pkg.packageName + " - not in privapp-permissions whitelist"); 10407 } 10408 } 10409 boolean allowed = (compareSignatures( 10410 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10411 == PackageManager.SIGNATURE_MATCH) 10412 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10413 == PackageManager.SIGNATURE_MATCH); 10414 if (!allowed && privilegedPermission) { 10415 if (isSystemApp(pkg)) { 10416 // For updated system applications, a system permission 10417 // is granted only if it had been defined by the original application. 10418 if (pkg.isUpdatedSystemApp()) { 10419 final PackageSetting sysPs = mSettings 10420 .getDisabledSystemPkgLPr(pkg.packageName); 10421 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10422 // If the original was granted this permission, we take 10423 // that grant decision as read and propagate it to the 10424 // update. 10425 if (sysPs.isPrivileged()) { 10426 allowed = true; 10427 } 10428 } else { 10429 // The system apk may have been updated with an older 10430 // version of the one on the data partition, but which 10431 // granted a new system permission that it didn't have 10432 // before. In this case we do want to allow the app to 10433 // now get the new permission if the ancestral apk is 10434 // privileged to get it. 10435 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10436 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10437 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10438 allowed = true; 10439 break; 10440 } 10441 } 10442 } 10443 // Also if a privileged parent package on the system image or any of 10444 // its children requested a privileged permission, the updated child 10445 // packages can also get the permission. 10446 if (pkg.parentPackage != null) { 10447 final PackageSetting disabledSysParentPs = mSettings 10448 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10449 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10450 && disabledSysParentPs.isPrivileged()) { 10451 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10452 allowed = true; 10453 } else if (disabledSysParentPs.pkg.childPackages != null) { 10454 final int count = disabledSysParentPs.pkg.childPackages.size(); 10455 for (int i = 0; i < count; i++) { 10456 PackageParser.Package disabledSysChildPkg = 10457 disabledSysParentPs.pkg.childPackages.get(i); 10458 if (isPackageRequestingPermission(disabledSysChildPkg, 10459 perm)) { 10460 allowed = true; 10461 break; 10462 } 10463 } 10464 } 10465 } 10466 } 10467 } 10468 } else { 10469 allowed = isPrivilegedApp(pkg); 10470 } 10471 } 10472 } 10473 if (!allowed) { 10474 if (!allowed && (bp.protectionLevel 10475 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10476 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10477 // If this was a previously normal/dangerous permission that got moved 10478 // to a system permission as part of the runtime permission redesign, then 10479 // we still want to blindly grant it to old apps. 10480 allowed = true; 10481 } 10482 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10483 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10484 // If this permission is to be granted to the system installer and 10485 // this app is an installer, then it gets the permission. 10486 allowed = true; 10487 } 10488 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10489 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10490 // If this permission is to be granted to the system verifier and 10491 // this app is a verifier, then it gets the permission. 10492 allowed = true; 10493 } 10494 if (!allowed && (bp.protectionLevel 10495 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10496 && isSystemApp(pkg)) { 10497 // Any pre-installed system app is allowed to get this permission. 10498 allowed = true; 10499 } 10500 if (!allowed && (bp.protectionLevel 10501 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10502 // For development permissions, a development permission 10503 // is granted only if it was already granted. 10504 allowed = origPermissions.hasInstallPermission(perm); 10505 } 10506 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10507 && pkg.packageName.equals(mSetupWizardPackage)) { 10508 // If this permission is to be granted to the system setup wizard and 10509 // this app is a setup wizard, then it gets the permission. 10510 allowed = true; 10511 } 10512 } 10513 return allowed; 10514 } 10515 10516 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10517 final int permCount = pkg.requestedPermissions.size(); 10518 for (int j = 0; j < permCount; j++) { 10519 String requestedPermission = pkg.requestedPermissions.get(j); 10520 if (permission.equals(requestedPermission)) { 10521 return true; 10522 } 10523 } 10524 return false; 10525 } 10526 10527 final class ActivityIntentResolver 10528 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10529 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10530 boolean defaultOnly, int userId) { 10531 if (!sUserManager.exists(userId)) return null; 10532 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10533 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10534 } 10535 10536 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10537 int userId) { 10538 if (!sUserManager.exists(userId)) return null; 10539 mFlags = flags; 10540 return super.queryIntent(intent, resolvedType, 10541 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10542 } 10543 10544 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10545 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10546 if (!sUserManager.exists(userId)) return null; 10547 if (packageActivities == null) { 10548 return null; 10549 } 10550 mFlags = flags; 10551 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10552 final int N = packageActivities.size(); 10553 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10554 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10555 10556 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10557 for (int i = 0; i < N; ++i) { 10558 intentFilters = packageActivities.get(i).intents; 10559 if (intentFilters != null && intentFilters.size() > 0) { 10560 PackageParser.ActivityIntentInfo[] array = 10561 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10562 intentFilters.toArray(array); 10563 listCut.add(array); 10564 } 10565 } 10566 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10567 } 10568 10569 /** 10570 * Finds a privileged activity that matches the specified activity names. 10571 */ 10572 private PackageParser.Activity findMatchingActivity( 10573 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10574 for (PackageParser.Activity sysActivity : activityList) { 10575 if (sysActivity.info.name.equals(activityInfo.name)) { 10576 return sysActivity; 10577 } 10578 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10579 return sysActivity; 10580 } 10581 if (sysActivity.info.targetActivity != null) { 10582 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10583 return sysActivity; 10584 } 10585 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10586 return sysActivity; 10587 } 10588 } 10589 } 10590 return null; 10591 } 10592 10593 public class IterGenerator<E> { 10594 public Iterator<E> generate(ActivityIntentInfo info) { 10595 return null; 10596 } 10597 } 10598 10599 public class ActionIterGenerator extends IterGenerator<String> { 10600 @Override 10601 public Iterator<String> generate(ActivityIntentInfo info) { 10602 return info.actionsIterator(); 10603 } 10604 } 10605 10606 public class CategoriesIterGenerator extends IterGenerator<String> { 10607 @Override 10608 public Iterator<String> generate(ActivityIntentInfo info) { 10609 return info.categoriesIterator(); 10610 } 10611 } 10612 10613 public class SchemesIterGenerator extends IterGenerator<String> { 10614 @Override 10615 public Iterator<String> generate(ActivityIntentInfo info) { 10616 return info.schemesIterator(); 10617 } 10618 } 10619 10620 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10621 @Override 10622 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10623 return info.authoritiesIterator(); 10624 } 10625 } 10626 10627 /** 10628 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10629 * MODIFIED. Do not pass in a list that should not be changed. 10630 */ 10631 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10632 IterGenerator<T> generator, Iterator<T> searchIterator) { 10633 // loop through the set of actions; every one must be found in the intent filter 10634 while (searchIterator.hasNext()) { 10635 // we must have at least one filter in the list to consider a match 10636 if (intentList.size() == 0) { 10637 break; 10638 } 10639 10640 final T searchAction = searchIterator.next(); 10641 10642 // loop through the set of intent filters 10643 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10644 while (intentIter.hasNext()) { 10645 final ActivityIntentInfo intentInfo = intentIter.next(); 10646 boolean selectionFound = false; 10647 10648 // loop through the intent filter's selection criteria; at least one 10649 // of them must match the searched criteria 10650 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10651 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10652 final T intentSelection = intentSelectionIter.next(); 10653 if (intentSelection != null && intentSelection.equals(searchAction)) { 10654 selectionFound = true; 10655 break; 10656 } 10657 } 10658 10659 // the selection criteria wasn't found in this filter's set; this filter 10660 // is not a potential match 10661 if (!selectionFound) { 10662 intentIter.remove(); 10663 } 10664 } 10665 } 10666 } 10667 10668 private boolean isProtectedAction(ActivityIntentInfo filter) { 10669 final Iterator<String> actionsIter = filter.actionsIterator(); 10670 while (actionsIter != null && actionsIter.hasNext()) { 10671 final String filterAction = actionsIter.next(); 10672 if (PROTECTED_ACTIONS.contains(filterAction)) { 10673 return true; 10674 } 10675 } 10676 return false; 10677 } 10678 10679 /** 10680 * Adjusts the priority of the given intent filter according to policy. 10681 * <p> 10682 * <ul> 10683 * <li>The priority for non privileged applications is capped to '0'</li> 10684 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10685 * <li>The priority for unbundled updates to privileged applications is capped to the 10686 * priority defined on the system partition</li> 10687 * </ul> 10688 * <p> 10689 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10690 * allowed to obtain any priority on any action. 10691 */ 10692 private void adjustPriority( 10693 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10694 // nothing to do; priority is fine as-is 10695 if (intent.getPriority() <= 0) { 10696 return; 10697 } 10698 10699 final ActivityInfo activityInfo = intent.activity.info; 10700 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10701 10702 final boolean privilegedApp = 10703 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10704 if (!privilegedApp) { 10705 // non-privileged applications can never define a priority >0 10706 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10707 + " package: " + applicationInfo.packageName 10708 + " activity: " + intent.activity.className 10709 + " origPrio: " + intent.getPriority()); 10710 intent.setPriority(0); 10711 return; 10712 } 10713 10714 if (systemActivities == null) { 10715 // the system package is not disabled; we're parsing the system partition 10716 if (isProtectedAction(intent)) { 10717 if (mDeferProtectedFilters) { 10718 // We can't deal with these just yet. No component should ever obtain a 10719 // >0 priority for a protected actions, with ONE exception -- the setup 10720 // wizard. The setup wizard, however, cannot be known until we're able to 10721 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10722 // until all intent filters have been processed. Chicken, meet egg. 10723 // Let the filter temporarily have a high priority and rectify the 10724 // priorities after all system packages have been scanned. 10725 mProtectedFilters.add(intent); 10726 if (DEBUG_FILTERS) { 10727 Slog.i(TAG, "Protected action; save for later;" 10728 + " package: " + applicationInfo.packageName 10729 + " activity: " + intent.activity.className 10730 + " origPrio: " + intent.getPriority()); 10731 } 10732 return; 10733 } else { 10734 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10735 Slog.i(TAG, "No setup wizard;" 10736 + " All protected intents capped to priority 0"); 10737 } 10738 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10739 if (DEBUG_FILTERS) { 10740 Slog.i(TAG, "Found setup wizard;" 10741 + " allow priority " + intent.getPriority() + ";" 10742 + " package: " + intent.activity.info.packageName 10743 + " activity: " + intent.activity.className 10744 + " priority: " + intent.getPriority()); 10745 } 10746 // setup wizard gets whatever it wants 10747 return; 10748 } 10749 Slog.w(TAG, "Protected action; cap priority to 0;" 10750 + " package: " + intent.activity.info.packageName 10751 + " activity: " + intent.activity.className 10752 + " origPrio: " + intent.getPriority()); 10753 intent.setPriority(0); 10754 return; 10755 } 10756 } 10757 // privileged apps on the system image get whatever priority they request 10758 return; 10759 } 10760 10761 // privileged app unbundled update ... try to find the same activity 10762 final PackageParser.Activity foundActivity = 10763 findMatchingActivity(systemActivities, activityInfo); 10764 if (foundActivity == null) { 10765 // this is a new activity; it cannot obtain >0 priority 10766 if (DEBUG_FILTERS) { 10767 Slog.i(TAG, "New activity; cap priority to 0;" 10768 + " package: " + applicationInfo.packageName 10769 + " activity: " + intent.activity.className 10770 + " origPrio: " + intent.getPriority()); 10771 } 10772 intent.setPriority(0); 10773 return; 10774 } 10775 10776 // found activity, now check for filter equivalence 10777 10778 // a shallow copy is enough; we modify the list, not its contents 10779 final List<ActivityIntentInfo> intentListCopy = 10780 new ArrayList<>(foundActivity.intents); 10781 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10782 10783 // find matching action subsets 10784 final Iterator<String> actionsIterator = intent.actionsIterator(); 10785 if (actionsIterator != null) { 10786 getIntentListSubset( 10787 intentListCopy, new ActionIterGenerator(), actionsIterator); 10788 if (intentListCopy.size() == 0) { 10789 // no more intents to match; we're not equivalent 10790 if (DEBUG_FILTERS) { 10791 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10792 + " package: " + applicationInfo.packageName 10793 + " activity: " + intent.activity.className 10794 + " origPrio: " + intent.getPriority()); 10795 } 10796 intent.setPriority(0); 10797 return; 10798 } 10799 } 10800 10801 // find matching category subsets 10802 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10803 if (categoriesIterator != null) { 10804 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10805 categoriesIterator); 10806 if (intentListCopy.size() == 0) { 10807 // no more intents to match; we're not equivalent 10808 if (DEBUG_FILTERS) { 10809 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10810 + " package: " + applicationInfo.packageName 10811 + " activity: " + intent.activity.className 10812 + " origPrio: " + intent.getPriority()); 10813 } 10814 intent.setPriority(0); 10815 return; 10816 } 10817 } 10818 10819 // find matching schemes subsets 10820 final Iterator<String> schemesIterator = intent.schemesIterator(); 10821 if (schemesIterator != null) { 10822 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10823 schemesIterator); 10824 if (intentListCopy.size() == 0) { 10825 // no more intents to match; we're not equivalent 10826 if (DEBUG_FILTERS) { 10827 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10828 + " package: " + applicationInfo.packageName 10829 + " activity: " + intent.activity.className 10830 + " origPrio: " + intent.getPriority()); 10831 } 10832 intent.setPriority(0); 10833 return; 10834 } 10835 } 10836 10837 // find matching authorities subsets 10838 final Iterator<IntentFilter.AuthorityEntry> 10839 authoritiesIterator = intent.authoritiesIterator(); 10840 if (authoritiesIterator != null) { 10841 getIntentListSubset(intentListCopy, 10842 new AuthoritiesIterGenerator(), 10843 authoritiesIterator); 10844 if (intentListCopy.size() == 0) { 10845 // no more intents to match; we're not equivalent 10846 if (DEBUG_FILTERS) { 10847 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10848 + " package: " + applicationInfo.packageName 10849 + " activity: " + intent.activity.className 10850 + " origPrio: " + intent.getPriority()); 10851 } 10852 intent.setPriority(0); 10853 return; 10854 } 10855 } 10856 10857 // we found matching filter(s); app gets the max priority of all intents 10858 int cappedPriority = 0; 10859 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10860 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10861 } 10862 if (intent.getPriority() > cappedPriority) { 10863 if (DEBUG_FILTERS) { 10864 Slog.i(TAG, "Found matching filter(s);" 10865 + " cap priority to " + cappedPriority + ";" 10866 + " package: " + applicationInfo.packageName 10867 + " activity: " + intent.activity.className 10868 + " origPrio: " + intent.getPriority()); 10869 } 10870 intent.setPriority(cappedPriority); 10871 return; 10872 } 10873 // all this for nothing; the requested priority was <= what was on the system 10874 } 10875 10876 public final void addActivity(PackageParser.Activity a, String type) { 10877 mActivities.put(a.getComponentName(), a); 10878 if (DEBUG_SHOW_INFO) 10879 Log.v( 10880 TAG, " " + type + " " + 10881 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10882 if (DEBUG_SHOW_INFO) 10883 Log.v(TAG, " Class=" + a.info.name); 10884 final int NI = a.intents.size(); 10885 for (int j=0; j<NI; j++) { 10886 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10887 if ("activity".equals(type)) { 10888 final PackageSetting ps = 10889 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10890 final List<PackageParser.Activity> systemActivities = 10891 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10892 adjustPriority(systemActivities, intent); 10893 } 10894 if (DEBUG_SHOW_INFO) { 10895 Log.v(TAG, " IntentFilter:"); 10896 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10897 } 10898 if (!intent.debugCheck()) { 10899 Log.w(TAG, "==> For Activity " + a.info.name); 10900 } 10901 addFilter(intent); 10902 } 10903 } 10904 10905 public final void removeActivity(PackageParser.Activity a, String type) { 10906 mActivities.remove(a.getComponentName()); 10907 if (DEBUG_SHOW_INFO) { 10908 Log.v(TAG, " " + type + " " 10909 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10910 : a.info.name) + ":"); 10911 Log.v(TAG, " Class=" + a.info.name); 10912 } 10913 final int NI = a.intents.size(); 10914 for (int j=0; j<NI; j++) { 10915 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10916 if (DEBUG_SHOW_INFO) { 10917 Log.v(TAG, " IntentFilter:"); 10918 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10919 } 10920 removeFilter(intent); 10921 } 10922 } 10923 10924 @Override 10925 protected boolean allowFilterResult( 10926 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10927 ActivityInfo filterAi = filter.activity.info; 10928 for (int i=dest.size()-1; i>=0; i--) { 10929 ActivityInfo destAi = dest.get(i).activityInfo; 10930 if (destAi.name == filterAi.name 10931 && destAi.packageName == filterAi.packageName) { 10932 return false; 10933 } 10934 } 10935 return true; 10936 } 10937 10938 @Override 10939 protected ActivityIntentInfo[] newArray(int size) { 10940 return new ActivityIntentInfo[size]; 10941 } 10942 10943 @Override 10944 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10945 if (!sUserManager.exists(userId)) return true; 10946 PackageParser.Package p = filter.activity.owner; 10947 if (p != null) { 10948 PackageSetting ps = (PackageSetting)p.mExtras; 10949 if (ps != null) { 10950 // System apps are never considered stopped for purposes of 10951 // filtering, because there may be no way for the user to 10952 // actually re-launch them. 10953 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10954 && ps.getStopped(userId); 10955 } 10956 } 10957 return false; 10958 } 10959 10960 @Override 10961 protected boolean isPackageForFilter(String packageName, 10962 PackageParser.ActivityIntentInfo info) { 10963 return packageName.equals(info.activity.owner.packageName); 10964 } 10965 10966 @Override 10967 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10968 int match, int userId) { 10969 if (!sUserManager.exists(userId)) return null; 10970 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10971 return null; 10972 } 10973 final PackageParser.Activity activity = info.activity; 10974 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10975 if (ps == null) { 10976 return null; 10977 } 10978 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10979 ps.readUserState(userId), userId); 10980 if (ai == null) { 10981 return null; 10982 } 10983 final ResolveInfo res = new ResolveInfo(); 10984 res.activityInfo = ai; 10985 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10986 res.filter = info; 10987 } 10988 if (info != null) { 10989 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10990 } 10991 res.priority = info.getPriority(); 10992 res.preferredOrder = activity.owner.mPreferredOrder; 10993 //System.out.println("Result: " + res.activityInfo.className + 10994 // " = " + res.priority); 10995 res.match = match; 10996 res.isDefault = info.hasDefault; 10997 res.labelRes = info.labelRes; 10998 res.nonLocalizedLabel = info.nonLocalizedLabel; 10999 if (userNeedsBadging(userId)) { 11000 res.noResourceId = true; 11001 } else { 11002 res.icon = info.icon; 11003 } 11004 res.iconResourceId = info.icon; 11005 res.system = res.activityInfo.applicationInfo.isSystemApp(); 11006 return res; 11007 } 11008 11009 @Override 11010 protected void sortResults(List<ResolveInfo> results) { 11011 Collections.sort(results, mResolvePrioritySorter); 11012 } 11013 11014 @Override 11015 protected void dumpFilter(PrintWriter out, String prefix, 11016 PackageParser.ActivityIntentInfo filter) { 11017 out.print(prefix); out.print( 11018 Integer.toHexString(System.identityHashCode(filter.activity))); 11019 out.print(' '); 11020 filter.activity.printComponentShortName(out); 11021 out.print(" filter "); 11022 out.println(Integer.toHexString(System.identityHashCode(filter))); 11023 } 11024 11025 @Override 11026 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 11027 return filter.activity; 11028 } 11029 11030 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11031 PackageParser.Activity activity = (PackageParser.Activity)label; 11032 out.print(prefix); out.print( 11033 Integer.toHexString(System.identityHashCode(activity))); 11034 out.print(' '); 11035 activity.printComponentShortName(out); 11036 if (count > 1) { 11037 out.print(" ("); out.print(count); out.print(" filters)"); 11038 } 11039 out.println(); 11040 } 11041 11042 // Keys are String (activity class name), values are Activity. 11043 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 11044 = new ArrayMap<ComponentName, PackageParser.Activity>(); 11045 private int mFlags; 11046 } 11047 11048 private final class ServiceIntentResolver 11049 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 11050 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11051 boolean defaultOnly, int userId) { 11052 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11053 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11054 } 11055 11056 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11057 int userId) { 11058 if (!sUserManager.exists(userId)) return null; 11059 mFlags = flags; 11060 return super.queryIntent(intent, resolvedType, 11061 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11062 } 11063 11064 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11065 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 11066 if (!sUserManager.exists(userId)) return null; 11067 if (packageServices == null) { 11068 return null; 11069 } 11070 mFlags = flags; 11071 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 11072 final int N = packageServices.size(); 11073 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 11074 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 11075 11076 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 11077 for (int i = 0; i < N; ++i) { 11078 intentFilters = packageServices.get(i).intents; 11079 if (intentFilters != null && intentFilters.size() > 0) { 11080 PackageParser.ServiceIntentInfo[] array = 11081 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 11082 intentFilters.toArray(array); 11083 listCut.add(array); 11084 } 11085 } 11086 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11087 } 11088 11089 public final void addService(PackageParser.Service s) { 11090 mServices.put(s.getComponentName(), s); 11091 if (DEBUG_SHOW_INFO) { 11092 Log.v(TAG, " " 11093 + (s.info.nonLocalizedLabel != null 11094 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11095 Log.v(TAG, " Class=" + s.info.name); 11096 } 11097 final int NI = s.intents.size(); 11098 int j; 11099 for (j=0; j<NI; j++) { 11100 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11101 if (DEBUG_SHOW_INFO) { 11102 Log.v(TAG, " IntentFilter:"); 11103 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11104 } 11105 if (!intent.debugCheck()) { 11106 Log.w(TAG, "==> For Service " + s.info.name); 11107 } 11108 addFilter(intent); 11109 } 11110 } 11111 11112 public final void removeService(PackageParser.Service s) { 11113 mServices.remove(s.getComponentName()); 11114 if (DEBUG_SHOW_INFO) { 11115 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11116 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11117 Log.v(TAG, " Class=" + s.info.name); 11118 } 11119 final int NI = s.intents.size(); 11120 int j; 11121 for (j=0; j<NI; j++) { 11122 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11123 if (DEBUG_SHOW_INFO) { 11124 Log.v(TAG, " IntentFilter:"); 11125 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11126 } 11127 removeFilter(intent); 11128 } 11129 } 11130 11131 @Override 11132 protected boolean allowFilterResult( 11133 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11134 ServiceInfo filterSi = filter.service.info; 11135 for (int i=dest.size()-1; i>=0; i--) { 11136 ServiceInfo destAi = dest.get(i).serviceInfo; 11137 if (destAi.name == filterSi.name 11138 && destAi.packageName == filterSi.packageName) { 11139 return false; 11140 } 11141 } 11142 return true; 11143 } 11144 11145 @Override 11146 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11147 return new PackageParser.ServiceIntentInfo[size]; 11148 } 11149 11150 @Override 11151 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11152 if (!sUserManager.exists(userId)) return true; 11153 PackageParser.Package p = filter.service.owner; 11154 if (p != null) { 11155 PackageSetting ps = (PackageSetting)p.mExtras; 11156 if (ps != null) { 11157 // System apps are never considered stopped for purposes of 11158 // filtering, because there may be no way for the user to 11159 // actually re-launch them. 11160 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11161 && ps.getStopped(userId); 11162 } 11163 } 11164 return false; 11165 } 11166 11167 @Override 11168 protected boolean isPackageForFilter(String packageName, 11169 PackageParser.ServiceIntentInfo info) { 11170 return packageName.equals(info.service.owner.packageName); 11171 } 11172 11173 @Override 11174 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11175 int match, int userId) { 11176 if (!sUserManager.exists(userId)) return null; 11177 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11178 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11179 return null; 11180 } 11181 final PackageParser.Service service = info.service; 11182 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11183 if (ps == null) { 11184 return null; 11185 } 11186 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11187 ps.readUserState(userId), userId); 11188 if (si == null) { 11189 return null; 11190 } 11191 final ResolveInfo res = new ResolveInfo(); 11192 res.serviceInfo = si; 11193 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11194 res.filter = filter; 11195 } 11196 res.priority = info.getPriority(); 11197 res.preferredOrder = service.owner.mPreferredOrder; 11198 res.match = match; 11199 res.isDefault = info.hasDefault; 11200 res.labelRes = info.labelRes; 11201 res.nonLocalizedLabel = info.nonLocalizedLabel; 11202 res.icon = info.icon; 11203 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11204 return res; 11205 } 11206 11207 @Override 11208 protected void sortResults(List<ResolveInfo> results) { 11209 Collections.sort(results, mResolvePrioritySorter); 11210 } 11211 11212 @Override 11213 protected void dumpFilter(PrintWriter out, String prefix, 11214 PackageParser.ServiceIntentInfo filter) { 11215 out.print(prefix); out.print( 11216 Integer.toHexString(System.identityHashCode(filter.service))); 11217 out.print(' '); 11218 filter.service.printComponentShortName(out); 11219 out.print(" filter "); 11220 out.println(Integer.toHexString(System.identityHashCode(filter))); 11221 } 11222 11223 @Override 11224 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11225 return filter.service; 11226 } 11227 11228 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11229 PackageParser.Service service = (PackageParser.Service)label; 11230 out.print(prefix); out.print( 11231 Integer.toHexString(System.identityHashCode(service))); 11232 out.print(' '); 11233 service.printComponentShortName(out); 11234 if (count > 1) { 11235 out.print(" ("); out.print(count); out.print(" filters)"); 11236 } 11237 out.println(); 11238 } 11239 11240// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11241// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11242// final List<ResolveInfo> retList = Lists.newArrayList(); 11243// while (i.hasNext()) { 11244// final ResolveInfo resolveInfo = (ResolveInfo) i; 11245// if (isEnabledLP(resolveInfo.serviceInfo)) { 11246// retList.add(resolveInfo); 11247// } 11248// } 11249// return retList; 11250// } 11251 11252 // Keys are String (activity class name), values are Activity. 11253 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11254 = new ArrayMap<ComponentName, PackageParser.Service>(); 11255 private int mFlags; 11256 }; 11257 11258 private final class ProviderIntentResolver 11259 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11260 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11261 boolean defaultOnly, int userId) { 11262 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11263 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11264 } 11265 11266 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11267 int userId) { 11268 if (!sUserManager.exists(userId)) 11269 return null; 11270 mFlags = flags; 11271 return super.queryIntent(intent, resolvedType, 11272 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11273 } 11274 11275 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11276 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11277 if (!sUserManager.exists(userId)) 11278 return null; 11279 if (packageProviders == null) { 11280 return null; 11281 } 11282 mFlags = flags; 11283 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11284 final int N = packageProviders.size(); 11285 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11286 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11287 11288 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11289 for (int i = 0; i < N; ++i) { 11290 intentFilters = packageProviders.get(i).intents; 11291 if (intentFilters != null && intentFilters.size() > 0) { 11292 PackageParser.ProviderIntentInfo[] array = 11293 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11294 intentFilters.toArray(array); 11295 listCut.add(array); 11296 } 11297 } 11298 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11299 } 11300 11301 public final void addProvider(PackageParser.Provider p) { 11302 if (mProviders.containsKey(p.getComponentName())) { 11303 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11304 return; 11305 } 11306 11307 mProviders.put(p.getComponentName(), p); 11308 if (DEBUG_SHOW_INFO) { 11309 Log.v(TAG, " " 11310 + (p.info.nonLocalizedLabel != null 11311 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11312 Log.v(TAG, " Class=" + p.info.name); 11313 } 11314 final int NI = p.intents.size(); 11315 int j; 11316 for (j = 0; j < NI; j++) { 11317 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11318 if (DEBUG_SHOW_INFO) { 11319 Log.v(TAG, " IntentFilter:"); 11320 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11321 } 11322 if (!intent.debugCheck()) { 11323 Log.w(TAG, "==> For Provider " + p.info.name); 11324 } 11325 addFilter(intent); 11326 } 11327 } 11328 11329 public final void removeProvider(PackageParser.Provider p) { 11330 mProviders.remove(p.getComponentName()); 11331 if (DEBUG_SHOW_INFO) { 11332 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11333 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11334 Log.v(TAG, " Class=" + p.info.name); 11335 } 11336 final int NI = p.intents.size(); 11337 int j; 11338 for (j = 0; j < NI; j++) { 11339 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11340 if (DEBUG_SHOW_INFO) { 11341 Log.v(TAG, " IntentFilter:"); 11342 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11343 } 11344 removeFilter(intent); 11345 } 11346 } 11347 11348 @Override 11349 protected boolean allowFilterResult( 11350 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11351 ProviderInfo filterPi = filter.provider.info; 11352 for (int i = dest.size() - 1; i >= 0; i--) { 11353 ProviderInfo destPi = dest.get(i).providerInfo; 11354 if (destPi.name == filterPi.name 11355 && destPi.packageName == filterPi.packageName) { 11356 return false; 11357 } 11358 } 11359 return true; 11360 } 11361 11362 @Override 11363 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11364 return new PackageParser.ProviderIntentInfo[size]; 11365 } 11366 11367 @Override 11368 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11369 if (!sUserManager.exists(userId)) 11370 return true; 11371 PackageParser.Package p = filter.provider.owner; 11372 if (p != null) { 11373 PackageSetting ps = (PackageSetting) p.mExtras; 11374 if (ps != null) { 11375 // System apps are never considered stopped for purposes of 11376 // filtering, because there may be no way for the user to 11377 // actually re-launch them. 11378 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11379 && ps.getStopped(userId); 11380 } 11381 } 11382 return false; 11383 } 11384 11385 @Override 11386 protected boolean isPackageForFilter(String packageName, 11387 PackageParser.ProviderIntentInfo info) { 11388 return packageName.equals(info.provider.owner.packageName); 11389 } 11390 11391 @Override 11392 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11393 int match, int userId) { 11394 if (!sUserManager.exists(userId)) 11395 return null; 11396 final PackageParser.ProviderIntentInfo info = filter; 11397 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11398 return null; 11399 } 11400 final PackageParser.Provider provider = info.provider; 11401 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11402 if (ps == null) { 11403 return null; 11404 } 11405 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11406 ps.readUserState(userId), userId); 11407 if (pi == null) { 11408 return null; 11409 } 11410 final ResolveInfo res = new ResolveInfo(); 11411 res.providerInfo = pi; 11412 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11413 res.filter = filter; 11414 } 11415 res.priority = info.getPriority(); 11416 res.preferredOrder = provider.owner.mPreferredOrder; 11417 res.match = match; 11418 res.isDefault = info.hasDefault; 11419 res.labelRes = info.labelRes; 11420 res.nonLocalizedLabel = info.nonLocalizedLabel; 11421 res.icon = info.icon; 11422 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11423 return res; 11424 } 11425 11426 @Override 11427 protected void sortResults(List<ResolveInfo> results) { 11428 Collections.sort(results, mResolvePrioritySorter); 11429 } 11430 11431 @Override 11432 protected void dumpFilter(PrintWriter out, String prefix, 11433 PackageParser.ProviderIntentInfo filter) { 11434 out.print(prefix); 11435 out.print( 11436 Integer.toHexString(System.identityHashCode(filter.provider))); 11437 out.print(' '); 11438 filter.provider.printComponentShortName(out); 11439 out.print(" filter "); 11440 out.println(Integer.toHexString(System.identityHashCode(filter))); 11441 } 11442 11443 @Override 11444 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11445 return filter.provider; 11446 } 11447 11448 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11449 PackageParser.Provider provider = (PackageParser.Provider)label; 11450 out.print(prefix); out.print( 11451 Integer.toHexString(System.identityHashCode(provider))); 11452 out.print(' '); 11453 provider.printComponentShortName(out); 11454 if (count > 1) { 11455 out.print(" ("); out.print(count); out.print(" filters)"); 11456 } 11457 out.println(); 11458 } 11459 11460 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11461 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11462 private int mFlags; 11463 } 11464 11465 static final class EphemeralIntentResolver 11466 extends IntentResolver<EphemeralResponse, EphemeralResponse> { 11467 /** 11468 * The result that has the highest defined order. Ordering applies on a 11469 * per-package basis. Mapping is from package name to Pair of order and 11470 * EphemeralResolveInfo. 11471 * <p> 11472 * NOTE: This is implemented as a field variable for convenience and efficiency. 11473 * By having a field variable, we're able to track filter ordering as soon as 11474 * a non-zero order is defined. Otherwise, multiple loops across the result set 11475 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11476 * this needs to be contained entirely within {@link #filterResults()}. 11477 */ 11478 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11479 11480 @Override 11481 protected EphemeralResponse[] newArray(int size) { 11482 return new EphemeralResponse[size]; 11483 } 11484 11485 @Override 11486 protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) { 11487 return true; 11488 } 11489 11490 @Override 11491 protected EphemeralResponse newResult(EphemeralResponse responseObj, int match, 11492 int userId) { 11493 if (!sUserManager.exists(userId)) { 11494 return null; 11495 } 11496 final String packageName = responseObj.resolveInfo.getPackageName(); 11497 final Integer order = responseObj.getOrder(); 11498 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11499 mOrderResult.get(packageName); 11500 // ordering is enabled and this item's order isn't high enough 11501 if (lastOrderResult != null && lastOrderResult.first >= order) { 11502 return null; 11503 } 11504 final EphemeralResolveInfo res = responseObj.resolveInfo; 11505 if (order > 0) { 11506 // non-zero order, enable ordering 11507 mOrderResult.put(packageName, new Pair<>(order, res)); 11508 } 11509 return responseObj; 11510 } 11511 11512 @Override 11513 protected void filterResults(List<EphemeralResponse> results) { 11514 // only do work if ordering is enabled [most of the time it won't be] 11515 if (mOrderResult.size() == 0) { 11516 return; 11517 } 11518 int resultSize = results.size(); 11519 for (int i = 0; i < resultSize; i++) { 11520 final EphemeralResolveInfo info = results.get(i).resolveInfo; 11521 final String packageName = info.getPackageName(); 11522 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11523 if (savedInfo == null) { 11524 // package doesn't having ordering 11525 continue; 11526 } 11527 if (savedInfo.second == info) { 11528 // circled back to the highest ordered item; remove from order list 11529 mOrderResult.remove(savedInfo); 11530 if (mOrderResult.size() == 0) { 11531 // no more ordered items 11532 break; 11533 } 11534 continue; 11535 } 11536 // item has a worse order, remove it from the result list 11537 results.remove(i); 11538 resultSize--; 11539 i--; 11540 } 11541 } 11542 } 11543 11544 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11545 new Comparator<ResolveInfo>() { 11546 public int compare(ResolveInfo r1, ResolveInfo r2) { 11547 int v1 = r1.priority; 11548 int v2 = r2.priority; 11549 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11550 if (v1 != v2) { 11551 return (v1 > v2) ? -1 : 1; 11552 } 11553 v1 = r1.preferredOrder; 11554 v2 = r2.preferredOrder; 11555 if (v1 != v2) { 11556 return (v1 > v2) ? -1 : 1; 11557 } 11558 if (r1.isDefault != r2.isDefault) { 11559 return r1.isDefault ? -1 : 1; 11560 } 11561 v1 = r1.match; 11562 v2 = r2.match; 11563 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11564 if (v1 != v2) { 11565 return (v1 > v2) ? -1 : 1; 11566 } 11567 if (r1.system != r2.system) { 11568 return r1.system ? -1 : 1; 11569 } 11570 if (r1.activityInfo != null) { 11571 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11572 } 11573 if (r1.serviceInfo != null) { 11574 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11575 } 11576 if (r1.providerInfo != null) { 11577 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11578 } 11579 return 0; 11580 } 11581 }; 11582 11583 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11584 new Comparator<ProviderInfo>() { 11585 public int compare(ProviderInfo p1, ProviderInfo p2) { 11586 final int v1 = p1.initOrder; 11587 final int v2 = p2.initOrder; 11588 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11589 } 11590 }; 11591 11592 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11593 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11594 final int[] userIds) { 11595 mHandler.post(new Runnable() { 11596 @Override 11597 public void run() { 11598 try { 11599 final IActivityManager am = ActivityManager.getService(); 11600 if (am == null) return; 11601 final int[] resolvedUserIds; 11602 if (userIds == null) { 11603 resolvedUserIds = am.getRunningUserIds(); 11604 } else { 11605 resolvedUserIds = userIds; 11606 } 11607 for (int id : resolvedUserIds) { 11608 final Intent intent = new Intent(action, 11609 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11610 if (extras != null) { 11611 intent.putExtras(extras); 11612 } 11613 if (targetPkg != null) { 11614 intent.setPackage(targetPkg); 11615 } 11616 // Modify the UID when posting to other users 11617 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11618 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11619 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11620 intent.putExtra(Intent.EXTRA_UID, uid); 11621 } 11622 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11623 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11624 if (DEBUG_BROADCASTS) { 11625 RuntimeException here = new RuntimeException("here"); 11626 here.fillInStackTrace(); 11627 Slog.d(TAG, "Sending to user " + id + ": " 11628 + intent.toShortString(false, true, false, false) 11629 + " " + intent.getExtras(), here); 11630 } 11631 am.broadcastIntent(null, intent, null, finishedReceiver, 11632 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11633 null, finishedReceiver != null, false, id); 11634 } 11635 } catch (RemoteException ex) { 11636 } 11637 } 11638 }); 11639 } 11640 11641 /** 11642 * Check if the external storage media is available. This is true if there 11643 * is a mounted external storage medium or if the external storage is 11644 * emulated. 11645 */ 11646 private boolean isExternalMediaAvailable() { 11647 return mMediaMounted || Environment.isExternalStorageEmulated(); 11648 } 11649 11650 @Override 11651 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11652 // writer 11653 synchronized (mPackages) { 11654 if (!isExternalMediaAvailable()) { 11655 // If the external storage is no longer mounted at this point, 11656 // the caller may not have been able to delete all of this 11657 // packages files and can not delete any more. Bail. 11658 return null; 11659 } 11660 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11661 if (lastPackage != null) { 11662 pkgs.remove(lastPackage); 11663 } 11664 if (pkgs.size() > 0) { 11665 return pkgs.get(0); 11666 } 11667 } 11668 return null; 11669 } 11670 11671 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11672 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11673 userId, andCode ? 1 : 0, packageName); 11674 if (mSystemReady) { 11675 msg.sendToTarget(); 11676 } else { 11677 if (mPostSystemReadyMessages == null) { 11678 mPostSystemReadyMessages = new ArrayList<>(); 11679 } 11680 mPostSystemReadyMessages.add(msg); 11681 } 11682 } 11683 11684 void startCleaningPackages() { 11685 // reader 11686 if (!isExternalMediaAvailable()) { 11687 return; 11688 } 11689 synchronized (mPackages) { 11690 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11691 return; 11692 } 11693 } 11694 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11695 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11696 IActivityManager am = ActivityManager.getService(); 11697 if (am != null) { 11698 try { 11699 am.startService(null, intent, null, mContext.getOpPackageName(), 11700 UserHandle.USER_SYSTEM); 11701 } catch (RemoteException e) { 11702 } 11703 } 11704 } 11705 11706 @Override 11707 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11708 int installFlags, String installerPackageName, int userId) { 11709 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11710 11711 final int callingUid = Binder.getCallingUid(); 11712 enforceCrossUserPermission(callingUid, userId, 11713 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11714 11715 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11716 try { 11717 if (observer != null) { 11718 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11719 } 11720 } catch (RemoteException re) { 11721 } 11722 return; 11723 } 11724 11725 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11726 installFlags |= PackageManager.INSTALL_FROM_ADB; 11727 11728 } else { 11729 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11730 // about installerPackageName. 11731 11732 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11733 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11734 } 11735 11736 UserHandle user; 11737 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11738 user = UserHandle.ALL; 11739 } else { 11740 user = new UserHandle(userId); 11741 } 11742 11743 // Only system components can circumvent runtime permissions when installing. 11744 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11745 && mContext.checkCallingOrSelfPermission(Manifest.permission 11746 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11747 throw new SecurityException("You need the " 11748 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11749 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11750 } 11751 11752 final File originFile = new File(originPath); 11753 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11754 11755 final Message msg = mHandler.obtainMessage(INIT_COPY); 11756 final VerificationInfo verificationInfo = new VerificationInfo( 11757 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11758 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11759 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11760 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11761 null /*certificates*/); 11762 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11763 msg.obj = params; 11764 11765 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11766 System.identityHashCode(msg.obj)); 11767 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11768 System.identityHashCode(msg.obj)); 11769 11770 mHandler.sendMessage(msg); 11771 } 11772 11773 void installStage(String packageName, File stagedDir, String stagedCid, 11774 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11775 String installerPackageName, int installerUid, UserHandle user, 11776 Certificate[][] certificates) { 11777 if (DEBUG_EPHEMERAL) { 11778 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11779 Slog.d(TAG, "Ephemeral install of " + packageName); 11780 } 11781 } 11782 final VerificationInfo verificationInfo = new VerificationInfo( 11783 sessionParams.originatingUri, sessionParams.referrerUri, 11784 sessionParams.originatingUid, installerUid); 11785 11786 final OriginInfo origin; 11787 if (stagedDir != null) { 11788 origin = OriginInfo.fromStagedFile(stagedDir); 11789 } else { 11790 origin = OriginInfo.fromStagedContainer(stagedCid); 11791 } 11792 11793 final Message msg = mHandler.obtainMessage(INIT_COPY); 11794 final InstallParams params = new InstallParams(origin, null, observer, 11795 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11796 verificationInfo, user, sessionParams.abiOverride, 11797 sessionParams.grantedRuntimePermissions, certificates); 11798 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11799 msg.obj = params; 11800 11801 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11802 System.identityHashCode(msg.obj)); 11803 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11804 System.identityHashCode(msg.obj)); 11805 11806 mHandler.sendMessage(msg); 11807 } 11808 11809 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11810 int userId) { 11811 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11812 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 11813 } 11814 11815 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 11816 int appId, int... userIds) { 11817 if (ArrayUtils.isEmpty(userIds)) { 11818 return; 11819 } 11820 Bundle extras = new Bundle(1); 11821 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 11822 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 11823 11824 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11825 packageName, extras, 0, null, null, userIds); 11826 if (isSystem) { 11827 mHandler.post(() -> { 11828 for (int userId : userIds) { 11829 sendBootCompletedBroadcastToSystemApp(packageName, userId); 11830 } 11831 } 11832 ); 11833 } 11834 } 11835 11836 /** 11837 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 11838 * automatically without needing an explicit launch. 11839 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 11840 */ 11841 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 11842 // If user is not running, the app didn't miss any broadcast 11843 if (!mUserManagerInternal.isUserRunning(userId)) { 11844 return; 11845 } 11846 final IActivityManager am = ActivityManager.getService(); 11847 try { 11848 // Deliver LOCKED_BOOT_COMPLETED first 11849 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 11850 .setPackage(packageName); 11851 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 11852 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 11853 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11854 11855 // Deliver BOOT_COMPLETED only if user is unlocked 11856 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 11857 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 11858 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 11859 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11860 } 11861 } catch (RemoteException e) { 11862 throw e.rethrowFromSystemServer(); 11863 } 11864 } 11865 11866 @Override 11867 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11868 int userId) { 11869 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11870 PackageSetting pkgSetting; 11871 final int uid = Binder.getCallingUid(); 11872 enforceCrossUserPermission(uid, userId, 11873 true /* requireFullPermission */, true /* checkShell */, 11874 "setApplicationHiddenSetting for user " + userId); 11875 11876 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11877 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11878 return false; 11879 } 11880 11881 long callingId = Binder.clearCallingIdentity(); 11882 try { 11883 boolean sendAdded = false; 11884 boolean sendRemoved = false; 11885 // writer 11886 synchronized (mPackages) { 11887 pkgSetting = mSettings.mPackages.get(packageName); 11888 if (pkgSetting == null) { 11889 return false; 11890 } 11891 // Do not allow "android" is being disabled 11892 if ("android".equals(packageName)) { 11893 Slog.w(TAG, "Cannot hide package: android"); 11894 return false; 11895 } 11896 // Only allow protected packages to hide themselves. 11897 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11898 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11899 Slog.w(TAG, "Not hiding protected package: " + packageName); 11900 return false; 11901 } 11902 11903 if (pkgSetting.getHidden(userId) != hidden) { 11904 pkgSetting.setHidden(hidden, userId); 11905 mSettings.writePackageRestrictionsLPr(userId); 11906 if (hidden) { 11907 sendRemoved = true; 11908 } else { 11909 sendAdded = true; 11910 } 11911 } 11912 } 11913 if (sendAdded) { 11914 sendPackageAddedForUser(packageName, pkgSetting, userId); 11915 return true; 11916 } 11917 if (sendRemoved) { 11918 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11919 "hiding pkg"); 11920 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11921 return true; 11922 } 11923 } finally { 11924 Binder.restoreCallingIdentity(callingId); 11925 } 11926 return false; 11927 } 11928 11929 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11930 int userId) { 11931 final PackageRemovedInfo info = new PackageRemovedInfo(); 11932 info.removedPackage = packageName; 11933 info.removedUsers = new int[] {userId}; 11934 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11935 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11936 } 11937 11938 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11939 if (pkgList.length > 0) { 11940 Bundle extras = new Bundle(1); 11941 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11942 11943 sendPackageBroadcast( 11944 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11945 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11946 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11947 new int[] {userId}); 11948 } 11949 } 11950 11951 /** 11952 * Returns true if application is not found or there was an error. Otherwise it returns 11953 * the hidden state of the package for the given user. 11954 */ 11955 @Override 11956 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11957 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11958 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11959 true /* requireFullPermission */, false /* checkShell */, 11960 "getApplicationHidden for user " + userId); 11961 PackageSetting pkgSetting; 11962 long callingId = Binder.clearCallingIdentity(); 11963 try { 11964 // writer 11965 synchronized (mPackages) { 11966 pkgSetting = mSettings.mPackages.get(packageName); 11967 if (pkgSetting == null) { 11968 return true; 11969 } 11970 return pkgSetting.getHidden(userId); 11971 } 11972 } finally { 11973 Binder.restoreCallingIdentity(callingId); 11974 } 11975 } 11976 11977 /** 11978 * @hide 11979 */ 11980 @Override 11981 public int installExistingPackageAsUser(String packageName, int userId) { 11982 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11983 null); 11984 PackageSetting pkgSetting; 11985 final int uid = Binder.getCallingUid(); 11986 enforceCrossUserPermission(uid, userId, 11987 true /* requireFullPermission */, true /* checkShell */, 11988 "installExistingPackage for user " + userId); 11989 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11990 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11991 } 11992 11993 long callingId = Binder.clearCallingIdentity(); 11994 try { 11995 boolean installed = false; 11996 11997 // writer 11998 synchronized (mPackages) { 11999 pkgSetting = mSettings.mPackages.get(packageName); 12000 if (pkgSetting == null) { 12001 return PackageManager.INSTALL_FAILED_INVALID_URI; 12002 } 12003 if (!pkgSetting.getInstalled(userId)) { 12004 pkgSetting.setInstalled(true, userId); 12005 pkgSetting.setHidden(false, userId); 12006 mSettings.writePackageRestrictionsLPr(userId); 12007 installed = true; 12008 } 12009 } 12010 12011 if (installed) { 12012 if (pkgSetting.pkg != null) { 12013 synchronized (mInstallLock) { 12014 // We don't need to freeze for a brand new install 12015 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 12016 } 12017 } 12018 sendPackageAddedForUser(packageName, pkgSetting, userId); 12019 } 12020 } finally { 12021 Binder.restoreCallingIdentity(callingId); 12022 } 12023 12024 return PackageManager.INSTALL_SUCCEEDED; 12025 } 12026 12027 boolean isUserRestricted(int userId, String restrictionKey) { 12028 Bundle restrictions = sUserManager.getUserRestrictions(userId); 12029 if (restrictions.getBoolean(restrictionKey, false)) { 12030 Log.w(TAG, "User is restricted: " + restrictionKey); 12031 return true; 12032 } 12033 return false; 12034 } 12035 12036 @Override 12037 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 12038 int userId) { 12039 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12040 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12041 true /* requireFullPermission */, true /* checkShell */, 12042 "setPackagesSuspended for user " + userId); 12043 12044 if (ArrayUtils.isEmpty(packageNames)) { 12045 return packageNames; 12046 } 12047 12048 // List of package names for whom the suspended state has changed. 12049 List<String> changedPackages = new ArrayList<>(packageNames.length); 12050 // List of package names for whom the suspended state is not set as requested in this 12051 // method. 12052 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 12053 long callingId = Binder.clearCallingIdentity(); 12054 try { 12055 for (int i = 0; i < packageNames.length; i++) { 12056 String packageName = packageNames[i]; 12057 boolean changed = false; 12058 final int appId; 12059 synchronized (mPackages) { 12060 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12061 if (pkgSetting == null) { 12062 Slog.w(TAG, "Could not find package setting for package \"" + packageName 12063 + "\". Skipping suspending/un-suspending."); 12064 unactionedPackages.add(packageName); 12065 continue; 12066 } 12067 appId = pkgSetting.appId; 12068 if (pkgSetting.getSuspended(userId) != suspended) { 12069 if (!canSuspendPackageForUserLocked(packageName, userId)) { 12070 unactionedPackages.add(packageName); 12071 continue; 12072 } 12073 pkgSetting.setSuspended(suspended, userId); 12074 mSettings.writePackageRestrictionsLPr(userId); 12075 changed = true; 12076 changedPackages.add(packageName); 12077 } 12078 } 12079 12080 if (changed && suspended) { 12081 killApplication(packageName, UserHandle.getUid(userId, appId), 12082 "suspending package"); 12083 } 12084 } 12085 } finally { 12086 Binder.restoreCallingIdentity(callingId); 12087 } 12088 12089 if (!changedPackages.isEmpty()) { 12090 sendPackagesSuspendedForUser(changedPackages.toArray( 12091 new String[changedPackages.size()]), userId, suspended); 12092 } 12093 12094 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 12095 } 12096 12097 @Override 12098 public boolean isPackageSuspendedForUser(String packageName, int userId) { 12099 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12100 true /* requireFullPermission */, false /* checkShell */, 12101 "isPackageSuspendedForUser for user " + userId); 12102 synchronized (mPackages) { 12103 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12104 if (pkgSetting == null) { 12105 throw new IllegalArgumentException("Unknown target package: " + packageName); 12106 } 12107 return pkgSetting.getSuspended(userId); 12108 } 12109 } 12110 12111 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 12112 if (isPackageDeviceAdmin(packageName, userId)) { 12113 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12114 + "\": has an active device admin"); 12115 return false; 12116 } 12117 12118 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 12119 if (packageName.equals(activeLauncherPackageName)) { 12120 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12121 + "\": contains the active launcher"); 12122 return false; 12123 } 12124 12125 if (packageName.equals(mRequiredInstallerPackage)) { 12126 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12127 + "\": required for package installation"); 12128 return false; 12129 } 12130 12131 if (packageName.equals(mRequiredUninstallerPackage)) { 12132 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12133 + "\": required for package uninstallation"); 12134 return false; 12135 } 12136 12137 if (packageName.equals(mRequiredVerifierPackage)) { 12138 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12139 + "\": required for package verification"); 12140 return false; 12141 } 12142 12143 if (packageName.equals(getDefaultDialerPackageName(userId))) { 12144 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12145 + "\": is the default dialer"); 12146 return false; 12147 } 12148 12149 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12150 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12151 + "\": protected package"); 12152 return false; 12153 } 12154 12155 return true; 12156 } 12157 12158 private String getActiveLauncherPackageName(int userId) { 12159 Intent intent = new Intent(Intent.ACTION_MAIN); 12160 intent.addCategory(Intent.CATEGORY_HOME); 12161 ResolveInfo resolveInfo = resolveIntent( 12162 intent, 12163 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 12164 PackageManager.MATCH_DEFAULT_ONLY, 12165 userId); 12166 12167 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 12168 } 12169 12170 private String getDefaultDialerPackageName(int userId) { 12171 synchronized (mPackages) { 12172 return mSettings.getDefaultDialerPackageNameLPw(userId); 12173 } 12174 } 12175 12176 @Override 12177 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 12178 mContext.enforceCallingOrSelfPermission( 12179 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12180 "Only package verification agents can verify applications"); 12181 12182 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12183 final PackageVerificationResponse response = new PackageVerificationResponse( 12184 verificationCode, Binder.getCallingUid()); 12185 msg.arg1 = id; 12186 msg.obj = response; 12187 mHandler.sendMessage(msg); 12188 } 12189 12190 @Override 12191 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12192 long millisecondsToDelay) { 12193 mContext.enforceCallingOrSelfPermission( 12194 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12195 "Only package verification agents can extend verification timeouts"); 12196 12197 final PackageVerificationState state = mPendingVerification.get(id); 12198 final PackageVerificationResponse response = new PackageVerificationResponse( 12199 verificationCodeAtTimeout, Binder.getCallingUid()); 12200 12201 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12202 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12203 } 12204 if (millisecondsToDelay < 0) { 12205 millisecondsToDelay = 0; 12206 } 12207 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12208 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12209 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12210 } 12211 12212 if ((state != null) && !state.timeoutExtended()) { 12213 state.extendTimeout(); 12214 12215 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12216 msg.arg1 = id; 12217 msg.obj = response; 12218 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12219 } 12220 } 12221 12222 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12223 int verificationCode, UserHandle user) { 12224 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12225 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12226 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12227 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12228 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12229 12230 mContext.sendBroadcastAsUser(intent, user, 12231 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12232 } 12233 12234 private ComponentName matchComponentForVerifier(String packageName, 12235 List<ResolveInfo> receivers) { 12236 ActivityInfo targetReceiver = null; 12237 12238 final int NR = receivers.size(); 12239 for (int i = 0; i < NR; i++) { 12240 final ResolveInfo info = receivers.get(i); 12241 if (info.activityInfo == null) { 12242 continue; 12243 } 12244 12245 if (packageName.equals(info.activityInfo.packageName)) { 12246 targetReceiver = info.activityInfo; 12247 break; 12248 } 12249 } 12250 12251 if (targetReceiver == null) { 12252 return null; 12253 } 12254 12255 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12256 } 12257 12258 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12259 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12260 if (pkgInfo.verifiers.length == 0) { 12261 return null; 12262 } 12263 12264 final int N = pkgInfo.verifiers.length; 12265 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12266 for (int i = 0; i < N; i++) { 12267 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12268 12269 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12270 receivers); 12271 if (comp == null) { 12272 continue; 12273 } 12274 12275 final int verifierUid = getUidForVerifier(verifierInfo); 12276 if (verifierUid == -1) { 12277 continue; 12278 } 12279 12280 if (DEBUG_VERIFY) { 12281 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12282 + " with the correct signature"); 12283 } 12284 sufficientVerifiers.add(comp); 12285 verificationState.addSufficientVerifier(verifierUid); 12286 } 12287 12288 return sufficientVerifiers; 12289 } 12290 12291 private int getUidForVerifier(VerifierInfo verifierInfo) { 12292 synchronized (mPackages) { 12293 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12294 if (pkg == null) { 12295 return -1; 12296 } else if (pkg.mSignatures.length != 1) { 12297 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12298 + " has more than one signature; ignoring"); 12299 return -1; 12300 } 12301 12302 /* 12303 * If the public key of the package's signature does not match 12304 * our expected public key, then this is a different package and 12305 * we should skip. 12306 */ 12307 12308 final byte[] expectedPublicKey; 12309 try { 12310 final Signature verifierSig = pkg.mSignatures[0]; 12311 final PublicKey publicKey = verifierSig.getPublicKey(); 12312 expectedPublicKey = publicKey.getEncoded(); 12313 } catch (CertificateException e) { 12314 return -1; 12315 } 12316 12317 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12318 12319 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12320 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12321 + " does not have the expected public key; ignoring"); 12322 return -1; 12323 } 12324 12325 return pkg.applicationInfo.uid; 12326 } 12327 } 12328 12329 @Override 12330 public void finishPackageInstall(int token, boolean didLaunch) { 12331 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12332 12333 if (DEBUG_INSTALL) { 12334 Slog.v(TAG, "BM finishing package install for " + token); 12335 } 12336 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12337 12338 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12339 mHandler.sendMessage(msg); 12340 } 12341 12342 /** 12343 * Get the verification agent timeout. 12344 * 12345 * @return verification timeout in milliseconds 12346 */ 12347 private long getVerificationTimeout() { 12348 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12349 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12350 DEFAULT_VERIFICATION_TIMEOUT); 12351 } 12352 12353 /** 12354 * Get the default verification agent response code. 12355 * 12356 * @return default verification response code 12357 */ 12358 private int getDefaultVerificationResponse() { 12359 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12360 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12361 DEFAULT_VERIFICATION_RESPONSE); 12362 } 12363 12364 /** 12365 * Check whether or not package verification has been enabled. 12366 * 12367 * @return true if verification should be performed 12368 */ 12369 private boolean isVerificationEnabled(int userId, int installFlags) { 12370 if (!DEFAULT_VERIFY_ENABLE) { 12371 return false; 12372 } 12373 // Ephemeral apps don't get the full verification treatment 12374 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12375 if (DEBUG_EPHEMERAL) { 12376 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12377 } 12378 return false; 12379 } 12380 12381 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12382 12383 // Check if installing from ADB 12384 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12385 // Do not run verification in a test harness environment 12386 if (ActivityManager.isRunningInTestHarness()) { 12387 return false; 12388 } 12389 if (ensureVerifyAppsEnabled) { 12390 return true; 12391 } 12392 // Check if the developer does not want package verification for ADB installs 12393 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12394 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12395 return false; 12396 } 12397 } 12398 12399 if (ensureVerifyAppsEnabled) { 12400 return true; 12401 } 12402 12403 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12404 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12405 } 12406 12407 @Override 12408 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12409 throws RemoteException { 12410 mContext.enforceCallingOrSelfPermission( 12411 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12412 "Only intentfilter verification agents can verify applications"); 12413 12414 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12415 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12416 Binder.getCallingUid(), verificationCode, failedDomains); 12417 msg.arg1 = id; 12418 msg.obj = response; 12419 mHandler.sendMessage(msg); 12420 } 12421 12422 @Override 12423 public int getIntentVerificationStatus(String packageName, int userId) { 12424 synchronized (mPackages) { 12425 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12426 } 12427 } 12428 12429 @Override 12430 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12431 mContext.enforceCallingOrSelfPermission( 12432 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12433 12434 boolean result = false; 12435 synchronized (mPackages) { 12436 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12437 } 12438 if (result) { 12439 scheduleWritePackageRestrictionsLocked(userId); 12440 } 12441 return result; 12442 } 12443 12444 @Override 12445 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12446 String packageName) { 12447 synchronized (mPackages) { 12448 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12449 } 12450 } 12451 12452 @Override 12453 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12454 if (TextUtils.isEmpty(packageName)) { 12455 return ParceledListSlice.emptyList(); 12456 } 12457 synchronized (mPackages) { 12458 PackageParser.Package pkg = mPackages.get(packageName); 12459 if (pkg == null || pkg.activities == null) { 12460 return ParceledListSlice.emptyList(); 12461 } 12462 final int count = pkg.activities.size(); 12463 ArrayList<IntentFilter> result = new ArrayList<>(); 12464 for (int n=0; n<count; n++) { 12465 PackageParser.Activity activity = pkg.activities.get(n); 12466 if (activity.intents != null && activity.intents.size() > 0) { 12467 result.addAll(activity.intents); 12468 } 12469 } 12470 return new ParceledListSlice<>(result); 12471 } 12472 } 12473 12474 @Override 12475 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12476 mContext.enforceCallingOrSelfPermission( 12477 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12478 12479 synchronized (mPackages) { 12480 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12481 if (packageName != null) { 12482 result |= updateIntentVerificationStatus(packageName, 12483 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12484 userId); 12485 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12486 packageName, userId); 12487 } 12488 return result; 12489 } 12490 } 12491 12492 @Override 12493 public String getDefaultBrowserPackageName(int userId) { 12494 synchronized (mPackages) { 12495 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12496 } 12497 } 12498 12499 /** 12500 * Get the "allow unknown sources" setting. 12501 * 12502 * @return the current "allow unknown sources" setting 12503 */ 12504 private int getUnknownSourcesSettings() { 12505 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12506 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12507 -1); 12508 } 12509 12510 @Override 12511 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12512 final int uid = Binder.getCallingUid(); 12513 // writer 12514 synchronized (mPackages) { 12515 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12516 if (targetPackageSetting == null) { 12517 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12518 } 12519 12520 PackageSetting installerPackageSetting; 12521 if (installerPackageName != null) { 12522 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12523 if (installerPackageSetting == null) { 12524 throw new IllegalArgumentException("Unknown installer package: " 12525 + installerPackageName); 12526 } 12527 } else { 12528 installerPackageSetting = null; 12529 } 12530 12531 Signature[] callerSignature; 12532 Object obj = mSettings.getUserIdLPr(uid); 12533 if (obj != null) { 12534 if (obj instanceof SharedUserSetting) { 12535 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12536 } else if (obj instanceof PackageSetting) { 12537 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12538 } else { 12539 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12540 } 12541 } else { 12542 throw new SecurityException("Unknown calling UID: " + uid); 12543 } 12544 12545 // Verify: can't set installerPackageName to a package that is 12546 // not signed with the same cert as the caller. 12547 if (installerPackageSetting != null) { 12548 if (compareSignatures(callerSignature, 12549 installerPackageSetting.signatures.mSignatures) 12550 != PackageManager.SIGNATURE_MATCH) { 12551 throw new SecurityException( 12552 "Caller does not have same cert as new installer package " 12553 + installerPackageName); 12554 } 12555 } 12556 12557 // Verify: if target already has an installer package, it must 12558 // be signed with the same cert as the caller. 12559 if (targetPackageSetting.installerPackageName != null) { 12560 PackageSetting setting = mSettings.mPackages.get( 12561 targetPackageSetting.installerPackageName); 12562 // If the currently set package isn't valid, then it's always 12563 // okay to change it. 12564 if (setting != null) { 12565 if (compareSignatures(callerSignature, 12566 setting.signatures.mSignatures) 12567 != PackageManager.SIGNATURE_MATCH) { 12568 throw new SecurityException( 12569 "Caller does not have same cert as old installer package " 12570 + targetPackageSetting.installerPackageName); 12571 } 12572 } 12573 } 12574 12575 // Okay! 12576 targetPackageSetting.installerPackageName = installerPackageName; 12577 if (installerPackageName != null) { 12578 mSettings.mInstallerPackages.add(installerPackageName); 12579 } 12580 scheduleWriteSettingsLocked(); 12581 } 12582 } 12583 12584 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12585 // Queue up an async operation since the package installation may take a little while. 12586 mHandler.post(new Runnable() { 12587 public void run() { 12588 mHandler.removeCallbacks(this); 12589 // Result object to be returned 12590 PackageInstalledInfo res = new PackageInstalledInfo(); 12591 res.setReturnCode(currentStatus); 12592 res.uid = -1; 12593 res.pkg = null; 12594 res.removedInfo = null; 12595 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12596 args.doPreInstall(res.returnCode); 12597 synchronized (mInstallLock) { 12598 installPackageTracedLI(args, res); 12599 } 12600 args.doPostInstall(res.returnCode, res.uid); 12601 } 12602 12603 // A restore should be performed at this point if (a) the install 12604 // succeeded, (b) the operation is not an update, and (c) the new 12605 // package has not opted out of backup participation. 12606 final boolean update = res.removedInfo != null 12607 && res.removedInfo.removedPackage != null; 12608 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12609 boolean doRestore = !update 12610 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12611 12612 // Set up the post-install work request bookkeeping. This will be used 12613 // and cleaned up by the post-install event handling regardless of whether 12614 // there's a restore pass performed. Token values are >= 1. 12615 int token; 12616 if (mNextInstallToken < 0) mNextInstallToken = 1; 12617 token = mNextInstallToken++; 12618 12619 PostInstallData data = new PostInstallData(args, res); 12620 mRunningInstalls.put(token, data); 12621 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12622 12623 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12624 // Pass responsibility to the Backup Manager. It will perform a 12625 // restore if appropriate, then pass responsibility back to the 12626 // Package Manager to run the post-install observer callbacks 12627 // and broadcasts. 12628 IBackupManager bm = IBackupManager.Stub.asInterface( 12629 ServiceManager.getService(Context.BACKUP_SERVICE)); 12630 if (bm != null) { 12631 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12632 + " to BM for possible restore"); 12633 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12634 try { 12635 // TODO: http://b/22388012 12636 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12637 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12638 } else { 12639 doRestore = false; 12640 } 12641 } catch (RemoteException e) { 12642 // can't happen; the backup manager is local 12643 } catch (Exception e) { 12644 Slog.e(TAG, "Exception trying to enqueue restore", e); 12645 doRestore = false; 12646 } 12647 } else { 12648 Slog.e(TAG, "Backup Manager not found!"); 12649 doRestore = false; 12650 } 12651 } 12652 12653 if (!doRestore) { 12654 // No restore possible, or the Backup Manager was mysteriously not 12655 // available -- just fire the post-install work request directly. 12656 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12657 12658 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12659 12660 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12661 mHandler.sendMessage(msg); 12662 } 12663 } 12664 }); 12665 } 12666 12667 /** 12668 * Callback from PackageSettings whenever an app is first transitioned out of the 12669 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12670 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12671 * here whether the app is the target of an ongoing install, and only send the 12672 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12673 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12674 * handling. 12675 */ 12676 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12677 // Serialize this with the rest of the install-process message chain. In the 12678 // restore-at-install case, this Runnable will necessarily run before the 12679 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12680 // are coherent. In the non-restore case, the app has already completed install 12681 // and been launched through some other means, so it is not in a problematic 12682 // state for observers to see the FIRST_LAUNCH signal. 12683 mHandler.post(new Runnable() { 12684 @Override 12685 public void run() { 12686 for (int i = 0; i < mRunningInstalls.size(); i++) { 12687 final PostInstallData data = mRunningInstalls.valueAt(i); 12688 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12689 continue; 12690 } 12691 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12692 // right package; but is it for the right user? 12693 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12694 if (userId == data.res.newUsers[uIndex]) { 12695 if (DEBUG_BACKUP) { 12696 Slog.i(TAG, "Package " + pkgName 12697 + " being restored so deferring FIRST_LAUNCH"); 12698 } 12699 return; 12700 } 12701 } 12702 } 12703 } 12704 // didn't find it, so not being restored 12705 if (DEBUG_BACKUP) { 12706 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12707 } 12708 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12709 } 12710 }); 12711 } 12712 12713 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12714 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12715 installerPkg, null, userIds); 12716 } 12717 12718 private abstract class HandlerParams { 12719 private static final int MAX_RETRIES = 4; 12720 12721 /** 12722 * Number of times startCopy() has been attempted and had a non-fatal 12723 * error. 12724 */ 12725 private int mRetries = 0; 12726 12727 /** User handle for the user requesting the information or installation. */ 12728 private final UserHandle mUser; 12729 String traceMethod; 12730 int traceCookie; 12731 12732 HandlerParams(UserHandle user) { 12733 mUser = user; 12734 } 12735 12736 UserHandle getUser() { 12737 return mUser; 12738 } 12739 12740 HandlerParams setTraceMethod(String traceMethod) { 12741 this.traceMethod = traceMethod; 12742 return this; 12743 } 12744 12745 HandlerParams setTraceCookie(int traceCookie) { 12746 this.traceCookie = traceCookie; 12747 return this; 12748 } 12749 12750 final boolean startCopy() { 12751 boolean res; 12752 try { 12753 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12754 12755 if (++mRetries > MAX_RETRIES) { 12756 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12757 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12758 handleServiceError(); 12759 return false; 12760 } else { 12761 handleStartCopy(); 12762 res = true; 12763 } 12764 } catch (RemoteException e) { 12765 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12766 mHandler.sendEmptyMessage(MCS_RECONNECT); 12767 res = false; 12768 } 12769 handleReturnCode(); 12770 return res; 12771 } 12772 12773 final void serviceError() { 12774 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12775 handleServiceError(); 12776 handleReturnCode(); 12777 } 12778 12779 abstract void handleStartCopy() throws RemoteException; 12780 abstract void handleServiceError(); 12781 abstract void handleReturnCode(); 12782 } 12783 12784 class MeasureParams extends HandlerParams { 12785 private final PackageStats mStats; 12786 private boolean mSuccess; 12787 12788 private final IPackageStatsObserver mObserver; 12789 12790 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12791 super(new UserHandle(stats.userHandle)); 12792 mObserver = observer; 12793 mStats = stats; 12794 } 12795 12796 @Override 12797 public String toString() { 12798 return "MeasureParams{" 12799 + Integer.toHexString(System.identityHashCode(this)) 12800 + " " + mStats.packageName + "}"; 12801 } 12802 12803 @Override 12804 void handleStartCopy() throws RemoteException { 12805 synchronized (mInstallLock) { 12806 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12807 } 12808 12809 if (mSuccess) { 12810 boolean mounted = false; 12811 try { 12812 final String status = Environment.getExternalStorageState(); 12813 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12814 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12815 } catch (Exception e) { 12816 } 12817 12818 if (mounted) { 12819 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12820 12821 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12822 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12823 12824 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12825 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12826 12827 // Always subtract cache size, since it's a subdirectory 12828 mStats.externalDataSize -= mStats.externalCacheSize; 12829 12830 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12831 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12832 12833 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12834 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12835 } 12836 } 12837 } 12838 12839 @Override 12840 void handleReturnCode() { 12841 if (mObserver != null) { 12842 try { 12843 mObserver.onGetStatsCompleted(mStats, mSuccess); 12844 } catch (RemoteException e) { 12845 Slog.i(TAG, "Observer no longer exists."); 12846 } 12847 } 12848 } 12849 12850 @Override 12851 void handleServiceError() { 12852 Slog.e(TAG, "Could not measure application " + mStats.packageName 12853 + " external storage"); 12854 } 12855 } 12856 12857 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12858 throws RemoteException { 12859 long result = 0; 12860 for (File path : paths) { 12861 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12862 } 12863 return result; 12864 } 12865 12866 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12867 for (File path : paths) { 12868 try { 12869 mcs.clearDirectory(path.getAbsolutePath()); 12870 } catch (RemoteException e) { 12871 } 12872 } 12873 } 12874 12875 static class OriginInfo { 12876 /** 12877 * Location where install is coming from, before it has been 12878 * copied/renamed into place. This could be a single monolithic APK 12879 * file, or a cluster directory. This location may be untrusted. 12880 */ 12881 final File file; 12882 final String cid; 12883 12884 /** 12885 * Flag indicating that {@link #file} or {@link #cid} has already been 12886 * staged, meaning downstream users don't need to defensively copy the 12887 * contents. 12888 */ 12889 final boolean staged; 12890 12891 /** 12892 * Flag indicating that {@link #file} or {@link #cid} is an already 12893 * installed app that is being moved. 12894 */ 12895 final boolean existing; 12896 12897 final String resolvedPath; 12898 final File resolvedFile; 12899 12900 static OriginInfo fromNothing() { 12901 return new OriginInfo(null, null, false, false); 12902 } 12903 12904 static OriginInfo fromUntrustedFile(File file) { 12905 return new OriginInfo(file, null, false, false); 12906 } 12907 12908 static OriginInfo fromExistingFile(File file) { 12909 return new OriginInfo(file, null, false, true); 12910 } 12911 12912 static OriginInfo fromStagedFile(File file) { 12913 return new OriginInfo(file, null, true, false); 12914 } 12915 12916 static OriginInfo fromStagedContainer(String cid) { 12917 return new OriginInfo(null, cid, true, false); 12918 } 12919 12920 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12921 this.file = file; 12922 this.cid = cid; 12923 this.staged = staged; 12924 this.existing = existing; 12925 12926 if (cid != null) { 12927 resolvedPath = PackageHelper.getSdDir(cid); 12928 resolvedFile = new File(resolvedPath); 12929 } else if (file != null) { 12930 resolvedPath = file.getAbsolutePath(); 12931 resolvedFile = file; 12932 } else { 12933 resolvedPath = null; 12934 resolvedFile = null; 12935 } 12936 } 12937 } 12938 12939 static class MoveInfo { 12940 final int moveId; 12941 final String fromUuid; 12942 final String toUuid; 12943 final String packageName; 12944 final String dataAppName; 12945 final int appId; 12946 final String seinfo; 12947 final int targetSdkVersion; 12948 12949 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12950 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12951 this.moveId = moveId; 12952 this.fromUuid = fromUuid; 12953 this.toUuid = toUuid; 12954 this.packageName = packageName; 12955 this.dataAppName = dataAppName; 12956 this.appId = appId; 12957 this.seinfo = seinfo; 12958 this.targetSdkVersion = targetSdkVersion; 12959 } 12960 } 12961 12962 static class VerificationInfo { 12963 /** A constant used to indicate that a uid value is not present. */ 12964 public static final int NO_UID = -1; 12965 12966 /** URI referencing where the package was downloaded from. */ 12967 final Uri originatingUri; 12968 12969 /** HTTP referrer URI associated with the originatingURI. */ 12970 final Uri referrer; 12971 12972 /** UID of the application that the install request originated from. */ 12973 final int originatingUid; 12974 12975 /** UID of application requesting the install */ 12976 final int installerUid; 12977 12978 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12979 this.originatingUri = originatingUri; 12980 this.referrer = referrer; 12981 this.originatingUid = originatingUid; 12982 this.installerUid = installerUid; 12983 } 12984 } 12985 12986 class InstallParams extends HandlerParams { 12987 final OriginInfo origin; 12988 final MoveInfo move; 12989 final IPackageInstallObserver2 observer; 12990 int installFlags; 12991 final String installerPackageName; 12992 final String volumeUuid; 12993 private InstallArgs mArgs; 12994 private int mRet; 12995 final String packageAbiOverride; 12996 final String[] grantedRuntimePermissions; 12997 final VerificationInfo verificationInfo; 12998 final Certificate[][] certificates; 12999 13000 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13001 int installFlags, String installerPackageName, String volumeUuid, 13002 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 13003 String[] grantedPermissions, Certificate[][] certificates) { 13004 super(user); 13005 this.origin = origin; 13006 this.move = move; 13007 this.observer = observer; 13008 this.installFlags = installFlags; 13009 this.installerPackageName = installerPackageName; 13010 this.volumeUuid = volumeUuid; 13011 this.verificationInfo = verificationInfo; 13012 this.packageAbiOverride = packageAbiOverride; 13013 this.grantedRuntimePermissions = grantedPermissions; 13014 this.certificates = certificates; 13015 } 13016 13017 @Override 13018 public String toString() { 13019 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 13020 + " file=" + origin.file + " cid=" + origin.cid + "}"; 13021 } 13022 13023 private int installLocationPolicy(PackageInfoLite pkgLite) { 13024 String packageName = pkgLite.packageName; 13025 int installLocation = pkgLite.installLocation; 13026 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13027 // reader 13028 synchronized (mPackages) { 13029 // Currently installed package which the new package is attempting to replace or 13030 // null if no such package is installed. 13031 PackageParser.Package installedPkg = mPackages.get(packageName); 13032 // Package which currently owns the data which the new package will own if installed. 13033 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 13034 // will be null whereas dataOwnerPkg will contain information about the package 13035 // which was uninstalled while keeping its data. 13036 PackageParser.Package dataOwnerPkg = installedPkg; 13037 if (dataOwnerPkg == null) { 13038 PackageSetting ps = mSettings.mPackages.get(packageName); 13039 if (ps != null) { 13040 dataOwnerPkg = ps.pkg; 13041 } 13042 } 13043 13044 if (dataOwnerPkg != null) { 13045 // If installed, the package will get access to data left on the device by its 13046 // predecessor. As a security measure, this is permited only if this is not a 13047 // version downgrade or if the predecessor package is marked as debuggable and 13048 // a downgrade is explicitly requested. 13049 // 13050 // On debuggable platform builds, downgrades are permitted even for 13051 // non-debuggable packages to make testing easier. Debuggable platform builds do 13052 // not offer security guarantees and thus it's OK to disable some security 13053 // mechanisms to make debugging/testing easier on those builds. However, even on 13054 // debuggable builds downgrades of packages are permitted only if requested via 13055 // installFlags. This is because we aim to keep the behavior of debuggable 13056 // platform builds as close as possible to the behavior of non-debuggable 13057 // platform builds. 13058 final boolean downgradeRequested = 13059 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 13060 final boolean packageDebuggable = 13061 (dataOwnerPkg.applicationInfo.flags 13062 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 13063 final boolean downgradePermitted = 13064 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 13065 if (!downgradePermitted) { 13066 try { 13067 checkDowngrade(dataOwnerPkg, pkgLite); 13068 } catch (PackageManagerException e) { 13069 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 13070 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 13071 } 13072 } 13073 } 13074 13075 if (installedPkg != null) { 13076 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13077 // Check for updated system application. 13078 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13079 if (onSd) { 13080 Slog.w(TAG, "Cannot install update to system app on sdcard"); 13081 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 13082 } 13083 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13084 } else { 13085 if (onSd) { 13086 // Install flag overrides everything. 13087 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13088 } 13089 // If current upgrade specifies particular preference 13090 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 13091 // Application explicitly specified internal. 13092 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13093 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 13094 // App explictly prefers external. Let policy decide 13095 } else { 13096 // Prefer previous location 13097 if (isExternal(installedPkg)) { 13098 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13099 } 13100 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13101 } 13102 } 13103 } else { 13104 // Invalid install. Return error code 13105 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 13106 } 13107 } 13108 } 13109 // All the special cases have been taken care of. 13110 // Return result based on recommended install location. 13111 if (onSd) { 13112 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13113 } 13114 return pkgLite.recommendedInstallLocation; 13115 } 13116 13117 /* 13118 * Invoke remote method to get package information and install 13119 * location values. Override install location based on default 13120 * policy if needed and then create install arguments based 13121 * on the install location. 13122 */ 13123 public void handleStartCopy() throws RemoteException { 13124 int ret = PackageManager.INSTALL_SUCCEEDED; 13125 13126 // If we're already staged, we've firmly committed to an install location 13127 if (origin.staged) { 13128 if (origin.file != null) { 13129 installFlags |= PackageManager.INSTALL_INTERNAL; 13130 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13131 } else if (origin.cid != null) { 13132 installFlags |= PackageManager.INSTALL_EXTERNAL; 13133 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13134 } else { 13135 throw new IllegalStateException("Invalid stage location"); 13136 } 13137 } 13138 13139 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13140 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 13141 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13142 PackageInfoLite pkgLite = null; 13143 13144 if (onInt && onSd) { 13145 // Check if both bits are set. 13146 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 13147 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13148 } else if (onSd && ephemeral) { 13149 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 13150 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13151 } else { 13152 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 13153 packageAbiOverride); 13154 13155 if (DEBUG_EPHEMERAL && ephemeral) { 13156 Slog.v(TAG, "pkgLite for install: " + pkgLite); 13157 } 13158 13159 /* 13160 * If we have too little free space, try to free cache 13161 * before giving up. 13162 */ 13163 if (!origin.staged && pkgLite.recommendedInstallLocation 13164 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13165 // TODO: focus freeing disk space on the target device 13166 final StorageManager storage = StorageManager.from(mContext); 13167 final long lowThreshold = storage.getStorageLowBytes( 13168 Environment.getDataDirectory()); 13169 13170 final long sizeBytes = mContainerService.calculateInstalledSize( 13171 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 13172 13173 try { 13174 mInstaller.freeCache(null, sizeBytes + lowThreshold); 13175 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 13176 installFlags, packageAbiOverride); 13177 } catch (InstallerException e) { 13178 Slog.w(TAG, "Failed to free cache", e); 13179 } 13180 13181 /* 13182 * The cache free must have deleted the file we 13183 * downloaded to install. 13184 * 13185 * TODO: fix the "freeCache" call to not delete 13186 * the file we care about. 13187 */ 13188 if (pkgLite.recommendedInstallLocation 13189 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13190 pkgLite.recommendedInstallLocation 13191 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 13192 } 13193 } 13194 } 13195 13196 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13197 int loc = pkgLite.recommendedInstallLocation; 13198 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13199 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13200 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13201 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13202 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13203 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13204 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13205 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13206 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13207 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13208 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13209 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13210 } else { 13211 // Override with defaults if needed. 13212 loc = installLocationPolicy(pkgLite); 13213 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13214 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13215 } else if (!onSd && !onInt) { 13216 // Override install location with flags 13217 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13218 // Set the flag to install on external media. 13219 installFlags |= PackageManager.INSTALL_EXTERNAL; 13220 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13221 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13222 if (DEBUG_EPHEMERAL) { 13223 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13224 } 13225 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13226 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13227 |PackageManager.INSTALL_INTERNAL); 13228 } else { 13229 // Make sure the flag for installing on external 13230 // media is unset 13231 installFlags |= PackageManager.INSTALL_INTERNAL; 13232 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13233 } 13234 } 13235 } 13236 } 13237 13238 final InstallArgs args = createInstallArgs(this); 13239 mArgs = args; 13240 13241 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13242 // TODO: http://b/22976637 13243 // Apps installed for "all" users use the device owner to verify the app 13244 UserHandle verifierUser = getUser(); 13245 if (verifierUser == UserHandle.ALL) { 13246 verifierUser = UserHandle.SYSTEM; 13247 } 13248 13249 /* 13250 * Determine if we have any installed package verifiers. If we 13251 * do, then we'll defer to them to verify the packages. 13252 */ 13253 final int requiredUid = mRequiredVerifierPackage == null ? -1 13254 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13255 verifierUser.getIdentifier()); 13256 if (!origin.existing && requiredUid != -1 13257 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13258 final Intent verification = new Intent( 13259 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13260 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13261 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13262 PACKAGE_MIME_TYPE); 13263 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13264 13265 // Query all live verifiers based on current user state 13266 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13267 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13268 13269 if (DEBUG_VERIFY) { 13270 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13271 + verification.toString() + " with " + pkgLite.verifiers.length 13272 + " optional verifiers"); 13273 } 13274 13275 final int verificationId = mPendingVerificationToken++; 13276 13277 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13278 13279 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13280 installerPackageName); 13281 13282 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13283 installFlags); 13284 13285 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13286 pkgLite.packageName); 13287 13288 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13289 pkgLite.versionCode); 13290 13291 if (verificationInfo != null) { 13292 if (verificationInfo.originatingUri != null) { 13293 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13294 verificationInfo.originatingUri); 13295 } 13296 if (verificationInfo.referrer != null) { 13297 verification.putExtra(Intent.EXTRA_REFERRER, 13298 verificationInfo.referrer); 13299 } 13300 if (verificationInfo.originatingUid >= 0) { 13301 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13302 verificationInfo.originatingUid); 13303 } 13304 if (verificationInfo.installerUid >= 0) { 13305 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13306 verificationInfo.installerUid); 13307 } 13308 } 13309 13310 final PackageVerificationState verificationState = new PackageVerificationState( 13311 requiredUid, args); 13312 13313 mPendingVerification.append(verificationId, verificationState); 13314 13315 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13316 receivers, verificationState); 13317 13318 /* 13319 * If any sufficient verifiers were listed in the package 13320 * manifest, attempt to ask them. 13321 */ 13322 if (sufficientVerifiers != null) { 13323 final int N = sufficientVerifiers.size(); 13324 if (N == 0) { 13325 Slog.i(TAG, "Additional verifiers required, but none installed."); 13326 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13327 } else { 13328 for (int i = 0; i < N; i++) { 13329 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13330 13331 final Intent sufficientIntent = new Intent(verification); 13332 sufficientIntent.setComponent(verifierComponent); 13333 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13334 } 13335 } 13336 } 13337 13338 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13339 mRequiredVerifierPackage, receivers); 13340 if (ret == PackageManager.INSTALL_SUCCEEDED 13341 && mRequiredVerifierPackage != null) { 13342 Trace.asyncTraceBegin( 13343 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13344 /* 13345 * Send the intent to the required verification agent, 13346 * but only start the verification timeout after the 13347 * target BroadcastReceivers have run. 13348 */ 13349 verification.setComponent(requiredVerifierComponent); 13350 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13351 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13352 new BroadcastReceiver() { 13353 @Override 13354 public void onReceive(Context context, Intent intent) { 13355 final Message msg = mHandler 13356 .obtainMessage(CHECK_PENDING_VERIFICATION); 13357 msg.arg1 = verificationId; 13358 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13359 } 13360 }, null, 0, null, null); 13361 13362 /* 13363 * We don't want the copy to proceed until verification 13364 * succeeds, so null out this field. 13365 */ 13366 mArgs = null; 13367 } 13368 } else { 13369 /* 13370 * No package verification is enabled, so immediately start 13371 * the remote call to initiate copy using temporary file. 13372 */ 13373 ret = args.copyApk(mContainerService, true); 13374 } 13375 } 13376 13377 mRet = ret; 13378 } 13379 13380 @Override 13381 void handleReturnCode() { 13382 // If mArgs is null, then MCS couldn't be reached. When it 13383 // reconnects, it will try again to install. At that point, this 13384 // will succeed. 13385 if (mArgs != null) { 13386 processPendingInstall(mArgs, mRet); 13387 } 13388 } 13389 13390 @Override 13391 void handleServiceError() { 13392 mArgs = createInstallArgs(this); 13393 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13394 } 13395 13396 public boolean isForwardLocked() { 13397 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13398 } 13399 } 13400 13401 /** 13402 * Used during creation of InstallArgs 13403 * 13404 * @param installFlags package installation flags 13405 * @return true if should be installed on external storage 13406 */ 13407 private static boolean installOnExternalAsec(int installFlags) { 13408 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13409 return false; 13410 } 13411 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13412 return true; 13413 } 13414 return false; 13415 } 13416 13417 /** 13418 * Used during creation of InstallArgs 13419 * 13420 * @param installFlags package installation flags 13421 * @return true if should be installed as forward locked 13422 */ 13423 private static boolean installForwardLocked(int installFlags) { 13424 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13425 } 13426 13427 private InstallArgs createInstallArgs(InstallParams params) { 13428 if (params.move != null) { 13429 return new MoveInstallArgs(params); 13430 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13431 return new AsecInstallArgs(params); 13432 } else { 13433 return new FileInstallArgs(params); 13434 } 13435 } 13436 13437 /** 13438 * Create args that describe an existing installed package. Typically used 13439 * when cleaning up old installs, or used as a move source. 13440 */ 13441 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13442 String resourcePath, String[] instructionSets) { 13443 final boolean isInAsec; 13444 if (installOnExternalAsec(installFlags)) { 13445 /* Apps on SD card are always in ASEC containers. */ 13446 isInAsec = true; 13447 } else if (installForwardLocked(installFlags) 13448 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13449 /* 13450 * Forward-locked apps are only in ASEC containers if they're the 13451 * new style 13452 */ 13453 isInAsec = true; 13454 } else { 13455 isInAsec = false; 13456 } 13457 13458 if (isInAsec) { 13459 return new AsecInstallArgs(codePath, instructionSets, 13460 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13461 } else { 13462 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13463 } 13464 } 13465 13466 static abstract class InstallArgs { 13467 /** @see InstallParams#origin */ 13468 final OriginInfo origin; 13469 /** @see InstallParams#move */ 13470 final MoveInfo move; 13471 13472 final IPackageInstallObserver2 observer; 13473 // Always refers to PackageManager flags only 13474 final int installFlags; 13475 final String installerPackageName; 13476 final String volumeUuid; 13477 final UserHandle user; 13478 final String abiOverride; 13479 final String[] installGrantPermissions; 13480 /** If non-null, drop an async trace when the install completes */ 13481 final String traceMethod; 13482 final int traceCookie; 13483 final Certificate[][] certificates; 13484 13485 // The list of instruction sets supported by this app. This is currently 13486 // only used during the rmdex() phase to clean up resources. We can get rid of this 13487 // if we move dex files under the common app path. 13488 /* nullable */ String[] instructionSets; 13489 13490 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13491 int installFlags, String installerPackageName, String volumeUuid, 13492 UserHandle user, String[] instructionSets, 13493 String abiOverride, String[] installGrantPermissions, 13494 String traceMethod, int traceCookie, Certificate[][] certificates) { 13495 this.origin = origin; 13496 this.move = move; 13497 this.installFlags = installFlags; 13498 this.observer = observer; 13499 this.installerPackageName = installerPackageName; 13500 this.volumeUuid = volumeUuid; 13501 this.user = user; 13502 this.instructionSets = instructionSets; 13503 this.abiOverride = abiOverride; 13504 this.installGrantPermissions = installGrantPermissions; 13505 this.traceMethod = traceMethod; 13506 this.traceCookie = traceCookie; 13507 this.certificates = certificates; 13508 } 13509 13510 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13511 abstract int doPreInstall(int status); 13512 13513 /** 13514 * Rename package into final resting place. All paths on the given 13515 * scanned package should be updated to reflect the rename. 13516 */ 13517 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13518 abstract int doPostInstall(int status, int uid); 13519 13520 /** @see PackageSettingBase#codePathString */ 13521 abstract String getCodePath(); 13522 /** @see PackageSettingBase#resourcePathString */ 13523 abstract String getResourcePath(); 13524 13525 // Need installer lock especially for dex file removal. 13526 abstract void cleanUpResourcesLI(); 13527 abstract boolean doPostDeleteLI(boolean delete); 13528 13529 /** 13530 * Called before the source arguments are copied. This is used mostly 13531 * for MoveParams when it needs to read the source file to put it in the 13532 * destination. 13533 */ 13534 int doPreCopy() { 13535 return PackageManager.INSTALL_SUCCEEDED; 13536 } 13537 13538 /** 13539 * Called after the source arguments are copied. This is used mostly for 13540 * MoveParams when it needs to read the source file to put it in the 13541 * destination. 13542 */ 13543 int doPostCopy(int uid) { 13544 return PackageManager.INSTALL_SUCCEEDED; 13545 } 13546 13547 protected boolean isFwdLocked() { 13548 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13549 } 13550 13551 protected boolean isExternalAsec() { 13552 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13553 } 13554 13555 protected boolean isEphemeral() { 13556 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13557 } 13558 13559 UserHandle getUser() { 13560 return user; 13561 } 13562 } 13563 13564 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13565 if (!allCodePaths.isEmpty()) { 13566 if (instructionSets == null) { 13567 throw new IllegalStateException("instructionSet == null"); 13568 } 13569 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13570 for (String codePath : allCodePaths) { 13571 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13572 try { 13573 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13574 } catch (InstallerException ignored) { 13575 } 13576 } 13577 } 13578 } 13579 } 13580 13581 /** 13582 * Logic to handle installation of non-ASEC applications, including copying 13583 * and renaming logic. 13584 */ 13585 class FileInstallArgs extends InstallArgs { 13586 private File codeFile; 13587 private File resourceFile; 13588 13589 // Example topology: 13590 // /data/app/com.example/base.apk 13591 // /data/app/com.example/split_foo.apk 13592 // /data/app/com.example/lib/arm/libfoo.so 13593 // /data/app/com.example/lib/arm64/libfoo.so 13594 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13595 13596 /** New install */ 13597 FileInstallArgs(InstallParams params) { 13598 super(params.origin, params.move, params.observer, params.installFlags, 13599 params.installerPackageName, params.volumeUuid, 13600 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13601 params.grantedRuntimePermissions, 13602 params.traceMethod, params.traceCookie, params.certificates); 13603 if (isFwdLocked()) { 13604 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13605 } 13606 } 13607 13608 /** Existing install */ 13609 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13610 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13611 null, null, null, 0, null /*certificates*/); 13612 this.codeFile = (codePath != null) ? new File(codePath) : null; 13613 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13614 } 13615 13616 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13617 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13618 try { 13619 return doCopyApk(imcs, temp); 13620 } finally { 13621 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13622 } 13623 } 13624 13625 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13626 if (origin.staged) { 13627 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13628 codeFile = origin.file; 13629 resourceFile = origin.file; 13630 return PackageManager.INSTALL_SUCCEEDED; 13631 } 13632 13633 try { 13634 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13635 final File tempDir = 13636 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13637 codeFile = tempDir; 13638 resourceFile = tempDir; 13639 } catch (IOException e) { 13640 Slog.w(TAG, "Failed to create copy file: " + e); 13641 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13642 } 13643 13644 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13645 @Override 13646 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13647 if (!FileUtils.isValidExtFilename(name)) { 13648 throw new IllegalArgumentException("Invalid filename: " + name); 13649 } 13650 try { 13651 final File file = new File(codeFile, name); 13652 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13653 O_RDWR | O_CREAT, 0644); 13654 Os.chmod(file.getAbsolutePath(), 0644); 13655 return new ParcelFileDescriptor(fd); 13656 } catch (ErrnoException e) { 13657 throw new RemoteException("Failed to open: " + e.getMessage()); 13658 } 13659 } 13660 }; 13661 13662 int ret = PackageManager.INSTALL_SUCCEEDED; 13663 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13664 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13665 Slog.e(TAG, "Failed to copy package"); 13666 return ret; 13667 } 13668 13669 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13670 NativeLibraryHelper.Handle handle = null; 13671 try { 13672 handle = NativeLibraryHelper.Handle.create(codeFile); 13673 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13674 abiOverride); 13675 } catch (IOException e) { 13676 Slog.e(TAG, "Copying native libraries failed", e); 13677 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13678 } finally { 13679 IoUtils.closeQuietly(handle); 13680 } 13681 13682 return ret; 13683 } 13684 13685 int doPreInstall(int status) { 13686 if (status != PackageManager.INSTALL_SUCCEEDED) { 13687 cleanUp(); 13688 } 13689 return status; 13690 } 13691 13692 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13693 if (status != PackageManager.INSTALL_SUCCEEDED) { 13694 cleanUp(); 13695 return false; 13696 } 13697 13698 final File targetDir = codeFile.getParentFile(); 13699 final File beforeCodeFile = codeFile; 13700 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13701 13702 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13703 try { 13704 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13705 } catch (ErrnoException e) { 13706 Slog.w(TAG, "Failed to rename", e); 13707 return false; 13708 } 13709 13710 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13711 Slog.w(TAG, "Failed to restorecon"); 13712 return false; 13713 } 13714 13715 // Reflect the rename internally 13716 codeFile = afterCodeFile; 13717 resourceFile = afterCodeFile; 13718 13719 // Reflect the rename in scanned details 13720 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13721 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13722 afterCodeFile, pkg.baseCodePath)); 13723 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13724 afterCodeFile, pkg.splitCodePaths)); 13725 13726 // Reflect the rename in app info 13727 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13728 pkg.setApplicationInfoCodePath(pkg.codePath); 13729 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13730 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13731 pkg.setApplicationInfoResourcePath(pkg.codePath); 13732 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13733 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13734 13735 return true; 13736 } 13737 13738 int doPostInstall(int status, int uid) { 13739 if (status != PackageManager.INSTALL_SUCCEEDED) { 13740 cleanUp(); 13741 } 13742 return status; 13743 } 13744 13745 @Override 13746 String getCodePath() { 13747 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13748 } 13749 13750 @Override 13751 String getResourcePath() { 13752 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13753 } 13754 13755 private boolean cleanUp() { 13756 if (codeFile == null || !codeFile.exists()) { 13757 return false; 13758 } 13759 13760 removeCodePathLI(codeFile); 13761 13762 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13763 resourceFile.delete(); 13764 } 13765 13766 return true; 13767 } 13768 13769 void cleanUpResourcesLI() { 13770 // Try enumerating all code paths before deleting 13771 List<String> allCodePaths = Collections.EMPTY_LIST; 13772 if (codeFile != null && codeFile.exists()) { 13773 try { 13774 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13775 allCodePaths = pkg.getAllCodePaths(); 13776 } catch (PackageParserException e) { 13777 // Ignored; we tried our best 13778 } 13779 } 13780 13781 cleanUp(); 13782 removeDexFiles(allCodePaths, instructionSets); 13783 } 13784 13785 boolean doPostDeleteLI(boolean delete) { 13786 // XXX err, shouldn't we respect the delete flag? 13787 cleanUpResourcesLI(); 13788 return true; 13789 } 13790 } 13791 13792 private boolean isAsecExternal(String cid) { 13793 final String asecPath = PackageHelper.getSdFilesystem(cid); 13794 return !asecPath.startsWith(mAsecInternalPath); 13795 } 13796 13797 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13798 PackageManagerException { 13799 if (copyRet < 0) { 13800 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13801 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13802 throw new PackageManagerException(copyRet, message); 13803 } 13804 } 13805 } 13806 13807 /** 13808 * Extract the StorageManagerService "container ID" from the full code path of an 13809 * .apk. 13810 */ 13811 static String cidFromCodePath(String fullCodePath) { 13812 int eidx = fullCodePath.lastIndexOf("/"); 13813 String subStr1 = fullCodePath.substring(0, eidx); 13814 int sidx = subStr1.lastIndexOf("/"); 13815 return subStr1.substring(sidx+1, eidx); 13816 } 13817 13818 /** 13819 * Logic to handle installation of ASEC applications, including copying and 13820 * renaming logic. 13821 */ 13822 class AsecInstallArgs extends InstallArgs { 13823 static final String RES_FILE_NAME = "pkg.apk"; 13824 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13825 13826 String cid; 13827 String packagePath; 13828 String resourcePath; 13829 13830 /** New install */ 13831 AsecInstallArgs(InstallParams params) { 13832 super(params.origin, params.move, params.observer, params.installFlags, 13833 params.installerPackageName, params.volumeUuid, 13834 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13835 params.grantedRuntimePermissions, 13836 params.traceMethod, params.traceCookie, params.certificates); 13837 } 13838 13839 /** Existing install */ 13840 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13841 boolean isExternal, boolean isForwardLocked) { 13842 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13843 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13844 instructionSets, null, null, null, 0, null /*certificates*/); 13845 // Hackily pretend we're still looking at a full code path 13846 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13847 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13848 } 13849 13850 // Extract cid from fullCodePath 13851 int eidx = fullCodePath.lastIndexOf("/"); 13852 String subStr1 = fullCodePath.substring(0, eidx); 13853 int sidx = subStr1.lastIndexOf("/"); 13854 cid = subStr1.substring(sidx+1, eidx); 13855 setMountPath(subStr1); 13856 } 13857 13858 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13859 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13860 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13861 instructionSets, null, null, null, 0, null /*certificates*/); 13862 this.cid = cid; 13863 setMountPath(PackageHelper.getSdDir(cid)); 13864 } 13865 13866 void createCopyFile() { 13867 cid = mInstallerService.allocateExternalStageCidLegacy(); 13868 } 13869 13870 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13871 if (origin.staged && origin.cid != null) { 13872 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13873 cid = origin.cid; 13874 setMountPath(PackageHelper.getSdDir(cid)); 13875 return PackageManager.INSTALL_SUCCEEDED; 13876 } 13877 13878 if (temp) { 13879 createCopyFile(); 13880 } else { 13881 /* 13882 * Pre-emptively destroy the container since it's destroyed if 13883 * copying fails due to it existing anyway. 13884 */ 13885 PackageHelper.destroySdDir(cid); 13886 } 13887 13888 final String newMountPath = imcs.copyPackageToContainer( 13889 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13890 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13891 13892 if (newMountPath != null) { 13893 setMountPath(newMountPath); 13894 return PackageManager.INSTALL_SUCCEEDED; 13895 } else { 13896 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13897 } 13898 } 13899 13900 @Override 13901 String getCodePath() { 13902 return packagePath; 13903 } 13904 13905 @Override 13906 String getResourcePath() { 13907 return resourcePath; 13908 } 13909 13910 int doPreInstall(int status) { 13911 if (status != PackageManager.INSTALL_SUCCEEDED) { 13912 // Destroy container 13913 PackageHelper.destroySdDir(cid); 13914 } else { 13915 boolean mounted = PackageHelper.isContainerMounted(cid); 13916 if (!mounted) { 13917 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13918 Process.SYSTEM_UID); 13919 if (newMountPath != null) { 13920 setMountPath(newMountPath); 13921 } else { 13922 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13923 } 13924 } 13925 } 13926 return status; 13927 } 13928 13929 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13930 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13931 String newMountPath = null; 13932 if (PackageHelper.isContainerMounted(cid)) { 13933 // Unmount the container 13934 if (!PackageHelper.unMountSdDir(cid)) { 13935 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13936 return false; 13937 } 13938 } 13939 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13940 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13941 " which might be stale. Will try to clean up."); 13942 // Clean up the stale container and proceed to recreate. 13943 if (!PackageHelper.destroySdDir(newCacheId)) { 13944 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13945 return false; 13946 } 13947 // Successfully cleaned up stale container. Try to rename again. 13948 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13949 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13950 + " inspite of cleaning it up."); 13951 return false; 13952 } 13953 } 13954 if (!PackageHelper.isContainerMounted(newCacheId)) { 13955 Slog.w(TAG, "Mounting container " + newCacheId); 13956 newMountPath = PackageHelper.mountSdDir(newCacheId, 13957 getEncryptKey(), Process.SYSTEM_UID); 13958 } else { 13959 newMountPath = PackageHelper.getSdDir(newCacheId); 13960 } 13961 if (newMountPath == null) { 13962 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13963 return false; 13964 } 13965 Log.i(TAG, "Succesfully renamed " + cid + 13966 " to " + newCacheId + 13967 " at new path: " + newMountPath); 13968 cid = newCacheId; 13969 13970 final File beforeCodeFile = new File(packagePath); 13971 setMountPath(newMountPath); 13972 final File afterCodeFile = new File(packagePath); 13973 13974 // Reflect the rename in scanned details 13975 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13976 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13977 afterCodeFile, pkg.baseCodePath)); 13978 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13979 afterCodeFile, pkg.splitCodePaths)); 13980 13981 // Reflect the rename in app info 13982 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13983 pkg.setApplicationInfoCodePath(pkg.codePath); 13984 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13985 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13986 pkg.setApplicationInfoResourcePath(pkg.codePath); 13987 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13988 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13989 13990 return true; 13991 } 13992 13993 private void setMountPath(String mountPath) { 13994 final File mountFile = new File(mountPath); 13995 13996 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13997 if (monolithicFile.exists()) { 13998 packagePath = monolithicFile.getAbsolutePath(); 13999 if (isFwdLocked()) { 14000 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 14001 } else { 14002 resourcePath = packagePath; 14003 } 14004 } else { 14005 packagePath = mountFile.getAbsolutePath(); 14006 resourcePath = packagePath; 14007 } 14008 } 14009 14010 int doPostInstall(int status, int uid) { 14011 if (status != PackageManager.INSTALL_SUCCEEDED) { 14012 cleanUp(); 14013 } else { 14014 final int groupOwner; 14015 final String protectedFile; 14016 if (isFwdLocked()) { 14017 groupOwner = UserHandle.getSharedAppGid(uid); 14018 protectedFile = RES_FILE_NAME; 14019 } else { 14020 groupOwner = -1; 14021 protectedFile = null; 14022 } 14023 14024 if (uid < Process.FIRST_APPLICATION_UID 14025 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 14026 Slog.e(TAG, "Failed to finalize " + cid); 14027 PackageHelper.destroySdDir(cid); 14028 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14029 } 14030 14031 boolean mounted = PackageHelper.isContainerMounted(cid); 14032 if (!mounted) { 14033 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 14034 } 14035 } 14036 return status; 14037 } 14038 14039 private void cleanUp() { 14040 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 14041 14042 // Destroy secure container 14043 PackageHelper.destroySdDir(cid); 14044 } 14045 14046 private List<String> getAllCodePaths() { 14047 final File codeFile = new File(getCodePath()); 14048 if (codeFile != null && codeFile.exists()) { 14049 try { 14050 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14051 return pkg.getAllCodePaths(); 14052 } catch (PackageParserException e) { 14053 // Ignored; we tried our best 14054 } 14055 } 14056 return Collections.EMPTY_LIST; 14057 } 14058 14059 void cleanUpResourcesLI() { 14060 // Enumerate all code paths before deleting 14061 cleanUpResourcesLI(getAllCodePaths()); 14062 } 14063 14064 private void cleanUpResourcesLI(List<String> allCodePaths) { 14065 cleanUp(); 14066 removeDexFiles(allCodePaths, instructionSets); 14067 } 14068 14069 String getPackageName() { 14070 return getAsecPackageName(cid); 14071 } 14072 14073 boolean doPostDeleteLI(boolean delete) { 14074 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 14075 final List<String> allCodePaths = getAllCodePaths(); 14076 boolean mounted = PackageHelper.isContainerMounted(cid); 14077 if (mounted) { 14078 // Unmount first 14079 if (PackageHelper.unMountSdDir(cid)) { 14080 mounted = false; 14081 } 14082 } 14083 if (!mounted && delete) { 14084 cleanUpResourcesLI(allCodePaths); 14085 } 14086 return !mounted; 14087 } 14088 14089 @Override 14090 int doPreCopy() { 14091 if (isFwdLocked()) { 14092 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 14093 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 14094 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14095 } 14096 } 14097 14098 return PackageManager.INSTALL_SUCCEEDED; 14099 } 14100 14101 @Override 14102 int doPostCopy(int uid) { 14103 if (isFwdLocked()) { 14104 if (uid < Process.FIRST_APPLICATION_UID 14105 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 14106 RES_FILE_NAME)) { 14107 Slog.e(TAG, "Failed to finalize " + cid); 14108 PackageHelper.destroySdDir(cid); 14109 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14110 } 14111 } 14112 14113 return PackageManager.INSTALL_SUCCEEDED; 14114 } 14115 } 14116 14117 /** 14118 * Logic to handle movement of existing installed applications. 14119 */ 14120 class MoveInstallArgs extends InstallArgs { 14121 private File codeFile; 14122 private File resourceFile; 14123 14124 /** New install */ 14125 MoveInstallArgs(InstallParams params) { 14126 super(params.origin, params.move, params.observer, params.installFlags, 14127 params.installerPackageName, params.volumeUuid, 14128 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14129 params.grantedRuntimePermissions, 14130 params.traceMethod, params.traceCookie, params.certificates); 14131 } 14132 14133 int copyApk(IMediaContainerService imcs, boolean temp) { 14134 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 14135 + move.fromUuid + " to " + move.toUuid); 14136 synchronized (mInstaller) { 14137 try { 14138 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 14139 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 14140 } catch (InstallerException e) { 14141 Slog.w(TAG, "Failed to move app", e); 14142 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14143 } 14144 } 14145 14146 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 14147 resourceFile = codeFile; 14148 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 14149 14150 return PackageManager.INSTALL_SUCCEEDED; 14151 } 14152 14153 int doPreInstall(int status) { 14154 if (status != PackageManager.INSTALL_SUCCEEDED) { 14155 cleanUp(move.toUuid); 14156 } 14157 return status; 14158 } 14159 14160 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14161 if (status != PackageManager.INSTALL_SUCCEEDED) { 14162 cleanUp(move.toUuid); 14163 return false; 14164 } 14165 14166 // Reflect the move in app info 14167 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14168 pkg.setApplicationInfoCodePath(pkg.codePath); 14169 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14170 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14171 pkg.setApplicationInfoResourcePath(pkg.codePath); 14172 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14173 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14174 14175 return true; 14176 } 14177 14178 int doPostInstall(int status, int uid) { 14179 if (status == PackageManager.INSTALL_SUCCEEDED) { 14180 cleanUp(move.fromUuid); 14181 } else { 14182 cleanUp(move.toUuid); 14183 } 14184 return status; 14185 } 14186 14187 @Override 14188 String getCodePath() { 14189 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14190 } 14191 14192 @Override 14193 String getResourcePath() { 14194 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14195 } 14196 14197 private boolean cleanUp(String volumeUuid) { 14198 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14199 move.dataAppName); 14200 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14201 final int[] userIds = sUserManager.getUserIds(); 14202 synchronized (mInstallLock) { 14203 // Clean up both app data and code 14204 // All package moves are frozen until finished 14205 for (int userId : userIds) { 14206 try { 14207 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14208 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14209 } catch (InstallerException e) { 14210 Slog.w(TAG, String.valueOf(e)); 14211 } 14212 } 14213 removeCodePathLI(codeFile); 14214 } 14215 return true; 14216 } 14217 14218 void cleanUpResourcesLI() { 14219 throw new UnsupportedOperationException(); 14220 } 14221 14222 boolean doPostDeleteLI(boolean delete) { 14223 throw new UnsupportedOperationException(); 14224 } 14225 } 14226 14227 static String getAsecPackageName(String packageCid) { 14228 int idx = packageCid.lastIndexOf("-"); 14229 if (idx == -1) { 14230 return packageCid; 14231 } 14232 return packageCid.substring(0, idx); 14233 } 14234 14235 // Utility method used to create code paths based on package name and available index. 14236 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14237 String idxStr = ""; 14238 int idx = 1; 14239 // Fall back to default value of idx=1 if prefix is not 14240 // part of oldCodePath 14241 if (oldCodePath != null) { 14242 String subStr = oldCodePath; 14243 // Drop the suffix right away 14244 if (suffix != null && subStr.endsWith(suffix)) { 14245 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14246 } 14247 // If oldCodePath already contains prefix find out the 14248 // ending index to either increment or decrement. 14249 int sidx = subStr.lastIndexOf(prefix); 14250 if (sidx != -1) { 14251 subStr = subStr.substring(sidx + prefix.length()); 14252 if (subStr != null) { 14253 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14254 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14255 } 14256 try { 14257 idx = Integer.parseInt(subStr); 14258 if (idx <= 1) { 14259 idx++; 14260 } else { 14261 idx--; 14262 } 14263 } catch(NumberFormatException e) { 14264 } 14265 } 14266 } 14267 } 14268 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14269 return prefix + idxStr; 14270 } 14271 14272 private File getNextCodePath(File targetDir, String packageName) { 14273 File result; 14274 SecureRandom random = new SecureRandom(); 14275 byte[] bytes = new byte[16]; 14276 do { 14277 random.nextBytes(bytes); 14278 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 14279 result = new File(targetDir, packageName + "-" + suffix); 14280 } while (result.exists()); 14281 return result; 14282 } 14283 14284 // Utility method that returns the relative package path with respect 14285 // to the installation directory. Like say for /data/data/com.test-1.apk 14286 // string com.test-1 is returned. 14287 static String deriveCodePathName(String codePath) { 14288 if (codePath == null) { 14289 return null; 14290 } 14291 final File codeFile = new File(codePath); 14292 final String name = codeFile.getName(); 14293 if (codeFile.isDirectory()) { 14294 return name; 14295 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14296 final int lastDot = name.lastIndexOf('.'); 14297 return name.substring(0, lastDot); 14298 } else { 14299 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14300 return null; 14301 } 14302 } 14303 14304 static class PackageInstalledInfo { 14305 String name; 14306 int uid; 14307 // The set of users that originally had this package installed. 14308 int[] origUsers; 14309 // The set of users that now have this package installed. 14310 int[] newUsers; 14311 PackageParser.Package pkg; 14312 int returnCode; 14313 String returnMsg; 14314 PackageRemovedInfo removedInfo; 14315 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14316 14317 public void setError(int code, String msg) { 14318 setReturnCode(code); 14319 setReturnMessage(msg); 14320 Slog.w(TAG, msg); 14321 } 14322 14323 public void setError(String msg, PackageParserException e) { 14324 setReturnCode(e.error); 14325 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14326 Slog.w(TAG, msg, e); 14327 } 14328 14329 public void setError(String msg, PackageManagerException e) { 14330 returnCode = e.error; 14331 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14332 Slog.w(TAG, msg, e); 14333 } 14334 14335 public void setReturnCode(int returnCode) { 14336 this.returnCode = returnCode; 14337 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14338 for (int i = 0; i < childCount; i++) { 14339 addedChildPackages.valueAt(i).returnCode = returnCode; 14340 } 14341 } 14342 14343 private void setReturnMessage(String returnMsg) { 14344 this.returnMsg = returnMsg; 14345 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14346 for (int i = 0; i < childCount; i++) { 14347 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14348 } 14349 } 14350 14351 // In some error cases we want to convey more info back to the observer 14352 String origPackage; 14353 String origPermission; 14354 } 14355 14356 /* 14357 * Install a non-existing package. 14358 */ 14359 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14360 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14361 PackageInstalledInfo res) { 14362 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14363 14364 // Remember this for later, in case we need to rollback this install 14365 String pkgName = pkg.packageName; 14366 14367 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14368 14369 synchronized(mPackages) { 14370 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 14371 if (renamedPackage != null) { 14372 // A package with the same name is already installed, though 14373 // it has been renamed to an older name. The package we 14374 // are trying to install should be installed as an update to 14375 // the existing one, but that has not been requested, so bail. 14376 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14377 + " without first uninstalling package running as " 14378 + renamedPackage); 14379 return; 14380 } 14381 if (mPackages.containsKey(pkgName)) { 14382 // Don't allow installation over an existing package with the same name. 14383 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14384 + " without first uninstalling."); 14385 return; 14386 } 14387 } 14388 14389 try { 14390 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14391 System.currentTimeMillis(), user); 14392 14393 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14394 14395 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14396 prepareAppDataAfterInstallLIF(newPackage); 14397 14398 } else { 14399 // Remove package from internal structures, but keep around any 14400 // data that might have already existed 14401 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14402 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14403 } 14404 } catch (PackageManagerException e) { 14405 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14406 } 14407 14408 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14409 } 14410 14411 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14412 // Can't rotate keys during boot or if sharedUser. 14413 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14414 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14415 return false; 14416 } 14417 // app is using upgradeKeySets; make sure all are valid 14418 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14419 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14420 for (int i = 0; i < upgradeKeySets.length; i++) { 14421 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14422 Slog.wtf(TAG, "Package " 14423 + (oldPs.name != null ? oldPs.name : "<null>") 14424 + " contains upgrade-key-set reference to unknown key-set: " 14425 + upgradeKeySets[i] 14426 + " reverting to signatures check."); 14427 return false; 14428 } 14429 } 14430 return true; 14431 } 14432 14433 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14434 // Upgrade keysets are being used. Determine if new package has a superset of the 14435 // required keys. 14436 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14437 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14438 for (int i = 0; i < upgradeKeySets.length; i++) { 14439 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14440 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14441 return true; 14442 } 14443 } 14444 return false; 14445 } 14446 14447 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14448 try (DigestInputStream digestStream = 14449 new DigestInputStream(new FileInputStream(file), digest)) { 14450 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14451 } 14452 } 14453 14454 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14455 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14456 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14457 14458 final PackageParser.Package oldPackage; 14459 final String pkgName = pkg.packageName; 14460 final int[] allUsers; 14461 final int[] installedUsers; 14462 14463 synchronized(mPackages) { 14464 oldPackage = mPackages.get(pkgName); 14465 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14466 14467 // don't allow upgrade to target a release SDK from a pre-release SDK 14468 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14469 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14470 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14471 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14472 if (oldTargetsPreRelease 14473 && !newTargetsPreRelease 14474 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14475 Slog.w(TAG, "Can't install package targeting released sdk"); 14476 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14477 return; 14478 } 14479 14480 // don't allow an upgrade from full to ephemeral 14481 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14482 if (isEphemeral && !oldIsEphemeral) { 14483 // can't downgrade from full to ephemeral 14484 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14485 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14486 return; 14487 } 14488 14489 // verify signatures are valid 14490 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14491 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14492 if (!checkUpgradeKeySetLP(ps, pkg)) { 14493 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14494 "New package not signed by keys specified by upgrade-keysets: " 14495 + pkgName); 14496 return; 14497 } 14498 } else { 14499 // default to original signature matching 14500 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14501 != PackageManager.SIGNATURE_MATCH) { 14502 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14503 "New package has a different signature: " + pkgName); 14504 return; 14505 } 14506 } 14507 14508 // don't allow a system upgrade unless the upgrade hash matches 14509 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14510 byte[] digestBytes = null; 14511 try { 14512 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14513 updateDigest(digest, new File(pkg.baseCodePath)); 14514 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14515 for (String path : pkg.splitCodePaths) { 14516 updateDigest(digest, new File(path)); 14517 } 14518 } 14519 digestBytes = digest.digest(); 14520 } catch (NoSuchAlgorithmException | IOException e) { 14521 res.setError(INSTALL_FAILED_INVALID_APK, 14522 "Could not compute hash: " + pkgName); 14523 return; 14524 } 14525 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14526 res.setError(INSTALL_FAILED_INVALID_APK, 14527 "New package fails restrict-update check: " + pkgName); 14528 return; 14529 } 14530 // retain upgrade restriction 14531 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14532 } 14533 14534 // Check for shared user id changes 14535 String invalidPackageName = 14536 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14537 if (invalidPackageName != null) { 14538 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14539 "Package " + invalidPackageName + " tried to change user " 14540 + oldPackage.mSharedUserId); 14541 return; 14542 } 14543 14544 // In case of rollback, remember per-user/profile install state 14545 allUsers = sUserManager.getUserIds(); 14546 installedUsers = ps.queryInstalledUsers(allUsers, true); 14547 } 14548 14549 // Update what is removed 14550 res.removedInfo = new PackageRemovedInfo(); 14551 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14552 res.removedInfo.removedPackage = oldPackage.packageName; 14553 res.removedInfo.isUpdate = true; 14554 res.removedInfo.origUsers = installedUsers; 14555 final int childCount = (oldPackage.childPackages != null) 14556 ? oldPackage.childPackages.size() : 0; 14557 for (int i = 0; i < childCount; i++) { 14558 boolean childPackageUpdated = false; 14559 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14560 if (res.addedChildPackages != null) { 14561 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14562 if (childRes != null) { 14563 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14564 childRes.removedInfo.removedPackage = childPkg.packageName; 14565 childRes.removedInfo.isUpdate = true; 14566 childPackageUpdated = true; 14567 } 14568 } 14569 if (!childPackageUpdated) { 14570 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14571 childRemovedRes.removedPackage = childPkg.packageName; 14572 childRemovedRes.isUpdate = false; 14573 childRemovedRes.dataRemoved = true; 14574 synchronized (mPackages) { 14575 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 14576 if (childPs != null) { 14577 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14578 } 14579 } 14580 if (res.removedInfo.removedChildPackages == null) { 14581 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14582 } 14583 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14584 } 14585 } 14586 14587 boolean sysPkg = (isSystemApp(oldPackage)); 14588 if (sysPkg) { 14589 // Set the system/privileged flags as needed 14590 final boolean privileged = 14591 (oldPackage.applicationInfo.privateFlags 14592 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14593 final int systemPolicyFlags = policyFlags 14594 | PackageParser.PARSE_IS_SYSTEM 14595 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14596 14597 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14598 user, allUsers, installerPackageName, res); 14599 } else { 14600 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14601 user, allUsers, installerPackageName, res); 14602 } 14603 } 14604 14605 public List<String> getPreviousCodePaths(String packageName) { 14606 final PackageSetting ps = mSettings.mPackages.get(packageName); 14607 final List<String> result = new ArrayList<String>(); 14608 if (ps != null && ps.oldCodePaths != null) { 14609 result.addAll(ps.oldCodePaths); 14610 } 14611 return result; 14612 } 14613 14614 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14615 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14616 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14617 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14618 + deletedPackage); 14619 14620 String pkgName = deletedPackage.packageName; 14621 boolean deletedPkg = true; 14622 boolean addedPkg = false; 14623 boolean updatedSettings = false; 14624 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14625 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14626 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14627 14628 final long origUpdateTime = (pkg.mExtras != null) 14629 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14630 14631 // First delete the existing package while retaining the data directory 14632 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14633 res.removedInfo, true, pkg)) { 14634 // If the existing package wasn't successfully deleted 14635 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14636 deletedPkg = false; 14637 } else { 14638 // Successfully deleted the old package; proceed with replace. 14639 14640 // If deleted package lived in a container, give users a chance to 14641 // relinquish resources before killing. 14642 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14643 if (DEBUG_INSTALL) { 14644 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14645 } 14646 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14647 final ArrayList<String> pkgList = new ArrayList<String>(1); 14648 pkgList.add(deletedPackage.applicationInfo.packageName); 14649 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14650 } 14651 14652 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14653 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14654 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14655 14656 try { 14657 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14658 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14659 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14660 14661 // Update the in-memory copy of the previous code paths. 14662 PackageSetting ps = mSettings.mPackages.get(pkgName); 14663 if (!killApp) { 14664 if (ps.oldCodePaths == null) { 14665 ps.oldCodePaths = new ArraySet<>(); 14666 } 14667 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14668 if (deletedPackage.splitCodePaths != null) { 14669 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14670 } 14671 } else { 14672 ps.oldCodePaths = null; 14673 } 14674 if (ps.childPackageNames != null) { 14675 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14676 final String childPkgName = ps.childPackageNames.get(i); 14677 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14678 childPs.oldCodePaths = ps.oldCodePaths; 14679 } 14680 } 14681 prepareAppDataAfterInstallLIF(newPackage); 14682 addedPkg = true; 14683 } catch (PackageManagerException e) { 14684 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14685 } 14686 } 14687 14688 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14689 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14690 14691 // Revert all internal state mutations and added folders for the failed install 14692 if (addedPkg) { 14693 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14694 res.removedInfo, true, null); 14695 } 14696 14697 // Restore the old package 14698 if (deletedPkg) { 14699 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14700 File restoreFile = new File(deletedPackage.codePath); 14701 // Parse old package 14702 boolean oldExternal = isExternal(deletedPackage); 14703 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14704 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14705 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14706 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14707 try { 14708 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14709 null); 14710 } catch (PackageManagerException e) { 14711 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14712 + e.getMessage()); 14713 return; 14714 } 14715 14716 synchronized (mPackages) { 14717 // Ensure the installer package name up to date 14718 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14719 14720 // Update permissions for restored package 14721 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14722 14723 mSettings.writeLPr(); 14724 } 14725 14726 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14727 } 14728 } else { 14729 synchronized (mPackages) { 14730 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 14731 if (ps != null) { 14732 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14733 if (res.removedInfo.removedChildPackages != null) { 14734 final int childCount = res.removedInfo.removedChildPackages.size(); 14735 // Iterate in reverse as we may modify the collection 14736 for (int i = childCount - 1; i >= 0; i--) { 14737 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14738 if (res.addedChildPackages.containsKey(childPackageName)) { 14739 res.removedInfo.removedChildPackages.removeAt(i); 14740 } else { 14741 PackageRemovedInfo childInfo = res.removedInfo 14742 .removedChildPackages.valueAt(i); 14743 childInfo.removedForAllUsers = mPackages.get( 14744 childInfo.removedPackage) == null; 14745 } 14746 } 14747 } 14748 } 14749 } 14750 } 14751 } 14752 14753 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14754 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14755 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14756 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14757 + ", old=" + deletedPackage); 14758 14759 final boolean disabledSystem; 14760 14761 // Remove existing system package 14762 removePackageLI(deletedPackage, true); 14763 14764 synchronized (mPackages) { 14765 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14766 } 14767 if (!disabledSystem) { 14768 // We didn't need to disable the .apk as a current system package, 14769 // which means we are replacing another update that is already 14770 // installed. We need to make sure to delete the older one's .apk. 14771 res.removedInfo.args = createInstallArgsForExisting(0, 14772 deletedPackage.applicationInfo.getCodePath(), 14773 deletedPackage.applicationInfo.getResourcePath(), 14774 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14775 } else { 14776 res.removedInfo.args = null; 14777 } 14778 14779 // Successfully disabled the old package. Now proceed with re-installation 14780 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14781 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14782 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14783 14784 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14785 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14786 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14787 14788 PackageParser.Package newPackage = null; 14789 try { 14790 // Add the package to the internal data structures 14791 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14792 14793 // Set the update and install times 14794 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14795 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14796 System.currentTimeMillis()); 14797 14798 // Update the package dynamic state if succeeded 14799 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14800 // Now that the install succeeded make sure we remove data 14801 // directories for any child package the update removed. 14802 final int deletedChildCount = (deletedPackage.childPackages != null) 14803 ? deletedPackage.childPackages.size() : 0; 14804 final int newChildCount = (newPackage.childPackages != null) 14805 ? newPackage.childPackages.size() : 0; 14806 for (int i = 0; i < deletedChildCount; i++) { 14807 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14808 boolean childPackageDeleted = true; 14809 for (int j = 0; j < newChildCount; j++) { 14810 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14811 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14812 childPackageDeleted = false; 14813 break; 14814 } 14815 } 14816 if (childPackageDeleted) { 14817 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14818 deletedChildPkg.packageName); 14819 if (ps != null && res.removedInfo.removedChildPackages != null) { 14820 PackageRemovedInfo removedChildRes = res.removedInfo 14821 .removedChildPackages.get(deletedChildPkg.packageName); 14822 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14823 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14824 } 14825 } 14826 } 14827 14828 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14829 prepareAppDataAfterInstallLIF(newPackage); 14830 } 14831 } catch (PackageManagerException e) { 14832 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14833 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14834 } 14835 14836 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14837 // Re installation failed. Restore old information 14838 // Remove new pkg information 14839 if (newPackage != null) { 14840 removeInstalledPackageLI(newPackage, true); 14841 } 14842 // Add back the old system package 14843 try { 14844 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14845 } catch (PackageManagerException e) { 14846 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14847 } 14848 14849 synchronized (mPackages) { 14850 if (disabledSystem) { 14851 enableSystemPackageLPw(deletedPackage); 14852 } 14853 14854 // Ensure the installer package name up to date 14855 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14856 14857 // Update permissions for restored package 14858 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14859 14860 mSettings.writeLPr(); 14861 } 14862 14863 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14864 + " after failed upgrade"); 14865 } 14866 } 14867 14868 /** 14869 * Checks whether the parent or any of the child packages have a change shared 14870 * user. For a package to be a valid update the shred users of the parent and 14871 * the children should match. We may later support changing child shared users. 14872 * @param oldPkg The updated package. 14873 * @param newPkg The update package. 14874 * @return The shared user that change between the versions. 14875 */ 14876 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14877 PackageParser.Package newPkg) { 14878 // Check parent shared user 14879 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14880 return newPkg.packageName; 14881 } 14882 // Check child shared users 14883 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14884 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14885 for (int i = 0; i < newChildCount; i++) { 14886 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14887 // If this child was present, did it have the same shared user? 14888 for (int j = 0; j < oldChildCount; j++) { 14889 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14890 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14891 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14892 return newChildPkg.packageName; 14893 } 14894 } 14895 } 14896 return null; 14897 } 14898 14899 private void removeNativeBinariesLI(PackageSetting ps) { 14900 // Remove the lib path for the parent package 14901 if (ps != null) { 14902 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14903 // Remove the lib path for the child packages 14904 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14905 for (int i = 0; i < childCount; i++) { 14906 PackageSetting childPs = null; 14907 synchronized (mPackages) { 14908 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 14909 } 14910 if (childPs != null) { 14911 NativeLibraryHelper.removeNativeBinariesLI(childPs 14912 .legacyNativeLibraryPathString); 14913 } 14914 } 14915 } 14916 } 14917 14918 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14919 // Enable the parent package 14920 mSettings.enableSystemPackageLPw(pkg.packageName); 14921 // Enable the child packages 14922 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14923 for (int i = 0; i < childCount; i++) { 14924 PackageParser.Package childPkg = pkg.childPackages.get(i); 14925 mSettings.enableSystemPackageLPw(childPkg.packageName); 14926 } 14927 } 14928 14929 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14930 PackageParser.Package newPkg) { 14931 // Disable the parent package (parent always replaced) 14932 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14933 // Disable the child packages 14934 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14935 for (int i = 0; i < childCount; i++) { 14936 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14937 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14938 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14939 } 14940 return disabled; 14941 } 14942 14943 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14944 String installerPackageName) { 14945 // Enable the parent package 14946 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14947 // Enable the child packages 14948 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14949 for (int i = 0; i < childCount; i++) { 14950 PackageParser.Package childPkg = pkg.childPackages.get(i); 14951 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14952 } 14953 } 14954 14955 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14956 // Collect all used permissions in the UID 14957 ArraySet<String> usedPermissions = new ArraySet<>(); 14958 final int packageCount = su.packages.size(); 14959 for (int i = 0; i < packageCount; i++) { 14960 PackageSetting ps = su.packages.valueAt(i); 14961 if (ps.pkg == null) { 14962 continue; 14963 } 14964 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14965 for (int j = 0; j < requestedPermCount; j++) { 14966 String permission = ps.pkg.requestedPermissions.get(j); 14967 BasePermission bp = mSettings.mPermissions.get(permission); 14968 if (bp != null) { 14969 usedPermissions.add(permission); 14970 } 14971 } 14972 } 14973 14974 PermissionsState permissionsState = su.getPermissionsState(); 14975 // Prune install permissions 14976 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14977 final int installPermCount = installPermStates.size(); 14978 for (int i = installPermCount - 1; i >= 0; i--) { 14979 PermissionState permissionState = installPermStates.get(i); 14980 if (!usedPermissions.contains(permissionState.getName())) { 14981 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14982 if (bp != null) { 14983 permissionsState.revokeInstallPermission(bp); 14984 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14985 PackageManager.MASK_PERMISSION_FLAGS, 0); 14986 } 14987 } 14988 } 14989 14990 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14991 14992 // Prune runtime permissions 14993 for (int userId : allUserIds) { 14994 List<PermissionState> runtimePermStates = permissionsState 14995 .getRuntimePermissionStates(userId); 14996 final int runtimePermCount = runtimePermStates.size(); 14997 for (int i = runtimePermCount - 1; i >= 0; i--) { 14998 PermissionState permissionState = runtimePermStates.get(i); 14999 if (!usedPermissions.contains(permissionState.getName())) { 15000 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15001 if (bp != null) { 15002 permissionsState.revokeRuntimePermission(bp, userId); 15003 permissionsState.updatePermissionFlags(bp, userId, 15004 PackageManager.MASK_PERMISSION_FLAGS, 0); 15005 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 15006 runtimePermissionChangedUserIds, userId); 15007 } 15008 } 15009 } 15010 } 15011 15012 return runtimePermissionChangedUserIds; 15013 } 15014 15015 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 15016 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 15017 // Update the parent package setting 15018 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 15019 res, user); 15020 // Update the child packages setting 15021 final int childCount = (newPackage.childPackages != null) 15022 ? newPackage.childPackages.size() : 0; 15023 for (int i = 0; i < childCount; i++) { 15024 PackageParser.Package childPackage = newPackage.childPackages.get(i); 15025 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 15026 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 15027 childRes.origUsers, childRes, user); 15028 } 15029 } 15030 15031 private void updateSettingsInternalLI(PackageParser.Package newPackage, 15032 String installerPackageName, int[] allUsers, int[] installedForUsers, 15033 PackageInstalledInfo res, UserHandle user) { 15034 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 15035 15036 String pkgName = newPackage.packageName; 15037 synchronized (mPackages) { 15038 //write settings. the installStatus will be incomplete at this stage. 15039 //note that the new package setting would have already been 15040 //added to mPackages. It hasn't been persisted yet. 15041 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 15042 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15043 mSettings.writeLPr(); 15044 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15045 } 15046 15047 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 15048 synchronized (mPackages) { 15049 updatePermissionsLPw(newPackage.packageName, newPackage, 15050 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 15051 ? UPDATE_PERMISSIONS_ALL : 0)); 15052 // For system-bundled packages, we assume that installing an upgraded version 15053 // of the package implies that the user actually wants to run that new code, 15054 // so we enable the package. 15055 PackageSetting ps = mSettings.mPackages.get(pkgName); 15056 final int userId = user.getIdentifier(); 15057 if (ps != null) { 15058 if (isSystemApp(newPackage)) { 15059 if (DEBUG_INSTALL) { 15060 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 15061 } 15062 // Enable system package for requested users 15063 if (res.origUsers != null) { 15064 for (int origUserId : res.origUsers) { 15065 if (userId == UserHandle.USER_ALL || userId == origUserId) { 15066 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 15067 origUserId, installerPackageName); 15068 } 15069 } 15070 } 15071 // Also convey the prior install/uninstall state 15072 if (allUsers != null && installedForUsers != null) { 15073 for (int currentUserId : allUsers) { 15074 final boolean installed = ArrayUtils.contains( 15075 installedForUsers, currentUserId); 15076 if (DEBUG_INSTALL) { 15077 Slog.d(TAG, " user " + currentUserId + " => " + installed); 15078 } 15079 ps.setInstalled(installed, currentUserId); 15080 } 15081 // these install state changes will be persisted in the 15082 // upcoming call to mSettings.writeLPr(). 15083 } 15084 } 15085 // It's implied that when a user requests installation, they want the app to be 15086 // installed and enabled. 15087 if (userId != UserHandle.USER_ALL) { 15088 ps.setInstalled(true, userId); 15089 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 15090 } 15091 } 15092 res.name = pkgName; 15093 res.uid = newPackage.applicationInfo.uid; 15094 res.pkg = newPackage; 15095 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 15096 mSettings.setInstallerPackageName(pkgName, installerPackageName); 15097 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15098 //to update install status 15099 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15100 mSettings.writeLPr(); 15101 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15102 } 15103 15104 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15105 } 15106 15107 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 15108 try { 15109 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 15110 installPackageLI(args, res); 15111 } finally { 15112 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15113 } 15114 } 15115 15116 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 15117 final int installFlags = args.installFlags; 15118 final String installerPackageName = args.installerPackageName; 15119 final String volumeUuid = args.volumeUuid; 15120 final File tmpPackageFile = new File(args.getCodePath()); 15121 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 15122 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 15123 || (args.volumeUuid != null)); 15124 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 15125 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 15126 boolean replace = false; 15127 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 15128 if (args.move != null) { 15129 // moving a complete application; perform an initial scan on the new install location 15130 scanFlags |= SCAN_INITIAL; 15131 } 15132 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 15133 scanFlags |= SCAN_DONT_KILL_APP; 15134 } 15135 15136 // Result object to be returned 15137 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15138 15139 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 15140 15141 // Sanity check 15142 if (ephemeral && (forwardLocked || onExternal)) { 15143 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 15144 + " external=" + onExternal); 15145 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15146 return; 15147 } 15148 15149 // Retrieve PackageSettings and parse package 15150 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 15151 | PackageParser.PARSE_ENFORCE_CODE 15152 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 15153 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 15154 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 15155 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 15156 PackageParser pp = new PackageParser(); 15157 pp.setSeparateProcesses(mSeparateProcesses); 15158 pp.setDisplayMetrics(mMetrics); 15159 15160 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 15161 final PackageParser.Package pkg; 15162 try { 15163 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 15164 } catch (PackageParserException e) { 15165 res.setError("Failed parse during installPackageLI", e); 15166 return; 15167 } finally { 15168 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15169 } 15170 15171 // If we are installing a clustered package add results for the children 15172 if (pkg.childPackages != null) { 15173 synchronized (mPackages) { 15174 final int childCount = pkg.childPackages.size(); 15175 for (int i = 0; i < childCount; i++) { 15176 PackageParser.Package childPkg = pkg.childPackages.get(i); 15177 PackageInstalledInfo childRes = new PackageInstalledInfo(); 15178 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15179 childRes.pkg = childPkg; 15180 childRes.name = childPkg.packageName; 15181 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15182 if (childPs != null) { 15183 childRes.origUsers = childPs.queryInstalledUsers( 15184 sUserManager.getUserIds(), true); 15185 } 15186 if ((mPackages.containsKey(childPkg.packageName))) { 15187 childRes.removedInfo = new PackageRemovedInfo(); 15188 childRes.removedInfo.removedPackage = childPkg.packageName; 15189 } 15190 if (res.addedChildPackages == null) { 15191 res.addedChildPackages = new ArrayMap<>(); 15192 } 15193 res.addedChildPackages.put(childPkg.packageName, childRes); 15194 } 15195 } 15196 } 15197 15198 // If package doesn't declare API override, mark that we have an install 15199 // time CPU ABI override. 15200 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15201 pkg.cpuAbiOverride = args.abiOverride; 15202 } 15203 15204 String pkgName = res.name = pkg.packageName; 15205 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15206 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15207 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15208 return; 15209 } 15210 } 15211 15212 try { 15213 // either use what we've been given or parse directly from the APK 15214 if (args.certificates != null) { 15215 try { 15216 PackageParser.populateCertificates(pkg, args.certificates); 15217 } catch (PackageParserException e) { 15218 // there was something wrong with the certificates we were given; 15219 // try to pull them from the APK 15220 PackageParser.collectCertificates(pkg, parseFlags); 15221 } 15222 } else { 15223 PackageParser.collectCertificates(pkg, parseFlags); 15224 } 15225 } catch (PackageParserException e) { 15226 res.setError("Failed collect during installPackageLI", e); 15227 return; 15228 } 15229 15230 // Get rid of all references to package scan path via parser. 15231 pp = null; 15232 String oldCodePath = null; 15233 boolean systemApp = false; 15234 synchronized (mPackages) { 15235 // Check if installing already existing package 15236 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15237 String oldName = mSettings.getRenamedPackageLPr(pkgName); 15238 if (pkg.mOriginalPackages != null 15239 && pkg.mOriginalPackages.contains(oldName) 15240 && mPackages.containsKey(oldName)) { 15241 // This package is derived from an original package, 15242 // and this device has been updating from that original 15243 // name. We must continue using the original name, so 15244 // rename the new package here. 15245 pkg.setPackageName(oldName); 15246 pkgName = pkg.packageName; 15247 replace = true; 15248 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15249 + oldName + " pkgName=" + pkgName); 15250 } else if (mPackages.containsKey(pkgName)) { 15251 // This package, under its official name, already exists 15252 // on the device; we should replace it. 15253 replace = true; 15254 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15255 } 15256 15257 // Child packages are installed through the parent package 15258 if (pkg.parentPackage != null) { 15259 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15260 "Package " + pkg.packageName + " is child of package " 15261 + pkg.parentPackage.parentPackage + ". Child packages " 15262 + "can be updated only through the parent package."); 15263 return; 15264 } 15265 15266 if (replace) { 15267 // Prevent apps opting out from runtime permissions 15268 PackageParser.Package oldPackage = mPackages.get(pkgName); 15269 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15270 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15271 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15272 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15273 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15274 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15275 + " doesn't support runtime permissions but the old" 15276 + " target SDK " + oldTargetSdk + " does."); 15277 return; 15278 } 15279 15280 // Prevent installing of child packages 15281 if (oldPackage.parentPackage != null) { 15282 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15283 "Package " + pkg.packageName + " is child of package " 15284 + oldPackage.parentPackage + ". Child packages " 15285 + "can be updated only through the parent package."); 15286 return; 15287 } 15288 } 15289 } 15290 15291 PackageSetting ps = mSettings.mPackages.get(pkgName); 15292 if (ps != null) { 15293 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15294 15295 // Quick sanity check that we're signed correctly if updating; 15296 // we'll check this again later when scanning, but we want to 15297 // bail early here before tripping over redefined permissions. 15298 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15299 if (!checkUpgradeKeySetLP(ps, pkg)) { 15300 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15301 + pkg.packageName + " upgrade keys do not match the " 15302 + "previously installed version"); 15303 return; 15304 } 15305 } else { 15306 try { 15307 verifySignaturesLP(ps, pkg); 15308 } catch (PackageManagerException e) { 15309 res.setError(e.error, e.getMessage()); 15310 return; 15311 } 15312 } 15313 15314 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15315 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15316 systemApp = (ps.pkg.applicationInfo.flags & 15317 ApplicationInfo.FLAG_SYSTEM) != 0; 15318 } 15319 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15320 } 15321 15322 // Check whether the newly-scanned package wants to define an already-defined perm 15323 int N = pkg.permissions.size(); 15324 for (int i = N-1; i >= 0; i--) { 15325 PackageParser.Permission perm = pkg.permissions.get(i); 15326 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15327 if (bp != null) { 15328 // If the defining package is signed with our cert, it's okay. This 15329 // also includes the "updating the same package" case, of course. 15330 // "updating same package" could also involve key-rotation. 15331 final boolean sigsOk; 15332 if (bp.sourcePackage.equals(pkg.packageName) 15333 && (bp.packageSetting instanceof PackageSetting) 15334 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15335 scanFlags))) { 15336 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15337 } else { 15338 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15339 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15340 } 15341 if (!sigsOk) { 15342 // If the owning package is the system itself, we log but allow 15343 // install to proceed; we fail the install on all other permission 15344 // redefinitions. 15345 if (!bp.sourcePackage.equals("android")) { 15346 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15347 + pkg.packageName + " attempting to redeclare permission " 15348 + perm.info.name + " already owned by " + bp.sourcePackage); 15349 res.origPermission = perm.info.name; 15350 res.origPackage = bp.sourcePackage; 15351 return; 15352 } else { 15353 Slog.w(TAG, "Package " + pkg.packageName 15354 + " attempting to redeclare system permission " 15355 + perm.info.name + "; ignoring new declaration"); 15356 pkg.permissions.remove(i); 15357 } 15358 } 15359 } 15360 } 15361 } 15362 15363 if (systemApp) { 15364 if (onExternal) { 15365 // Abort update; system app can't be replaced with app on sdcard 15366 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15367 "Cannot install updates to system apps on sdcard"); 15368 return; 15369 } else if (ephemeral) { 15370 // Abort update; system app can't be replaced with an ephemeral app 15371 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15372 "Cannot update a system app with an ephemeral app"); 15373 return; 15374 } 15375 } 15376 15377 if (args.move != null) { 15378 // We did an in-place move, so dex is ready to roll 15379 scanFlags |= SCAN_NO_DEX; 15380 scanFlags |= SCAN_MOVE; 15381 15382 synchronized (mPackages) { 15383 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15384 if (ps == null) { 15385 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15386 "Missing settings for moved package " + pkgName); 15387 } 15388 15389 // We moved the entire application as-is, so bring over the 15390 // previously derived ABI information. 15391 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15392 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15393 } 15394 15395 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15396 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15397 scanFlags |= SCAN_NO_DEX; 15398 15399 try { 15400 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15401 args.abiOverride : pkg.cpuAbiOverride); 15402 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15403 true /*extractLibs*/, mAppLib32InstallDir); 15404 } catch (PackageManagerException pme) { 15405 Slog.e(TAG, "Error deriving application ABI", pme); 15406 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15407 return; 15408 } 15409 15410 // Shared libraries for the package need to be updated. 15411 synchronized (mPackages) { 15412 try { 15413 updateSharedLibrariesLPr(pkg, null); 15414 } catch (PackageManagerException e) { 15415 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15416 } 15417 } 15418 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15419 // Do not run PackageDexOptimizer through the local performDexOpt 15420 // method because `pkg` may not be in `mPackages` yet. 15421 // 15422 // Also, don't fail application installs if the dexopt step fails. 15423 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15424 null /* instructionSets */, false /* checkProfiles */, 15425 getCompilerFilterForReason(REASON_INSTALL), 15426 getOrCreateCompilerPackageStats(pkg)); 15427 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15428 15429 // Notify BackgroundDexOptService that the package has been changed. 15430 // If this is an update of a package which used to fail to compile, 15431 // BDOS will remove it from its blacklist. 15432 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15433 } 15434 15435 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15436 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15437 return; 15438 } 15439 15440 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15441 15442 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15443 "installPackageLI")) { 15444 if (replace) { 15445 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15446 installerPackageName, res); 15447 } else { 15448 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15449 args.user, installerPackageName, volumeUuid, res); 15450 } 15451 } 15452 synchronized (mPackages) { 15453 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15454 if (ps != null) { 15455 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15456 } 15457 15458 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15459 for (int i = 0; i < childCount; i++) { 15460 PackageParser.Package childPkg = pkg.childPackages.get(i); 15461 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15462 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15463 if (childPs != null) { 15464 childRes.newUsers = childPs.queryInstalledUsers( 15465 sUserManager.getUserIds(), true); 15466 } 15467 } 15468 } 15469 } 15470 15471 private void startIntentFilterVerifications(int userId, boolean replacing, 15472 PackageParser.Package pkg) { 15473 if (mIntentFilterVerifierComponent == null) { 15474 Slog.w(TAG, "No IntentFilter verification will not be done as " 15475 + "there is no IntentFilterVerifier available!"); 15476 return; 15477 } 15478 15479 final int verifierUid = getPackageUid( 15480 mIntentFilterVerifierComponent.getPackageName(), 15481 MATCH_DEBUG_TRIAGED_MISSING, 15482 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15483 15484 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15485 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15486 mHandler.sendMessage(msg); 15487 15488 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15489 for (int i = 0; i < childCount; i++) { 15490 PackageParser.Package childPkg = pkg.childPackages.get(i); 15491 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15492 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15493 mHandler.sendMessage(msg); 15494 } 15495 } 15496 15497 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15498 PackageParser.Package pkg) { 15499 int size = pkg.activities.size(); 15500 if (size == 0) { 15501 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15502 "No activity, so no need to verify any IntentFilter!"); 15503 return; 15504 } 15505 15506 final boolean hasDomainURLs = hasDomainURLs(pkg); 15507 if (!hasDomainURLs) { 15508 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15509 "No domain URLs, so no need to verify any IntentFilter!"); 15510 return; 15511 } 15512 15513 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15514 + " if any IntentFilter from the " + size 15515 + " Activities needs verification ..."); 15516 15517 int count = 0; 15518 final String packageName = pkg.packageName; 15519 15520 synchronized (mPackages) { 15521 // If this is a new install and we see that we've already run verification for this 15522 // package, we have nothing to do: it means the state was restored from backup. 15523 if (!replacing) { 15524 IntentFilterVerificationInfo ivi = 15525 mSettings.getIntentFilterVerificationLPr(packageName); 15526 if (ivi != null) { 15527 if (DEBUG_DOMAIN_VERIFICATION) { 15528 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15529 + ivi.getStatusString()); 15530 } 15531 return; 15532 } 15533 } 15534 15535 // If any filters need to be verified, then all need to be. 15536 boolean needToVerify = false; 15537 for (PackageParser.Activity a : pkg.activities) { 15538 for (ActivityIntentInfo filter : a.intents) { 15539 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15540 if (DEBUG_DOMAIN_VERIFICATION) { 15541 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15542 } 15543 needToVerify = true; 15544 break; 15545 } 15546 } 15547 } 15548 15549 if (needToVerify) { 15550 final int verificationId = mIntentFilterVerificationToken++; 15551 for (PackageParser.Activity a : pkg.activities) { 15552 for (ActivityIntentInfo filter : a.intents) { 15553 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15554 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15555 "Verification needed for IntentFilter:" + filter.toString()); 15556 mIntentFilterVerifier.addOneIntentFilterVerification( 15557 verifierUid, userId, verificationId, filter, packageName); 15558 count++; 15559 } 15560 } 15561 } 15562 } 15563 } 15564 15565 if (count > 0) { 15566 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15567 + " IntentFilter verification" + (count > 1 ? "s" : "") 15568 + " for userId:" + userId); 15569 mIntentFilterVerifier.startVerifications(userId); 15570 } else { 15571 if (DEBUG_DOMAIN_VERIFICATION) { 15572 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15573 } 15574 } 15575 } 15576 15577 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15578 final ComponentName cn = filter.activity.getComponentName(); 15579 final String packageName = cn.getPackageName(); 15580 15581 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15582 packageName); 15583 if (ivi == null) { 15584 return true; 15585 } 15586 int status = ivi.getStatus(); 15587 switch (status) { 15588 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15589 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15590 return true; 15591 15592 default: 15593 // Nothing to do 15594 return false; 15595 } 15596 } 15597 15598 private static boolean isMultiArch(ApplicationInfo info) { 15599 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15600 } 15601 15602 private static boolean isExternal(PackageParser.Package pkg) { 15603 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15604 } 15605 15606 private static boolean isExternal(PackageSetting ps) { 15607 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15608 } 15609 15610 private static boolean isEphemeral(PackageParser.Package pkg) { 15611 return pkg.applicationInfo.isEphemeralApp(); 15612 } 15613 15614 private static boolean isEphemeral(PackageSetting ps) { 15615 return ps.pkg != null && isEphemeral(ps.pkg); 15616 } 15617 15618 private static boolean isSystemApp(PackageParser.Package pkg) { 15619 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15620 } 15621 15622 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15623 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15624 } 15625 15626 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15627 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15628 } 15629 15630 private static boolean isSystemApp(PackageSetting ps) { 15631 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15632 } 15633 15634 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15635 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15636 } 15637 15638 private int packageFlagsToInstallFlags(PackageSetting ps) { 15639 int installFlags = 0; 15640 if (isEphemeral(ps)) { 15641 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15642 } 15643 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15644 // This existing package was an external ASEC install when we have 15645 // the external flag without a UUID 15646 installFlags |= PackageManager.INSTALL_EXTERNAL; 15647 } 15648 if (ps.isForwardLocked()) { 15649 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15650 } 15651 return installFlags; 15652 } 15653 15654 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15655 if (isExternal(pkg)) { 15656 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15657 return StorageManager.UUID_PRIMARY_PHYSICAL; 15658 } else { 15659 return pkg.volumeUuid; 15660 } 15661 } else { 15662 return StorageManager.UUID_PRIVATE_INTERNAL; 15663 } 15664 } 15665 15666 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15667 if (isExternal(pkg)) { 15668 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15669 return mSettings.getExternalVersion(); 15670 } else { 15671 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15672 } 15673 } else { 15674 return mSettings.getInternalVersion(); 15675 } 15676 } 15677 15678 private void deleteTempPackageFiles() { 15679 final FilenameFilter filter = new FilenameFilter() { 15680 public boolean accept(File dir, String name) { 15681 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15682 } 15683 }; 15684 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15685 file.delete(); 15686 } 15687 } 15688 15689 @Override 15690 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15691 int flags) { 15692 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15693 flags); 15694 } 15695 15696 @Override 15697 public void deletePackage(final String packageName, 15698 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15699 mContext.enforceCallingOrSelfPermission( 15700 android.Manifest.permission.DELETE_PACKAGES, null); 15701 Preconditions.checkNotNull(packageName); 15702 Preconditions.checkNotNull(observer); 15703 final int uid = Binder.getCallingUid(); 15704 if (!isOrphaned(packageName) 15705 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 15706 try { 15707 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 15708 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 15709 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 15710 observer.onUserActionRequired(intent); 15711 } catch (RemoteException re) { 15712 } 15713 return; 15714 } 15715 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15716 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15717 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15718 mContext.enforceCallingOrSelfPermission( 15719 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15720 "deletePackage for user " + userId); 15721 } 15722 15723 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15724 try { 15725 observer.onPackageDeleted(packageName, 15726 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15727 } catch (RemoteException re) { 15728 } 15729 return; 15730 } 15731 15732 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15733 try { 15734 observer.onPackageDeleted(packageName, 15735 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15736 } catch (RemoteException re) { 15737 } 15738 return; 15739 } 15740 15741 if (DEBUG_REMOVE) { 15742 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15743 + " deleteAllUsers: " + deleteAllUsers ); 15744 } 15745 // Queue up an async operation since the package deletion may take a little while. 15746 mHandler.post(new Runnable() { 15747 public void run() { 15748 mHandler.removeCallbacks(this); 15749 int returnCode; 15750 if (!deleteAllUsers) { 15751 returnCode = deletePackageX(packageName, userId, deleteFlags); 15752 } else { 15753 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15754 // If nobody is blocking uninstall, proceed with delete for all users 15755 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15756 returnCode = deletePackageX(packageName, userId, deleteFlags); 15757 } else { 15758 // Otherwise uninstall individually for users with blockUninstalls=false 15759 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15760 for (int userId : users) { 15761 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15762 returnCode = deletePackageX(packageName, userId, userFlags); 15763 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15764 Slog.w(TAG, "Package delete failed for user " + userId 15765 + ", returnCode " + returnCode); 15766 } 15767 } 15768 } 15769 // The app has only been marked uninstalled for certain users. 15770 // We still need to report that delete was blocked 15771 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15772 } 15773 } 15774 try { 15775 observer.onPackageDeleted(packageName, returnCode, null); 15776 } catch (RemoteException e) { 15777 Log.i(TAG, "Observer no longer exists."); 15778 } //end catch 15779 } //end run 15780 }); 15781 } 15782 15783 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 15784 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 15785 || callingUid == Process.SYSTEM_UID) { 15786 return true; 15787 } 15788 final int callingUserId = UserHandle.getUserId(callingUid); 15789 // If the caller installed the pkgName, then allow it to silently uninstall. 15790 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 15791 return true; 15792 } 15793 15794 // Allow package verifier to silently uninstall. 15795 if (mRequiredVerifierPackage != null && 15796 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 15797 return true; 15798 } 15799 15800 // Allow package uninstaller to silently uninstall. 15801 if (mRequiredUninstallerPackage != null && 15802 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 15803 return true; 15804 } 15805 15806 // Allow storage manager to silently uninstall. 15807 if (mStorageManagerPackage != null && 15808 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 15809 return true; 15810 } 15811 return false; 15812 } 15813 15814 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15815 int[] result = EMPTY_INT_ARRAY; 15816 for (int userId : userIds) { 15817 if (getBlockUninstallForUser(packageName, userId)) { 15818 result = ArrayUtils.appendInt(result, userId); 15819 } 15820 } 15821 return result; 15822 } 15823 15824 @Override 15825 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15826 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15827 } 15828 15829 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15830 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15831 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15832 try { 15833 if (dpm != null) { 15834 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15835 /* callingUserOnly =*/ false); 15836 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15837 : deviceOwnerComponentName.getPackageName(); 15838 // Does the package contains the device owner? 15839 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15840 // this check is probably not needed, since DO should be registered as a device 15841 // admin on some user too. (Original bug for this: b/17657954) 15842 if (packageName.equals(deviceOwnerPackageName)) { 15843 return true; 15844 } 15845 // Does it contain a device admin for any user? 15846 int[] users; 15847 if (userId == UserHandle.USER_ALL) { 15848 users = sUserManager.getUserIds(); 15849 } else { 15850 users = new int[]{userId}; 15851 } 15852 for (int i = 0; i < users.length; ++i) { 15853 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15854 return true; 15855 } 15856 } 15857 } 15858 } catch (RemoteException e) { 15859 } 15860 return false; 15861 } 15862 15863 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15864 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15865 } 15866 15867 /** 15868 * This method is an internal method that could be get invoked either 15869 * to delete an installed package or to clean up a failed installation. 15870 * After deleting an installed package, a broadcast is sent to notify any 15871 * listeners that the package has been removed. For cleaning up a failed 15872 * installation, the broadcast is not necessary since the package's 15873 * installation wouldn't have sent the initial broadcast either 15874 * The key steps in deleting a package are 15875 * deleting the package information in internal structures like mPackages, 15876 * deleting the packages base directories through installd 15877 * updating mSettings to reflect current status 15878 * persisting settings for later use 15879 * sending a broadcast if necessary 15880 */ 15881 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15882 final PackageRemovedInfo info = new PackageRemovedInfo(); 15883 final boolean res; 15884 15885 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15886 ? UserHandle.USER_ALL : userId; 15887 15888 if (isPackageDeviceAdmin(packageName, removeUser)) { 15889 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15890 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15891 } 15892 15893 PackageSetting uninstalledPs = null; 15894 15895 // for the uninstall-updates case and restricted profiles, remember the per- 15896 // user handle installed state 15897 int[] allUsers; 15898 synchronized (mPackages) { 15899 uninstalledPs = mSettings.mPackages.get(packageName); 15900 if (uninstalledPs == null) { 15901 Slog.w(TAG, "Not removing non-existent package " + packageName); 15902 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15903 } 15904 allUsers = sUserManager.getUserIds(); 15905 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15906 } 15907 15908 final int freezeUser; 15909 if (isUpdatedSystemApp(uninstalledPs) 15910 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15911 // We're downgrading a system app, which will apply to all users, so 15912 // freeze them all during the downgrade 15913 freezeUser = UserHandle.USER_ALL; 15914 } else { 15915 freezeUser = removeUser; 15916 } 15917 15918 synchronized (mInstallLock) { 15919 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15920 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15921 deleteFlags, "deletePackageX")) { 15922 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15923 deleteFlags | REMOVE_CHATTY, info, true, null); 15924 } 15925 synchronized (mPackages) { 15926 if (res) { 15927 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15928 } 15929 } 15930 } 15931 15932 if (res) { 15933 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15934 info.sendPackageRemovedBroadcasts(killApp); 15935 info.sendSystemPackageUpdatedBroadcasts(); 15936 info.sendSystemPackageAppearedBroadcasts(); 15937 } 15938 // Force a gc here. 15939 Runtime.getRuntime().gc(); 15940 // Delete the resources here after sending the broadcast to let 15941 // other processes clean up before deleting resources. 15942 if (info.args != null) { 15943 synchronized (mInstallLock) { 15944 info.args.doPostDeleteLI(true); 15945 } 15946 } 15947 15948 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15949 } 15950 15951 class PackageRemovedInfo { 15952 String removedPackage; 15953 int uid = -1; 15954 int removedAppId = -1; 15955 int[] origUsers; 15956 int[] removedUsers = null; 15957 boolean isRemovedPackageSystemUpdate = false; 15958 boolean isUpdate; 15959 boolean dataRemoved; 15960 boolean removedForAllUsers; 15961 // Clean up resources deleted packages. 15962 InstallArgs args = null; 15963 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15964 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15965 15966 void sendPackageRemovedBroadcasts(boolean killApp) { 15967 sendPackageRemovedBroadcastInternal(killApp); 15968 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15969 for (int i = 0; i < childCount; i++) { 15970 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15971 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15972 } 15973 } 15974 15975 void sendSystemPackageUpdatedBroadcasts() { 15976 if (isRemovedPackageSystemUpdate) { 15977 sendSystemPackageUpdatedBroadcastsInternal(); 15978 final int childCount = (removedChildPackages != null) 15979 ? removedChildPackages.size() : 0; 15980 for (int i = 0; i < childCount; i++) { 15981 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15982 if (childInfo.isRemovedPackageSystemUpdate) { 15983 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15984 } 15985 } 15986 } 15987 } 15988 15989 void sendSystemPackageAppearedBroadcasts() { 15990 final int packageCount = (appearedChildPackages != null) 15991 ? appearedChildPackages.size() : 0; 15992 for (int i = 0; i < packageCount; i++) { 15993 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15994 sendPackageAddedForNewUsers(installedInfo.name, true, 15995 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 15996 } 15997 } 15998 15999 private void sendSystemPackageUpdatedBroadcastsInternal() { 16000 Bundle extras = new Bundle(2); 16001 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16002 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16003 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 16004 extras, 0, null, null, null); 16005 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 16006 extras, 0, null, null, null); 16007 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 16008 null, 0, removedPackage, null, null); 16009 } 16010 16011 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 16012 Bundle extras = new Bundle(2); 16013 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16014 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 16015 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 16016 if (isUpdate || isRemovedPackageSystemUpdate) { 16017 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16018 } 16019 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 16020 if (removedPackage != null) { 16021 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 16022 extras, 0, null, null, removedUsers); 16023 if (dataRemoved && !isRemovedPackageSystemUpdate) { 16024 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 16025 removedPackage, extras, 0, null, null, removedUsers); 16026 } 16027 } 16028 if (removedAppId >= 0) { 16029 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 16030 removedUsers); 16031 } 16032 } 16033 } 16034 16035 /* 16036 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 16037 * flag is not set, the data directory is removed as well. 16038 * make sure this flag is set for partially installed apps. If not its meaningless to 16039 * delete a partially installed application. 16040 */ 16041 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 16042 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 16043 String packageName = ps.name; 16044 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 16045 // Retrieve object to delete permissions for shared user later on 16046 final PackageParser.Package deletedPkg; 16047 final PackageSetting deletedPs; 16048 // reader 16049 synchronized (mPackages) { 16050 deletedPkg = mPackages.get(packageName); 16051 deletedPs = mSettings.mPackages.get(packageName); 16052 if (outInfo != null) { 16053 outInfo.removedPackage = packageName; 16054 outInfo.removedUsers = deletedPs != null 16055 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 16056 : null; 16057 } 16058 } 16059 16060 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 16061 16062 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 16063 final PackageParser.Package resolvedPkg; 16064 if (deletedPkg != null) { 16065 resolvedPkg = deletedPkg; 16066 } else { 16067 // We don't have a parsed package when it lives on an ejected 16068 // adopted storage device, so fake something together 16069 resolvedPkg = new PackageParser.Package(ps.name); 16070 resolvedPkg.setVolumeUuid(ps.volumeUuid); 16071 } 16072 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 16073 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16074 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 16075 if (outInfo != null) { 16076 outInfo.dataRemoved = true; 16077 } 16078 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 16079 } 16080 16081 // writer 16082 synchronized (mPackages) { 16083 if (deletedPs != null) { 16084 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 16085 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 16086 clearDefaultBrowserIfNeeded(packageName); 16087 if (outInfo != null) { 16088 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 16089 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 16090 } 16091 updatePermissionsLPw(deletedPs.name, null, 0); 16092 if (deletedPs.sharedUser != null) { 16093 // Remove permissions associated with package. Since runtime 16094 // permissions are per user we have to kill the removed package 16095 // or packages running under the shared user of the removed 16096 // package if revoking the permissions requested only by the removed 16097 // package is successful and this causes a change in gids. 16098 for (int userId : UserManagerService.getInstance().getUserIds()) { 16099 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 16100 userId); 16101 if (userIdToKill == UserHandle.USER_ALL 16102 || userIdToKill >= UserHandle.USER_SYSTEM) { 16103 // If gids changed for this user, kill all affected packages. 16104 mHandler.post(new Runnable() { 16105 @Override 16106 public void run() { 16107 // This has to happen with no lock held. 16108 killApplication(deletedPs.name, deletedPs.appId, 16109 KILL_APP_REASON_GIDS_CHANGED); 16110 } 16111 }); 16112 break; 16113 } 16114 } 16115 } 16116 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 16117 } 16118 // make sure to preserve per-user disabled state if this removal was just 16119 // a downgrade of a system app to the factory package 16120 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 16121 if (DEBUG_REMOVE) { 16122 Slog.d(TAG, "Propagating install state across downgrade"); 16123 } 16124 for (int userId : allUserHandles) { 16125 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16126 if (DEBUG_REMOVE) { 16127 Slog.d(TAG, " user " + userId + " => " + installed); 16128 } 16129 ps.setInstalled(installed, userId); 16130 } 16131 } 16132 } 16133 // can downgrade to reader 16134 if (writeSettings) { 16135 // Save settings now 16136 mSettings.writeLPr(); 16137 } 16138 } 16139 if (outInfo != null) { 16140 // A user ID was deleted here. Go through all users and remove it 16141 // from KeyStore. 16142 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 16143 } 16144 } 16145 16146 static boolean locationIsPrivileged(File path) { 16147 try { 16148 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 16149 .getCanonicalPath(); 16150 return path.getCanonicalPath().startsWith(privilegedAppDir); 16151 } catch (IOException e) { 16152 Slog.e(TAG, "Unable to access code path " + path); 16153 } 16154 return false; 16155 } 16156 16157 /* 16158 * Tries to delete system package. 16159 */ 16160 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 16161 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 16162 boolean writeSettings) { 16163 if (deletedPs.parentPackageName != null) { 16164 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 16165 return false; 16166 } 16167 16168 final boolean applyUserRestrictions 16169 = (allUserHandles != null) && (outInfo.origUsers != null); 16170 final PackageSetting disabledPs; 16171 // Confirm if the system package has been updated 16172 // An updated system app can be deleted. This will also have to restore 16173 // the system pkg from system partition 16174 // reader 16175 synchronized (mPackages) { 16176 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 16177 } 16178 16179 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 16180 + " disabledPs=" + disabledPs); 16181 16182 if (disabledPs == null) { 16183 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 16184 return false; 16185 } else if (DEBUG_REMOVE) { 16186 Slog.d(TAG, "Deleting system pkg from data partition"); 16187 } 16188 16189 if (DEBUG_REMOVE) { 16190 if (applyUserRestrictions) { 16191 Slog.d(TAG, "Remembering install states:"); 16192 for (int userId : allUserHandles) { 16193 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 16194 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 16195 } 16196 } 16197 } 16198 16199 // Delete the updated package 16200 outInfo.isRemovedPackageSystemUpdate = true; 16201 if (outInfo.removedChildPackages != null) { 16202 final int childCount = (deletedPs.childPackageNames != null) 16203 ? deletedPs.childPackageNames.size() : 0; 16204 for (int i = 0; i < childCount; i++) { 16205 String childPackageName = deletedPs.childPackageNames.get(i); 16206 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16207 .contains(childPackageName)) { 16208 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16209 childPackageName); 16210 if (childInfo != null) { 16211 childInfo.isRemovedPackageSystemUpdate = true; 16212 } 16213 } 16214 } 16215 } 16216 16217 if (disabledPs.versionCode < deletedPs.versionCode) { 16218 // Delete data for downgrades 16219 flags &= ~PackageManager.DELETE_KEEP_DATA; 16220 } else { 16221 // Preserve data by setting flag 16222 flags |= PackageManager.DELETE_KEEP_DATA; 16223 } 16224 16225 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16226 outInfo, writeSettings, disabledPs.pkg); 16227 if (!ret) { 16228 return false; 16229 } 16230 16231 // writer 16232 synchronized (mPackages) { 16233 // Reinstate the old system package 16234 enableSystemPackageLPw(disabledPs.pkg); 16235 // Remove any native libraries from the upgraded package. 16236 removeNativeBinariesLI(deletedPs); 16237 } 16238 16239 // Install the system package 16240 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16241 int parseFlags = mDefParseFlags 16242 | PackageParser.PARSE_MUST_BE_APK 16243 | PackageParser.PARSE_IS_SYSTEM 16244 | PackageParser.PARSE_IS_SYSTEM_DIR; 16245 if (locationIsPrivileged(disabledPs.codePath)) { 16246 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16247 } 16248 16249 final PackageParser.Package newPkg; 16250 try { 16251 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 16252 0 /* currentTime */, null); 16253 } catch (PackageManagerException e) { 16254 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16255 + e.getMessage()); 16256 return false; 16257 } 16258 try { 16259 // update shared libraries for the newly re-installed system package 16260 updateSharedLibrariesLPr(newPkg, null); 16261 } catch (PackageManagerException e) { 16262 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16263 } 16264 16265 prepareAppDataAfterInstallLIF(newPkg); 16266 16267 // writer 16268 synchronized (mPackages) { 16269 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16270 16271 // Propagate the permissions state as we do not want to drop on the floor 16272 // runtime permissions. The update permissions method below will take 16273 // care of removing obsolete permissions and grant install permissions. 16274 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16275 updatePermissionsLPw(newPkg.packageName, newPkg, 16276 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16277 16278 if (applyUserRestrictions) { 16279 if (DEBUG_REMOVE) { 16280 Slog.d(TAG, "Propagating install state across reinstall"); 16281 } 16282 for (int userId : allUserHandles) { 16283 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16284 if (DEBUG_REMOVE) { 16285 Slog.d(TAG, " user " + userId + " => " + installed); 16286 } 16287 ps.setInstalled(installed, userId); 16288 16289 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16290 } 16291 // Regardless of writeSettings we need to ensure that this restriction 16292 // state propagation is persisted 16293 mSettings.writeAllUsersPackageRestrictionsLPr(); 16294 } 16295 // can downgrade to reader here 16296 if (writeSettings) { 16297 mSettings.writeLPr(); 16298 } 16299 } 16300 return true; 16301 } 16302 16303 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16304 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16305 PackageRemovedInfo outInfo, boolean writeSettings, 16306 PackageParser.Package replacingPackage) { 16307 synchronized (mPackages) { 16308 if (outInfo != null) { 16309 outInfo.uid = ps.appId; 16310 } 16311 16312 if (outInfo != null && outInfo.removedChildPackages != null) { 16313 final int childCount = (ps.childPackageNames != null) 16314 ? ps.childPackageNames.size() : 0; 16315 for (int i = 0; i < childCount; i++) { 16316 String childPackageName = ps.childPackageNames.get(i); 16317 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16318 if (childPs == null) { 16319 return false; 16320 } 16321 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16322 childPackageName); 16323 if (childInfo != null) { 16324 childInfo.uid = childPs.appId; 16325 } 16326 } 16327 } 16328 } 16329 16330 // Delete package data from internal structures and also remove data if flag is set 16331 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16332 16333 // Delete the child packages data 16334 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16335 for (int i = 0; i < childCount; i++) { 16336 PackageSetting childPs; 16337 synchronized (mPackages) { 16338 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16339 } 16340 if (childPs != null) { 16341 PackageRemovedInfo childOutInfo = (outInfo != null 16342 && outInfo.removedChildPackages != null) 16343 ? outInfo.removedChildPackages.get(childPs.name) : null; 16344 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16345 && (replacingPackage != null 16346 && !replacingPackage.hasChildPackage(childPs.name)) 16347 ? flags & ~DELETE_KEEP_DATA : flags; 16348 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16349 deleteFlags, writeSettings); 16350 } 16351 } 16352 16353 // Delete application code and resources only for parent packages 16354 if (ps.parentPackageName == null) { 16355 if (deleteCodeAndResources && (outInfo != null)) { 16356 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16357 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16358 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16359 } 16360 } 16361 16362 return true; 16363 } 16364 16365 @Override 16366 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16367 int userId) { 16368 mContext.enforceCallingOrSelfPermission( 16369 android.Manifest.permission.DELETE_PACKAGES, null); 16370 synchronized (mPackages) { 16371 PackageSetting ps = mSettings.mPackages.get(packageName); 16372 if (ps == null) { 16373 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16374 return false; 16375 } 16376 if (!ps.getInstalled(userId)) { 16377 // Can't block uninstall for an app that is not installed or enabled. 16378 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16379 return false; 16380 } 16381 ps.setBlockUninstall(blockUninstall, userId); 16382 mSettings.writePackageRestrictionsLPr(userId); 16383 } 16384 return true; 16385 } 16386 16387 @Override 16388 public boolean getBlockUninstallForUser(String packageName, int userId) { 16389 synchronized (mPackages) { 16390 PackageSetting ps = mSettings.mPackages.get(packageName); 16391 if (ps == null) { 16392 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16393 return false; 16394 } 16395 return ps.getBlockUninstall(userId); 16396 } 16397 } 16398 16399 @Override 16400 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16401 int callingUid = Binder.getCallingUid(); 16402 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16403 throw new SecurityException( 16404 "setRequiredForSystemUser can only be run by the system or root"); 16405 } 16406 synchronized (mPackages) { 16407 PackageSetting ps = mSettings.mPackages.get(packageName); 16408 if (ps == null) { 16409 Log.w(TAG, "Package doesn't exist: " + packageName); 16410 return false; 16411 } 16412 if (systemUserApp) { 16413 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16414 } else { 16415 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16416 } 16417 mSettings.writeLPr(); 16418 } 16419 return true; 16420 } 16421 16422 /* 16423 * This method handles package deletion in general 16424 */ 16425 private boolean deletePackageLIF(String packageName, UserHandle user, 16426 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16427 PackageRemovedInfo outInfo, boolean writeSettings, 16428 PackageParser.Package replacingPackage) { 16429 if (packageName == null) { 16430 Slog.w(TAG, "Attempt to delete null packageName."); 16431 return false; 16432 } 16433 16434 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16435 16436 PackageSetting ps; 16437 16438 synchronized (mPackages) { 16439 ps = mSettings.mPackages.get(packageName); 16440 if (ps == null) { 16441 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16442 return false; 16443 } 16444 16445 if (ps.parentPackageName != null && (!isSystemApp(ps) 16446 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16447 if (DEBUG_REMOVE) { 16448 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16449 + ((user == null) ? UserHandle.USER_ALL : user)); 16450 } 16451 final int removedUserId = (user != null) ? user.getIdentifier() 16452 : UserHandle.USER_ALL; 16453 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16454 return false; 16455 } 16456 markPackageUninstalledForUserLPw(ps, user); 16457 scheduleWritePackageRestrictionsLocked(user); 16458 return true; 16459 } 16460 } 16461 16462 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16463 && user.getIdentifier() != UserHandle.USER_ALL)) { 16464 // The caller is asking that the package only be deleted for a single 16465 // user. To do this, we just mark its uninstalled state and delete 16466 // its data. If this is a system app, we only allow this to happen if 16467 // they have set the special DELETE_SYSTEM_APP which requests different 16468 // semantics than normal for uninstalling system apps. 16469 markPackageUninstalledForUserLPw(ps, user); 16470 16471 if (!isSystemApp(ps)) { 16472 // Do not uninstall the APK if an app should be cached 16473 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16474 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16475 // Other user still have this package installed, so all 16476 // we need to do is clear this user's data and save that 16477 // it is uninstalled. 16478 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16479 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16480 return false; 16481 } 16482 scheduleWritePackageRestrictionsLocked(user); 16483 return true; 16484 } else { 16485 // We need to set it back to 'installed' so the uninstall 16486 // broadcasts will be sent correctly. 16487 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16488 ps.setInstalled(true, user.getIdentifier()); 16489 } 16490 } else { 16491 // This is a system app, so we assume that the 16492 // other users still have this package installed, so all 16493 // we need to do is clear this user's data and save that 16494 // it is uninstalled. 16495 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16496 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16497 return false; 16498 } 16499 scheduleWritePackageRestrictionsLocked(user); 16500 return true; 16501 } 16502 } 16503 16504 // If we are deleting a composite package for all users, keep track 16505 // of result for each child. 16506 if (ps.childPackageNames != null && outInfo != null) { 16507 synchronized (mPackages) { 16508 final int childCount = ps.childPackageNames.size(); 16509 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16510 for (int i = 0; i < childCount; i++) { 16511 String childPackageName = ps.childPackageNames.get(i); 16512 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16513 childInfo.removedPackage = childPackageName; 16514 outInfo.removedChildPackages.put(childPackageName, childInfo); 16515 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16516 if (childPs != null) { 16517 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16518 } 16519 } 16520 } 16521 } 16522 16523 boolean ret = false; 16524 if (isSystemApp(ps)) { 16525 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16526 // When an updated system application is deleted we delete the existing resources 16527 // as well and fall back to existing code in system partition 16528 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16529 } else { 16530 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16531 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16532 outInfo, writeSettings, replacingPackage); 16533 } 16534 16535 // Take a note whether we deleted the package for all users 16536 if (outInfo != null) { 16537 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16538 if (outInfo.removedChildPackages != null) { 16539 synchronized (mPackages) { 16540 final int childCount = outInfo.removedChildPackages.size(); 16541 for (int i = 0; i < childCount; i++) { 16542 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16543 if (childInfo != null) { 16544 childInfo.removedForAllUsers = mPackages.get( 16545 childInfo.removedPackage) == null; 16546 } 16547 } 16548 } 16549 } 16550 // If we uninstalled an update to a system app there may be some 16551 // child packages that appeared as they are declared in the system 16552 // app but were not declared in the update. 16553 if (isSystemApp(ps)) { 16554 synchronized (mPackages) { 16555 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 16556 final int childCount = (updatedPs.childPackageNames != null) 16557 ? updatedPs.childPackageNames.size() : 0; 16558 for (int i = 0; i < childCount; i++) { 16559 String childPackageName = updatedPs.childPackageNames.get(i); 16560 if (outInfo.removedChildPackages == null 16561 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16562 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16563 if (childPs == null) { 16564 continue; 16565 } 16566 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16567 installRes.name = childPackageName; 16568 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16569 installRes.pkg = mPackages.get(childPackageName); 16570 installRes.uid = childPs.pkg.applicationInfo.uid; 16571 if (outInfo.appearedChildPackages == null) { 16572 outInfo.appearedChildPackages = new ArrayMap<>(); 16573 } 16574 outInfo.appearedChildPackages.put(childPackageName, installRes); 16575 } 16576 } 16577 } 16578 } 16579 } 16580 16581 return ret; 16582 } 16583 16584 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16585 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16586 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16587 for (int nextUserId : userIds) { 16588 if (DEBUG_REMOVE) { 16589 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16590 } 16591 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16592 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16593 false /*hidden*/, false /*suspended*/, null, null, null, 16594 false /*blockUninstall*/, 16595 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16596 } 16597 } 16598 16599 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16600 PackageRemovedInfo outInfo) { 16601 final PackageParser.Package pkg; 16602 synchronized (mPackages) { 16603 pkg = mPackages.get(ps.name); 16604 } 16605 16606 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16607 : new int[] {userId}; 16608 for (int nextUserId : userIds) { 16609 if (DEBUG_REMOVE) { 16610 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16611 + nextUserId); 16612 } 16613 16614 destroyAppDataLIF(pkg, userId, 16615 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16616 destroyAppProfilesLIF(pkg, userId); 16617 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16618 schedulePackageCleaning(ps.name, nextUserId, false); 16619 synchronized (mPackages) { 16620 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16621 scheduleWritePackageRestrictionsLocked(nextUserId); 16622 } 16623 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16624 } 16625 } 16626 16627 if (outInfo != null) { 16628 outInfo.removedPackage = ps.name; 16629 outInfo.removedAppId = ps.appId; 16630 outInfo.removedUsers = userIds; 16631 } 16632 16633 return true; 16634 } 16635 16636 private final class ClearStorageConnection implements ServiceConnection { 16637 IMediaContainerService mContainerService; 16638 16639 @Override 16640 public void onServiceConnected(ComponentName name, IBinder service) { 16641 synchronized (this) { 16642 mContainerService = IMediaContainerService.Stub 16643 .asInterface(Binder.allowBlocking(service)); 16644 notifyAll(); 16645 } 16646 } 16647 16648 @Override 16649 public void onServiceDisconnected(ComponentName name) { 16650 } 16651 } 16652 16653 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16654 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16655 16656 final boolean mounted; 16657 if (Environment.isExternalStorageEmulated()) { 16658 mounted = true; 16659 } else { 16660 final String status = Environment.getExternalStorageState(); 16661 16662 mounted = status.equals(Environment.MEDIA_MOUNTED) 16663 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16664 } 16665 16666 if (!mounted) { 16667 return; 16668 } 16669 16670 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16671 int[] users; 16672 if (userId == UserHandle.USER_ALL) { 16673 users = sUserManager.getUserIds(); 16674 } else { 16675 users = new int[] { userId }; 16676 } 16677 final ClearStorageConnection conn = new ClearStorageConnection(); 16678 if (mContext.bindServiceAsUser( 16679 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16680 try { 16681 for (int curUser : users) { 16682 long timeout = SystemClock.uptimeMillis() + 5000; 16683 synchronized (conn) { 16684 long now; 16685 while (conn.mContainerService == null && 16686 (now = SystemClock.uptimeMillis()) < timeout) { 16687 try { 16688 conn.wait(timeout - now); 16689 } catch (InterruptedException e) { 16690 } 16691 } 16692 } 16693 if (conn.mContainerService == null) { 16694 return; 16695 } 16696 16697 final UserEnvironment userEnv = new UserEnvironment(curUser); 16698 clearDirectory(conn.mContainerService, 16699 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16700 if (allData) { 16701 clearDirectory(conn.mContainerService, 16702 userEnv.buildExternalStorageAppDataDirs(packageName)); 16703 clearDirectory(conn.mContainerService, 16704 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16705 } 16706 } 16707 } finally { 16708 mContext.unbindService(conn); 16709 } 16710 } 16711 } 16712 16713 @Override 16714 public void clearApplicationProfileData(String packageName) { 16715 enforceSystemOrRoot("Only the system can clear all profile data"); 16716 16717 final PackageParser.Package pkg; 16718 synchronized (mPackages) { 16719 pkg = mPackages.get(packageName); 16720 } 16721 16722 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16723 synchronized (mInstallLock) { 16724 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16725 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16726 true /* removeBaseMarker */); 16727 } 16728 } 16729 } 16730 16731 @Override 16732 public void clearApplicationUserData(final String packageName, 16733 final IPackageDataObserver observer, final int userId) { 16734 mContext.enforceCallingOrSelfPermission( 16735 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16736 16737 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16738 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16739 16740 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16741 throw new SecurityException("Cannot clear data for a protected package: " 16742 + packageName); 16743 } 16744 // Queue up an async operation since the package deletion may take a little while. 16745 mHandler.post(new Runnable() { 16746 public void run() { 16747 mHandler.removeCallbacks(this); 16748 final boolean succeeded; 16749 try (PackageFreezer freezer = freezePackage(packageName, 16750 "clearApplicationUserData")) { 16751 synchronized (mInstallLock) { 16752 succeeded = clearApplicationUserDataLIF(packageName, userId); 16753 } 16754 clearExternalStorageDataSync(packageName, userId, true); 16755 } 16756 if (succeeded) { 16757 // invoke DeviceStorageMonitor's update method to clear any notifications 16758 DeviceStorageMonitorInternal dsm = LocalServices 16759 .getService(DeviceStorageMonitorInternal.class); 16760 if (dsm != null) { 16761 dsm.checkMemory(); 16762 } 16763 } 16764 if(observer != null) { 16765 try { 16766 observer.onRemoveCompleted(packageName, succeeded); 16767 } catch (RemoteException e) { 16768 Log.i(TAG, "Observer no longer exists."); 16769 } 16770 } //end if observer 16771 } //end run 16772 }); 16773 } 16774 16775 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16776 if (packageName == null) { 16777 Slog.w(TAG, "Attempt to delete null packageName."); 16778 return false; 16779 } 16780 16781 // Try finding details about the requested package 16782 PackageParser.Package pkg; 16783 synchronized (mPackages) { 16784 pkg = mPackages.get(packageName); 16785 if (pkg == null) { 16786 final PackageSetting ps = mSettings.mPackages.get(packageName); 16787 if (ps != null) { 16788 pkg = ps.pkg; 16789 } 16790 } 16791 16792 if (pkg == null) { 16793 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16794 return false; 16795 } 16796 16797 PackageSetting ps = (PackageSetting) pkg.mExtras; 16798 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16799 } 16800 16801 clearAppDataLIF(pkg, userId, 16802 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16803 16804 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16805 removeKeystoreDataIfNeeded(userId, appId); 16806 16807 UserManagerInternal umInternal = getUserManagerInternal(); 16808 final int flags; 16809 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16810 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16811 } else if (umInternal.isUserRunning(userId)) { 16812 flags = StorageManager.FLAG_STORAGE_DE; 16813 } else { 16814 flags = 0; 16815 } 16816 prepareAppDataContentsLIF(pkg, userId, flags); 16817 16818 return true; 16819 } 16820 16821 /** 16822 * Reverts user permission state changes (permissions and flags) in 16823 * all packages for a given user. 16824 * 16825 * @param userId The device user for which to do a reset. 16826 */ 16827 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16828 final int packageCount = mPackages.size(); 16829 for (int i = 0; i < packageCount; i++) { 16830 PackageParser.Package pkg = mPackages.valueAt(i); 16831 PackageSetting ps = (PackageSetting) pkg.mExtras; 16832 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16833 } 16834 } 16835 16836 private void resetNetworkPolicies(int userId) { 16837 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16838 } 16839 16840 /** 16841 * Reverts user permission state changes (permissions and flags). 16842 * 16843 * @param ps The package for which to reset. 16844 * @param userId The device user for which to do a reset. 16845 */ 16846 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16847 final PackageSetting ps, final int userId) { 16848 if (ps.pkg == null) { 16849 return; 16850 } 16851 16852 // These are flags that can change base on user actions. 16853 final int userSettableMask = FLAG_PERMISSION_USER_SET 16854 | FLAG_PERMISSION_USER_FIXED 16855 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16856 | FLAG_PERMISSION_REVIEW_REQUIRED; 16857 16858 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16859 | FLAG_PERMISSION_POLICY_FIXED; 16860 16861 boolean writeInstallPermissions = false; 16862 boolean writeRuntimePermissions = false; 16863 16864 final int permissionCount = ps.pkg.requestedPermissions.size(); 16865 for (int i = 0; i < permissionCount; i++) { 16866 String permission = ps.pkg.requestedPermissions.get(i); 16867 16868 BasePermission bp = mSettings.mPermissions.get(permission); 16869 if (bp == null) { 16870 continue; 16871 } 16872 16873 // If shared user we just reset the state to which only this app contributed. 16874 if (ps.sharedUser != null) { 16875 boolean used = false; 16876 final int packageCount = ps.sharedUser.packages.size(); 16877 for (int j = 0; j < packageCount; j++) { 16878 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16879 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16880 && pkg.pkg.requestedPermissions.contains(permission)) { 16881 used = true; 16882 break; 16883 } 16884 } 16885 if (used) { 16886 continue; 16887 } 16888 } 16889 16890 PermissionsState permissionsState = ps.getPermissionsState(); 16891 16892 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16893 16894 // Always clear the user settable flags. 16895 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16896 bp.name) != null; 16897 // If permission review is enabled and this is a legacy app, mark the 16898 // permission as requiring a review as this is the initial state. 16899 int flags = 0; 16900 if (mPermissionReviewRequired 16901 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16902 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16903 } 16904 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16905 if (hasInstallState) { 16906 writeInstallPermissions = true; 16907 } else { 16908 writeRuntimePermissions = true; 16909 } 16910 } 16911 16912 // Below is only runtime permission handling. 16913 if (!bp.isRuntime()) { 16914 continue; 16915 } 16916 16917 // Never clobber system or policy. 16918 if ((oldFlags & policyOrSystemFlags) != 0) { 16919 continue; 16920 } 16921 16922 // If this permission was granted by default, make sure it is. 16923 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16924 if (permissionsState.grantRuntimePermission(bp, userId) 16925 != PERMISSION_OPERATION_FAILURE) { 16926 writeRuntimePermissions = true; 16927 } 16928 // If permission review is enabled the permissions for a legacy apps 16929 // are represented as constantly granted runtime ones, so don't revoke. 16930 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16931 // Otherwise, reset the permission. 16932 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16933 switch (revokeResult) { 16934 case PERMISSION_OPERATION_SUCCESS: 16935 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16936 writeRuntimePermissions = true; 16937 final int appId = ps.appId; 16938 mHandler.post(new Runnable() { 16939 @Override 16940 public void run() { 16941 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16942 } 16943 }); 16944 } break; 16945 } 16946 } 16947 } 16948 16949 // Synchronously write as we are taking permissions away. 16950 if (writeRuntimePermissions) { 16951 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16952 } 16953 16954 // Synchronously write as we are taking permissions away. 16955 if (writeInstallPermissions) { 16956 mSettings.writeLPr(); 16957 } 16958 } 16959 16960 /** 16961 * Remove entries from the keystore daemon. Will only remove it if the 16962 * {@code appId} is valid. 16963 */ 16964 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16965 if (appId < 0) { 16966 return; 16967 } 16968 16969 final KeyStore keyStore = KeyStore.getInstance(); 16970 if (keyStore != null) { 16971 if (userId == UserHandle.USER_ALL) { 16972 for (final int individual : sUserManager.getUserIds()) { 16973 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16974 } 16975 } else { 16976 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16977 } 16978 } else { 16979 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16980 } 16981 } 16982 16983 @Override 16984 public void deleteApplicationCacheFiles(final String packageName, 16985 final IPackageDataObserver observer) { 16986 final int userId = UserHandle.getCallingUserId(); 16987 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16988 } 16989 16990 @Override 16991 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16992 final IPackageDataObserver observer) { 16993 mContext.enforceCallingOrSelfPermission( 16994 android.Manifest.permission.DELETE_CACHE_FILES, null); 16995 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16996 /* requireFullPermission= */ true, /* checkShell= */ false, 16997 "delete application cache files"); 16998 16999 final PackageParser.Package pkg; 17000 synchronized (mPackages) { 17001 pkg = mPackages.get(packageName); 17002 } 17003 17004 // Queue up an async operation since the package deletion may take a little while. 17005 mHandler.post(new Runnable() { 17006 public void run() { 17007 synchronized (mInstallLock) { 17008 final int flags = StorageManager.FLAG_STORAGE_DE 17009 | StorageManager.FLAG_STORAGE_CE; 17010 // We're only clearing cache files, so we don't care if the 17011 // app is unfrozen and still able to run 17012 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 17013 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 17014 } 17015 clearExternalStorageDataSync(packageName, userId, false); 17016 if (observer != null) { 17017 try { 17018 observer.onRemoveCompleted(packageName, true); 17019 } catch (RemoteException e) { 17020 Log.i(TAG, "Observer no longer exists."); 17021 } 17022 } 17023 } 17024 }); 17025 } 17026 17027 @Override 17028 public void getPackageSizeInfo(final String packageName, int userHandle, 17029 final IPackageStatsObserver observer) { 17030 mContext.enforceCallingOrSelfPermission( 17031 android.Manifest.permission.GET_PACKAGE_SIZE, null); 17032 if (packageName == null) { 17033 throw new IllegalArgumentException("Attempt to get size of null packageName"); 17034 } 17035 17036 PackageStats stats = new PackageStats(packageName, userHandle); 17037 17038 /* 17039 * Queue up an async operation since the package measurement may take a 17040 * little while. 17041 */ 17042 Message msg = mHandler.obtainMessage(INIT_COPY); 17043 msg.obj = new MeasureParams(stats, observer); 17044 mHandler.sendMessage(msg); 17045 } 17046 17047 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 17048 final PackageSetting ps; 17049 synchronized (mPackages) { 17050 ps = mSettings.mPackages.get(packageName); 17051 if (ps == null) { 17052 Slog.w(TAG, "Failed to find settings for " + packageName); 17053 return false; 17054 } 17055 } 17056 try { 17057 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 17058 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 17059 ps.getCeDataInode(userId), ps.codePathString, stats); 17060 } catch (InstallerException e) { 17061 Slog.w(TAG, String.valueOf(e)); 17062 return false; 17063 } 17064 17065 // For now, ignore code size of packages on system partition 17066 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 17067 stats.codeSize = 0; 17068 } 17069 17070 return true; 17071 } 17072 17073 private int getUidTargetSdkVersionLockedLPr(int uid) { 17074 Object obj = mSettings.getUserIdLPr(uid); 17075 if (obj instanceof SharedUserSetting) { 17076 final SharedUserSetting sus = (SharedUserSetting) obj; 17077 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 17078 final Iterator<PackageSetting> it = sus.packages.iterator(); 17079 while (it.hasNext()) { 17080 final PackageSetting ps = it.next(); 17081 if (ps.pkg != null) { 17082 int v = ps.pkg.applicationInfo.targetSdkVersion; 17083 if (v < vers) vers = v; 17084 } 17085 } 17086 return vers; 17087 } else if (obj instanceof PackageSetting) { 17088 final PackageSetting ps = (PackageSetting) obj; 17089 if (ps.pkg != null) { 17090 return ps.pkg.applicationInfo.targetSdkVersion; 17091 } 17092 } 17093 return Build.VERSION_CODES.CUR_DEVELOPMENT; 17094 } 17095 17096 @Override 17097 public void addPreferredActivity(IntentFilter filter, int match, 17098 ComponentName[] set, ComponentName activity, int userId) { 17099 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17100 "Adding preferred"); 17101 } 17102 17103 private void addPreferredActivityInternal(IntentFilter filter, int match, 17104 ComponentName[] set, ComponentName activity, boolean always, int userId, 17105 String opname) { 17106 // writer 17107 int callingUid = Binder.getCallingUid(); 17108 enforceCrossUserPermission(callingUid, userId, 17109 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 17110 if (filter.countActions() == 0) { 17111 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17112 return; 17113 } 17114 synchronized (mPackages) { 17115 if (mContext.checkCallingOrSelfPermission( 17116 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17117 != PackageManager.PERMISSION_GRANTED) { 17118 if (getUidTargetSdkVersionLockedLPr(callingUid) 17119 < Build.VERSION_CODES.FROYO) { 17120 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 17121 + callingUid); 17122 return; 17123 } 17124 mContext.enforceCallingOrSelfPermission( 17125 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17126 } 17127 17128 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 17129 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 17130 + userId + ":"); 17131 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17132 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 17133 scheduleWritePackageRestrictionsLocked(userId); 17134 postPreferredActivityChangedBroadcast(userId); 17135 } 17136 } 17137 17138 private void postPreferredActivityChangedBroadcast(int userId) { 17139 mHandler.post(() -> { 17140 final IActivityManager am = ActivityManager.getService(); 17141 if (am == null) { 17142 return; 17143 } 17144 17145 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 17146 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17147 try { 17148 am.broadcastIntent(null, intent, null, null, 17149 0, null, null, null, android.app.AppOpsManager.OP_NONE, 17150 null, false, false, userId); 17151 } catch (RemoteException e) { 17152 } 17153 }); 17154 } 17155 17156 @Override 17157 public void replacePreferredActivity(IntentFilter filter, int match, 17158 ComponentName[] set, ComponentName activity, int userId) { 17159 if (filter.countActions() != 1) { 17160 throw new IllegalArgumentException( 17161 "replacePreferredActivity expects filter to have only 1 action."); 17162 } 17163 if (filter.countDataAuthorities() != 0 17164 || filter.countDataPaths() != 0 17165 || filter.countDataSchemes() > 1 17166 || filter.countDataTypes() != 0) { 17167 throw new IllegalArgumentException( 17168 "replacePreferredActivity expects filter to have no data authorities, " + 17169 "paths, or types; and at most one scheme."); 17170 } 17171 17172 final int callingUid = Binder.getCallingUid(); 17173 enforceCrossUserPermission(callingUid, userId, 17174 true /* requireFullPermission */, false /* checkShell */, 17175 "replace preferred activity"); 17176 synchronized (mPackages) { 17177 if (mContext.checkCallingOrSelfPermission( 17178 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17179 != PackageManager.PERMISSION_GRANTED) { 17180 if (getUidTargetSdkVersionLockedLPr(callingUid) 17181 < Build.VERSION_CODES.FROYO) { 17182 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 17183 + Binder.getCallingUid()); 17184 return; 17185 } 17186 mContext.enforceCallingOrSelfPermission( 17187 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17188 } 17189 17190 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17191 if (pir != null) { 17192 // Get all of the existing entries that exactly match this filter. 17193 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 17194 if (existing != null && existing.size() == 1) { 17195 PreferredActivity cur = existing.get(0); 17196 if (DEBUG_PREFERRED) { 17197 Slog.i(TAG, "Checking replace of preferred:"); 17198 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17199 if (!cur.mPref.mAlways) { 17200 Slog.i(TAG, " -- CUR; not mAlways!"); 17201 } else { 17202 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 17203 Slog.i(TAG, " -- CUR: mSet=" 17204 + Arrays.toString(cur.mPref.mSetComponents)); 17205 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 17206 Slog.i(TAG, " -- NEW: mMatch=" 17207 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 17208 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17209 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17210 } 17211 } 17212 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17213 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17214 && cur.mPref.sameSet(set)) { 17215 // Setting the preferred activity to what it happens to be already 17216 if (DEBUG_PREFERRED) { 17217 Slog.i(TAG, "Replacing with same preferred activity " 17218 + cur.mPref.mShortComponent + " for user " 17219 + userId + ":"); 17220 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17221 } 17222 return; 17223 } 17224 } 17225 17226 if (existing != null) { 17227 if (DEBUG_PREFERRED) { 17228 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17229 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17230 } 17231 for (int i = 0; i < existing.size(); i++) { 17232 PreferredActivity pa = existing.get(i); 17233 if (DEBUG_PREFERRED) { 17234 Slog.i(TAG, "Removing existing preferred activity " 17235 + pa.mPref.mComponent + ":"); 17236 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17237 } 17238 pir.removeFilter(pa); 17239 } 17240 } 17241 } 17242 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17243 "Replacing preferred"); 17244 } 17245 } 17246 17247 @Override 17248 public void clearPackagePreferredActivities(String packageName) { 17249 final int uid = Binder.getCallingUid(); 17250 // writer 17251 synchronized (mPackages) { 17252 PackageParser.Package pkg = mPackages.get(packageName); 17253 if (pkg == null || pkg.applicationInfo.uid != uid) { 17254 if (mContext.checkCallingOrSelfPermission( 17255 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17256 != PackageManager.PERMISSION_GRANTED) { 17257 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17258 < Build.VERSION_CODES.FROYO) { 17259 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17260 + Binder.getCallingUid()); 17261 return; 17262 } 17263 mContext.enforceCallingOrSelfPermission( 17264 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17265 } 17266 } 17267 17268 int user = UserHandle.getCallingUserId(); 17269 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17270 scheduleWritePackageRestrictionsLocked(user); 17271 } 17272 } 17273 } 17274 17275 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17276 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17277 ArrayList<PreferredActivity> removed = null; 17278 boolean changed = false; 17279 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17280 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17281 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17282 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17283 continue; 17284 } 17285 Iterator<PreferredActivity> it = pir.filterIterator(); 17286 while (it.hasNext()) { 17287 PreferredActivity pa = it.next(); 17288 // Mark entry for removal only if it matches the package name 17289 // and the entry is of type "always". 17290 if (packageName == null || 17291 (pa.mPref.mComponent.getPackageName().equals(packageName) 17292 && pa.mPref.mAlways)) { 17293 if (removed == null) { 17294 removed = new ArrayList<PreferredActivity>(); 17295 } 17296 removed.add(pa); 17297 } 17298 } 17299 if (removed != null) { 17300 for (int j=0; j<removed.size(); j++) { 17301 PreferredActivity pa = removed.get(j); 17302 pir.removeFilter(pa); 17303 } 17304 changed = true; 17305 } 17306 } 17307 if (changed) { 17308 postPreferredActivityChangedBroadcast(userId); 17309 } 17310 return changed; 17311 } 17312 17313 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17314 private void clearIntentFilterVerificationsLPw(int userId) { 17315 final int packageCount = mPackages.size(); 17316 for (int i = 0; i < packageCount; i++) { 17317 PackageParser.Package pkg = mPackages.valueAt(i); 17318 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17319 } 17320 } 17321 17322 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17323 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17324 if (userId == UserHandle.USER_ALL) { 17325 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17326 sUserManager.getUserIds())) { 17327 for (int oneUserId : sUserManager.getUserIds()) { 17328 scheduleWritePackageRestrictionsLocked(oneUserId); 17329 } 17330 } 17331 } else { 17332 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17333 scheduleWritePackageRestrictionsLocked(userId); 17334 } 17335 } 17336 } 17337 17338 void clearDefaultBrowserIfNeeded(String packageName) { 17339 for (int oneUserId : sUserManager.getUserIds()) { 17340 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17341 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17342 if (packageName.equals(defaultBrowserPackageName)) { 17343 setDefaultBrowserPackageName(null, oneUserId); 17344 } 17345 } 17346 } 17347 17348 @Override 17349 public void resetApplicationPreferences(int userId) { 17350 mContext.enforceCallingOrSelfPermission( 17351 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17352 final long identity = Binder.clearCallingIdentity(); 17353 // writer 17354 try { 17355 synchronized (mPackages) { 17356 clearPackagePreferredActivitiesLPw(null, userId); 17357 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17358 // TODO: We have to reset the default SMS and Phone. This requires 17359 // significant refactoring to keep all default apps in the package 17360 // manager (cleaner but more work) or have the services provide 17361 // callbacks to the package manager to request a default app reset. 17362 applyFactoryDefaultBrowserLPw(userId); 17363 clearIntentFilterVerificationsLPw(userId); 17364 primeDomainVerificationsLPw(userId); 17365 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17366 scheduleWritePackageRestrictionsLocked(userId); 17367 } 17368 resetNetworkPolicies(userId); 17369 } finally { 17370 Binder.restoreCallingIdentity(identity); 17371 } 17372 } 17373 17374 @Override 17375 public int getPreferredActivities(List<IntentFilter> outFilters, 17376 List<ComponentName> outActivities, String packageName) { 17377 17378 int num = 0; 17379 final int userId = UserHandle.getCallingUserId(); 17380 // reader 17381 synchronized (mPackages) { 17382 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17383 if (pir != null) { 17384 final Iterator<PreferredActivity> it = pir.filterIterator(); 17385 while (it.hasNext()) { 17386 final PreferredActivity pa = it.next(); 17387 if (packageName == null 17388 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17389 && pa.mPref.mAlways)) { 17390 if (outFilters != null) { 17391 outFilters.add(new IntentFilter(pa)); 17392 } 17393 if (outActivities != null) { 17394 outActivities.add(pa.mPref.mComponent); 17395 } 17396 } 17397 } 17398 } 17399 } 17400 17401 return num; 17402 } 17403 17404 @Override 17405 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17406 int userId) { 17407 int callingUid = Binder.getCallingUid(); 17408 if (callingUid != Process.SYSTEM_UID) { 17409 throw new SecurityException( 17410 "addPersistentPreferredActivity can only be run by the system"); 17411 } 17412 if (filter.countActions() == 0) { 17413 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17414 return; 17415 } 17416 synchronized (mPackages) { 17417 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17418 ":"); 17419 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17420 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17421 new PersistentPreferredActivity(filter, activity)); 17422 scheduleWritePackageRestrictionsLocked(userId); 17423 postPreferredActivityChangedBroadcast(userId); 17424 } 17425 } 17426 17427 @Override 17428 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17429 int callingUid = Binder.getCallingUid(); 17430 if (callingUid != Process.SYSTEM_UID) { 17431 throw new SecurityException( 17432 "clearPackagePersistentPreferredActivities can only be run by the system"); 17433 } 17434 ArrayList<PersistentPreferredActivity> removed = null; 17435 boolean changed = false; 17436 synchronized (mPackages) { 17437 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17438 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17439 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17440 .valueAt(i); 17441 if (userId != thisUserId) { 17442 continue; 17443 } 17444 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17445 while (it.hasNext()) { 17446 PersistentPreferredActivity ppa = it.next(); 17447 // Mark entry for removal only if it matches the package name. 17448 if (ppa.mComponent.getPackageName().equals(packageName)) { 17449 if (removed == null) { 17450 removed = new ArrayList<PersistentPreferredActivity>(); 17451 } 17452 removed.add(ppa); 17453 } 17454 } 17455 if (removed != null) { 17456 for (int j=0; j<removed.size(); j++) { 17457 PersistentPreferredActivity ppa = removed.get(j); 17458 ppir.removeFilter(ppa); 17459 } 17460 changed = true; 17461 } 17462 } 17463 17464 if (changed) { 17465 scheduleWritePackageRestrictionsLocked(userId); 17466 postPreferredActivityChangedBroadcast(userId); 17467 } 17468 } 17469 } 17470 17471 /** 17472 * Common machinery for picking apart a restored XML blob and passing 17473 * it to a caller-supplied functor to be applied to the running system. 17474 */ 17475 private void restoreFromXml(XmlPullParser parser, int userId, 17476 String expectedStartTag, BlobXmlRestorer functor) 17477 throws IOException, XmlPullParserException { 17478 int type; 17479 while ((type = parser.next()) != XmlPullParser.START_TAG 17480 && type != XmlPullParser.END_DOCUMENT) { 17481 } 17482 if (type != XmlPullParser.START_TAG) { 17483 // oops didn't find a start tag?! 17484 if (DEBUG_BACKUP) { 17485 Slog.e(TAG, "Didn't find start tag during restore"); 17486 } 17487 return; 17488 } 17489Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17490 // this is supposed to be TAG_PREFERRED_BACKUP 17491 if (!expectedStartTag.equals(parser.getName())) { 17492 if (DEBUG_BACKUP) { 17493 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17494 } 17495 return; 17496 } 17497 17498 // skip interfering stuff, then we're aligned with the backing implementation 17499 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17500Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17501 functor.apply(parser, userId); 17502 } 17503 17504 private interface BlobXmlRestorer { 17505 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17506 } 17507 17508 /** 17509 * Non-Binder method, support for the backup/restore mechanism: write the 17510 * full set of preferred activities in its canonical XML format. Returns the 17511 * XML output as a byte array, or null if there is none. 17512 */ 17513 @Override 17514 public byte[] getPreferredActivityBackup(int userId) { 17515 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17516 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17517 } 17518 17519 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17520 try { 17521 final XmlSerializer serializer = new FastXmlSerializer(); 17522 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17523 serializer.startDocument(null, true); 17524 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17525 17526 synchronized (mPackages) { 17527 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17528 } 17529 17530 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17531 serializer.endDocument(); 17532 serializer.flush(); 17533 } catch (Exception e) { 17534 if (DEBUG_BACKUP) { 17535 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17536 } 17537 return null; 17538 } 17539 17540 return dataStream.toByteArray(); 17541 } 17542 17543 @Override 17544 public void restorePreferredActivities(byte[] backup, int userId) { 17545 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17546 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17547 } 17548 17549 try { 17550 final XmlPullParser parser = Xml.newPullParser(); 17551 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17552 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17553 new BlobXmlRestorer() { 17554 @Override 17555 public void apply(XmlPullParser parser, int userId) 17556 throws XmlPullParserException, IOException { 17557 synchronized (mPackages) { 17558 mSettings.readPreferredActivitiesLPw(parser, userId); 17559 } 17560 } 17561 } ); 17562 } catch (Exception e) { 17563 if (DEBUG_BACKUP) { 17564 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17565 } 17566 } 17567 } 17568 17569 /** 17570 * Non-Binder method, support for the backup/restore mechanism: write the 17571 * default browser (etc) settings in its canonical XML format. Returns the default 17572 * browser XML representation as a byte array, or null if there is none. 17573 */ 17574 @Override 17575 public byte[] getDefaultAppsBackup(int userId) { 17576 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17577 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17578 } 17579 17580 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17581 try { 17582 final XmlSerializer serializer = new FastXmlSerializer(); 17583 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17584 serializer.startDocument(null, true); 17585 serializer.startTag(null, TAG_DEFAULT_APPS); 17586 17587 synchronized (mPackages) { 17588 mSettings.writeDefaultAppsLPr(serializer, userId); 17589 } 17590 17591 serializer.endTag(null, TAG_DEFAULT_APPS); 17592 serializer.endDocument(); 17593 serializer.flush(); 17594 } catch (Exception e) { 17595 if (DEBUG_BACKUP) { 17596 Slog.e(TAG, "Unable to write default apps for backup", e); 17597 } 17598 return null; 17599 } 17600 17601 return dataStream.toByteArray(); 17602 } 17603 17604 @Override 17605 public void restoreDefaultApps(byte[] backup, int userId) { 17606 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17607 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17608 } 17609 17610 try { 17611 final XmlPullParser parser = Xml.newPullParser(); 17612 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17613 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17614 new BlobXmlRestorer() { 17615 @Override 17616 public void apply(XmlPullParser parser, int userId) 17617 throws XmlPullParserException, IOException { 17618 synchronized (mPackages) { 17619 mSettings.readDefaultAppsLPw(parser, userId); 17620 } 17621 } 17622 } ); 17623 } catch (Exception e) { 17624 if (DEBUG_BACKUP) { 17625 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17626 } 17627 } 17628 } 17629 17630 @Override 17631 public byte[] getIntentFilterVerificationBackup(int userId) { 17632 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17633 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17634 } 17635 17636 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17637 try { 17638 final XmlSerializer serializer = new FastXmlSerializer(); 17639 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17640 serializer.startDocument(null, true); 17641 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17642 17643 synchronized (mPackages) { 17644 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17645 } 17646 17647 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17648 serializer.endDocument(); 17649 serializer.flush(); 17650 } catch (Exception e) { 17651 if (DEBUG_BACKUP) { 17652 Slog.e(TAG, "Unable to write default apps for backup", e); 17653 } 17654 return null; 17655 } 17656 17657 return dataStream.toByteArray(); 17658 } 17659 17660 @Override 17661 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17662 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17663 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17664 } 17665 17666 try { 17667 final XmlPullParser parser = Xml.newPullParser(); 17668 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17669 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17670 new BlobXmlRestorer() { 17671 @Override 17672 public void apply(XmlPullParser parser, int userId) 17673 throws XmlPullParserException, IOException { 17674 synchronized (mPackages) { 17675 mSettings.readAllDomainVerificationsLPr(parser, userId); 17676 mSettings.writeLPr(); 17677 } 17678 } 17679 } ); 17680 } catch (Exception e) { 17681 if (DEBUG_BACKUP) { 17682 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17683 } 17684 } 17685 } 17686 17687 @Override 17688 public byte[] getPermissionGrantBackup(int userId) { 17689 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17690 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17691 } 17692 17693 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17694 try { 17695 final XmlSerializer serializer = new FastXmlSerializer(); 17696 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17697 serializer.startDocument(null, true); 17698 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17699 17700 synchronized (mPackages) { 17701 serializeRuntimePermissionGrantsLPr(serializer, userId); 17702 } 17703 17704 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17705 serializer.endDocument(); 17706 serializer.flush(); 17707 } catch (Exception e) { 17708 if (DEBUG_BACKUP) { 17709 Slog.e(TAG, "Unable to write default apps for backup", e); 17710 } 17711 return null; 17712 } 17713 17714 return dataStream.toByteArray(); 17715 } 17716 17717 @Override 17718 public void restorePermissionGrants(byte[] backup, int userId) { 17719 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17720 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17721 } 17722 17723 try { 17724 final XmlPullParser parser = Xml.newPullParser(); 17725 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17726 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17727 new BlobXmlRestorer() { 17728 @Override 17729 public void apply(XmlPullParser parser, int userId) 17730 throws XmlPullParserException, IOException { 17731 synchronized (mPackages) { 17732 processRestoredPermissionGrantsLPr(parser, userId); 17733 } 17734 } 17735 } ); 17736 } catch (Exception e) { 17737 if (DEBUG_BACKUP) { 17738 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17739 } 17740 } 17741 } 17742 17743 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17744 throws IOException { 17745 serializer.startTag(null, TAG_ALL_GRANTS); 17746 17747 final int N = mSettings.mPackages.size(); 17748 for (int i = 0; i < N; i++) { 17749 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17750 boolean pkgGrantsKnown = false; 17751 17752 PermissionsState packagePerms = ps.getPermissionsState(); 17753 17754 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17755 final int grantFlags = state.getFlags(); 17756 // only look at grants that are not system/policy fixed 17757 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17758 final boolean isGranted = state.isGranted(); 17759 // And only back up the user-twiddled state bits 17760 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17761 final String packageName = mSettings.mPackages.keyAt(i); 17762 if (!pkgGrantsKnown) { 17763 serializer.startTag(null, TAG_GRANT); 17764 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17765 pkgGrantsKnown = true; 17766 } 17767 17768 final boolean userSet = 17769 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17770 final boolean userFixed = 17771 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17772 final boolean revoke = 17773 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17774 17775 serializer.startTag(null, TAG_PERMISSION); 17776 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17777 if (isGranted) { 17778 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17779 } 17780 if (userSet) { 17781 serializer.attribute(null, ATTR_USER_SET, "true"); 17782 } 17783 if (userFixed) { 17784 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17785 } 17786 if (revoke) { 17787 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17788 } 17789 serializer.endTag(null, TAG_PERMISSION); 17790 } 17791 } 17792 } 17793 17794 if (pkgGrantsKnown) { 17795 serializer.endTag(null, TAG_GRANT); 17796 } 17797 } 17798 17799 serializer.endTag(null, TAG_ALL_GRANTS); 17800 } 17801 17802 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17803 throws XmlPullParserException, IOException { 17804 String pkgName = null; 17805 int outerDepth = parser.getDepth(); 17806 int type; 17807 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17808 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17809 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17810 continue; 17811 } 17812 17813 final String tagName = parser.getName(); 17814 if (tagName.equals(TAG_GRANT)) { 17815 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17816 if (DEBUG_BACKUP) { 17817 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17818 } 17819 } else if (tagName.equals(TAG_PERMISSION)) { 17820 17821 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17822 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17823 17824 int newFlagSet = 0; 17825 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17826 newFlagSet |= FLAG_PERMISSION_USER_SET; 17827 } 17828 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17829 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17830 } 17831 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17832 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17833 } 17834 if (DEBUG_BACKUP) { 17835 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17836 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17837 } 17838 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17839 if (ps != null) { 17840 // Already installed so we apply the grant immediately 17841 if (DEBUG_BACKUP) { 17842 Slog.v(TAG, " + already installed; applying"); 17843 } 17844 PermissionsState perms = ps.getPermissionsState(); 17845 BasePermission bp = mSettings.mPermissions.get(permName); 17846 if (bp != null) { 17847 if (isGranted) { 17848 perms.grantRuntimePermission(bp, userId); 17849 } 17850 if (newFlagSet != 0) { 17851 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17852 } 17853 } 17854 } else { 17855 // Need to wait for post-restore install to apply the grant 17856 if (DEBUG_BACKUP) { 17857 Slog.v(TAG, " - not yet installed; saving for later"); 17858 } 17859 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17860 isGranted, newFlagSet, userId); 17861 } 17862 } else { 17863 PackageManagerService.reportSettingsProblem(Log.WARN, 17864 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17865 XmlUtils.skipCurrentTag(parser); 17866 } 17867 } 17868 17869 scheduleWriteSettingsLocked(); 17870 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17871 } 17872 17873 @Override 17874 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17875 int sourceUserId, int targetUserId, int flags) { 17876 mContext.enforceCallingOrSelfPermission( 17877 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17878 int callingUid = Binder.getCallingUid(); 17879 enforceOwnerRights(ownerPackage, callingUid); 17880 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17881 if (intentFilter.countActions() == 0) { 17882 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17883 return; 17884 } 17885 synchronized (mPackages) { 17886 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17887 ownerPackage, targetUserId, flags); 17888 CrossProfileIntentResolver resolver = 17889 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17890 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17891 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17892 if (existing != null) { 17893 int size = existing.size(); 17894 for (int i = 0; i < size; i++) { 17895 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17896 return; 17897 } 17898 } 17899 } 17900 resolver.addFilter(newFilter); 17901 scheduleWritePackageRestrictionsLocked(sourceUserId); 17902 } 17903 } 17904 17905 @Override 17906 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17907 mContext.enforceCallingOrSelfPermission( 17908 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17909 int callingUid = Binder.getCallingUid(); 17910 enforceOwnerRights(ownerPackage, callingUid); 17911 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17912 synchronized (mPackages) { 17913 CrossProfileIntentResolver resolver = 17914 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17915 ArraySet<CrossProfileIntentFilter> set = 17916 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17917 for (CrossProfileIntentFilter filter : set) { 17918 if (filter.getOwnerPackage().equals(ownerPackage)) { 17919 resolver.removeFilter(filter); 17920 } 17921 } 17922 scheduleWritePackageRestrictionsLocked(sourceUserId); 17923 } 17924 } 17925 17926 // Enforcing that callingUid is owning pkg on userId 17927 private void enforceOwnerRights(String pkg, int callingUid) { 17928 // The system owns everything. 17929 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17930 return; 17931 } 17932 int callingUserId = UserHandle.getUserId(callingUid); 17933 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17934 if (pi == null) { 17935 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17936 + callingUserId); 17937 } 17938 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17939 throw new SecurityException("Calling uid " + callingUid 17940 + " does not own package " + pkg); 17941 } 17942 } 17943 17944 @Override 17945 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17946 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17947 } 17948 17949 private Intent getHomeIntent() { 17950 Intent intent = new Intent(Intent.ACTION_MAIN); 17951 intent.addCategory(Intent.CATEGORY_HOME); 17952 intent.addCategory(Intent.CATEGORY_DEFAULT); 17953 return intent; 17954 } 17955 17956 private IntentFilter getHomeFilter() { 17957 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17958 filter.addCategory(Intent.CATEGORY_HOME); 17959 filter.addCategory(Intent.CATEGORY_DEFAULT); 17960 return filter; 17961 } 17962 17963 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17964 int userId) { 17965 Intent intent = getHomeIntent(); 17966 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17967 PackageManager.GET_META_DATA, userId); 17968 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17969 true, false, false, userId); 17970 17971 allHomeCandidates.clear(); 17972 if (list != null) { 17973 for (ResolveInfo ri : list) { 17974 allHomeCandidates.add(ri); 17975 } 17976 } 17977 return (preferred == null || preferred.activityInfo == null) 17978 ? null 17979 : new ComponentName(preferred.activityInfo.packageName, 17980 preferred.activityInfo.name); 17981 } 17982 17983 @Override 17984 public void setHomeActivity(ComponentName comp, int userId) { 17985 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17986 getHomeActivitiesAsUser(homeActivities, userId); 17987 17988 boolean found = false; 17989 17990 final int size = homeActivities.size(); 17991 final ComponentName[] set = new ComponentName[size]; 17992 for (int i = 0; i < size; i++) { 17993 final ResolveInfo candidate = homeActivities.get(i); 17994 final ActivityInfo info = candidate.activityInfo; 17995 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17996 set[i] = activityName; 17997 if (!found && activityName.equals(comp)) { 17998 found = true; 17999 } 18000 } 18001 if (!found) { 18002 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 18003 + userId); 18004 } 18005 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 18006 set, comp, userId); 18007 } 18008 18009 private @Nullable String getSetupWizardPackageName() { 18010 final Intent intent = new Intent(Intent.ACTION_MAIN); 18011 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 18012 18013 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18014 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18015 | MATCH_DISABLED_COMPONENTS, 18016 UserHandle.myUserId()); 18017 if (matches.size() == 1) { 18018 return matches.get(0).getComponentInfo().packageName; 18019 } else { 18020 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 18021 + ": matches=" + matches); 18022 return null; 18023 } 18024 } 18025 18026 private @Nullable String getStorageManagerPackageName() { 18027 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 18028 18029 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18030 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18031 | MATCH_DISABLED_COMPONENTS, 18032 UserHandle.myUserId()); 18033 if (matches.size() == 1) { 18034 return matches.get(0).getComponentInfo().packageName; 18035 } else { 18036 Slog.e(TAG, "There should probably be exactly one storage manager; found " 18037 + matches.size() + ": matches=" + matches); 18038 return null; 18039 } 18040 } 18041 18042 @Override 18043 public void setApplicationEnabledSetting(String appPackageName, 18044 int newState, int flags, int userId, String callingPackage) { 18045 if (!sUserManager.exists(userId)) return; 18046 if (callingPackage == null) { 18047 callingPackage = Integer.toString(Binder.getCallingUid()); 18048 } 18049 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 18050 } 18051 18052 @Override 18053 public void setComponentEnabledSetting(ComponentName componentName, 18054 int newState, int flags, int userId) { 18055 if (!sUserManager.exists(userId)) return; 18056 setEnabledSetting(componentName.getPackageName(), 18057 componentName.getClassName(), newState, flags, userId, null); 18058 } 18059 18060 private void setEnabledSetting(final String packageName, String className, int newState, 18061 final int flags, int userId, String callingPackage) { 18062 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 18063 || newState == COMPONENT_ENABLED_STATE_ENABLED 18064 || newState == COMPONENT_ENABLED_STATE_DISABLED 18065 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18066 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 18067 throw new IllegalArgumentException("Invalid new component state: " 18068 + newState); 18069 } 18070 PackageSetting pkgSetting; 18071 final int uid = Binder.getCallingUid(); 18072 final int permission; 18073 if (uid == Process.SYSTEM_UID) { 18074 permission = PackageManager.PERMISSION_GRANTED; 18075 } else { 18076 permission = mContext.checkCallingOrSelfPermission( 18077 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18078 } 18079 enforceCrossUserPermission(uid, userId, 18080 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 18081 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18082 boolean sendNow = false; 18083 boolean isApp = (className == null); 18084 String componentName = isApp ? packageName : className; 18085 int packageUid = -1; 18086 ArrayList<String> components; 18087 18088 // writer 18089 synchronized (mPackages) { 18090 pkgSetting = mSettings.mPackages.get(packageName); 18091 if (pkgSetting == null) { 18092 if (className == null) { 18093 throw new IllegalArgumentException("Unknown package: " + packageName); 18094 } 18095 throw new IllegalArgumentException( 18096 "Unknown component: " + packageName + "/" + className); 18097 } 18098 } 18099 18100 // Limit who can change which apps 18101 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 18102 // Don't allow apps that don't have permission to modify other apps 18103 if (!allowedByPermission) { 18104 throw new SecurityException( 18105 "Permission Denial: attempt to change component state from pid=" 18106 + Binder.getCallingPid() 18107 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 18108 } 18109 // Don't allow changing protected packages. 18110 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 18111 throw new SecurityException("Cannot disable a protected package: " + packageName); 18112 } 18113 } 18114 18115 synchronized (mPackages) { 18116 if (uid == Process.SHELL_UID 18117 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 18118 // Shell can only change whole packages between ENABLED and DISABLED_USER states 18119 // unless it is a test package. 18120 int oldState = pkgSetting.getEnabled(userId); 18121 if (className == null 18122 && 18123 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 18124 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 18125 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 18126 && 18127 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18128 || newState == COMPONENT_ENABLED_STATE_DEFAULT 18129 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 18130 // ok 18131 } else { 18132 throw new SecurityException( 18133 "Shell cannot change component state for " + packageName + "/" 18134 + className + " to " + newState); 18135 } 18136 } 18137 if (className == null) { 18138 // We're dealing with an application/package level state change 18139 if (pkgSetting.getEnabled(userId) == newState) { 18140 // Nothing to do 18141 return; 18142 } 18143 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 18144 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 18145 // Don't care about who enables an app. 18146 callingPackage = null; 18147 } 18148 pkgSetting.setEnabled(newState, userId, callingPackage); 18149 // pkgSetting.pkg.mSetEnabled = newState; 18150 } else { 18151 // We're dealing with a component level state change 18152 // First, verify that this is a valid class name. 18153 PackageParser.Package pkg = pkgSetting.pkg; 18154 if (pkg == null || !pkg.hasComponentClassName(className)) { 18155 if (pkg != null && 18156 pkg.applicationInfo.targetSdkVersion >= 18157 Build.VERSION_CODES.JELLY_BEAN) { 18158 throw new IllegalArgumentException("Component class " + className 18159 + " does not exist in " + packageName); 18160 } else { 18161 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 18162 + className + " does not exist in " + packageName); 18163 } 18164 } 18165 switch (newState) { 18166 case COMPONENT_ENABLED_STATE_ENABLED: 18167 if (!pkgSetting.enableComponentLPw(className, userId)) { 18168 return; 18169 } 18170 break; 18171 case COMPONENT_ENABLED_STATE_DISABLED: 18172 if (!pkgSetting.disableComponentLPw(className, userId)) { 18173 return; 18174 } 18175 break; 18176 case COMPONENT_ENABLED_STATE_DEFAULT: 18177 if (!pkgSetting.restoreComponentLPw(className, userId)) { 18178 return; 18179 } 18180 break; 18181 default: 18182 Slog.e(TAG, "Invalid new component state: " + newState); 18183 return; 18184 } 18185 } 18186 scheduleWritePackageRestrictionsLocked(userId); 18187 components = mPendingBroadcasts.get(userId, packageName); 18188 final boolean newPackage = components == null; 18189 if (newPackage) { 18190 components = new ArrayList<String>(); 18191 } 18192 if (!components.contains(componentName)) { 18193 components.add(componentName); 18194 } 18195 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 18196 sendNow = true; 18197 // Purge entry from pending broadcast list if another one exists already 18198 // since we are sending one right away. 18199 mPendingBroadcasts.remove(userId, packageName); 18200 } else { 18201 if (newPackage) { 18202 mPendingBroadcasts.put(userId, packageName, components); 18203 } 18204 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 18205 // Schedule a message 18206 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 18207 } 18208 } 18209 } 18210 18211 long callingId = Binder.clearCallingIdentity(); 18212 try { 18213 if (sendNow) { 18214 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18215 sendPackageChangedBroadcast(packageName, 18216 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18217 } 18218 } finally { 18219 Binder.restoreCallingIdentity(callingId); 18220 } 18221 } 18222 18223 @Override 18224 public void flushPackageRestrictionsAsUser(int userId) { 18225 if (!sUserManager.exists(userId)) { 18226 return; 18227 } 18228 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18229 false /* checkShell */, "flushPackageRestrictions"); 18230 synchronized (mPackages) { 18231 mSettings.writePackageRestrictionsLPr(userId); 18232 mDirtyUsers.remove(userId); 18233 if (mDirtyUsers.isEmpty()) { 18234 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18235 } 18236 } 18237 } 18238 18239 private void sendPackageChangedBroadcast(String packageName, 18240 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18241 if (DEBUG_INSTALL) 18242 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18243 + componentNames); 18244 Bundle extras = new Bundle(4); 18245 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18246 String nameList[] = new String[componentNames.size()]; 18247 componentNames.toArray(nameList); 18248 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18249 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18250 extras.putInt(Intent.EXTRA_UID, packageUid); 18251 // If this is not reporting a change of the overall package, then only send it 18252 // to registered receivers. We don't want to launch a swath of apps for every 18253 // little component state change. 18254 final int flags = !componentNames.contains(packageName) 18255 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18256 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18257 new int[] {UserHandle.getUserId(packageUid)}); 18258 } 18259 18260 @Override 18261 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18262 if (!sUserManager.exists(userId)) return; 18263 final int uid = Binder.getCallingUid(); 18264 final int permission = mContext.checkCallingOrSelfPermission( 18265 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18266 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18267 enforceCrossUserPermission(uid, userId, 18268 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18269 // writer 18270 synchronized (mPackages) { 18271 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18272 allowedByPermission, uid, userId)) { 18273 scheduleWritePackageRestrictionsLocked(userId); 18274 } 18275 } 18276 } 18277 18278 @Override 18279 public String getInstallerPackageName(String packageName) { 18280 // reader 18281 synchronized (mPackages) { 18282 return mSettings.getInstallerPackageNameLPr(packageName); 18283 } 18284 } 18285 18286 public boolean isOrphaned(String packageName) { 18287 // reader 18288 synchronized (mPackages) { 18289 return mSettings.isOrphaned(packageName); 18290 } 18291 } 18292 18293 @Override 18294 public int getApplicationEnabledSetting(String packageName, int userId) { 18295 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18296 int uid = Binder.getCallingUid(); 18297 enforceCrossUserPermission(uid, userId, 18298 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18299 // reader 18300 synchronized (mPackages) { 18301 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18302 } 18303 } 18304 18305 @Override 18306 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18307 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18308 int uid = Binder.getCallingUid(); 18309 enforceCrossUserPermission(uid, userId, 18310 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18311 // reader 18312 synchronized (mPackages) { 18313 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18314 } 18315 } 18316 18317 @Override 18318 public void enterSafeMode() { 18319 enforceSystemOrRoot("Only the system can request entering safe mode"); 18320 18321 if (!mSystemReady) { 18322 mSafeMode = true; 18323 } 18324 } 18325 18326 @Override 18327 public void systemReady() { 18328 mSystemReady = true; 18329 18330 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18331 // disabled after already being started. 18332 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18333 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18334 18335 // Read the compatibilty setting when the system is ready. 18336 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18337 mContext.getContentResolver(), 18338 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18339 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18340 if (DEBUG_SETTINGS) { 18341 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18342 } 18343 18344 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18345 18346 synchronized (mPackages) { 18347 // Verify that all of the preferred activity components actually 18348 // exist. It is possible for applications to be updated and at 18349 // that point remove a previously declared activity component that 18350 // had been set as a preferred activity. We try to clean this up 18351 // the next time we encounter that preferred activity, but it is 18352 // possible for the user flow to never be able to return to that 18353 // situation so here we do a sanity check to make sure we haven't 18354 // left any junk around. 18355 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18356 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18357 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18358 removed.clear(); 18359 for (PreferredActivity pa : pir.filterSet()) { 18360 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18361 removed.add(pa); 18362 } 18363 } 18364 if (removed.size() > 0) { 18365 for (int r=0; r<removed.size(); r++) { 18366 PreferredActivity pa = removed.get(r); 18367 Slog.w(TAG, "Removing dangling preferred activity: " 18368 + pa.mPref.mComponent); 18369 pir.removeFilter(pa); 18370 } 18371 mSettings.writePackageRestrictionsLPr( 18372 mSettings.mPreferredActivities.keyAt(i)); 18373 } 18374 } 18375 18376 for (int userId : UserManagerService.getInstance().getUserIds()) { 18377 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18378 grantPermissionsUserIds = ArrayUtils.appendInt( 18379 grantPermissionsUserIds, userId); 18380 } 18381 } 18382 } 18383 sUserManager.systemReady(); 18384 18385 // If we upgraded grant all default permissions before kicking off. 18386 for (int userId : grantPermissionsUserIds) { 18387 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18388 } 18389 18390 // If we did not grant default permissions, we preload from this the 18391 // default permission exceptions lazily to ensure we don't hit the 18392 // disk on a new user creation. 18393 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18394 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18395 } 18396 18397 // Kick off any messages waiting for system ready 18398 if (mPostSystemReadyMessages != null) { 18399 for (Message msg : mPostSystemReadyMessages) { 18400 msg.sendToTarget(); 18401 } 18402 mPostSystemReadyMessages = null; 18403 } 18404 18405 // Watch for external volumes that come and go over time 18406 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18407 storage.registerListener(mStorageListener); 18408 18409 mInstallerService.systemReady(); 18410 mPackageDexOptimizer.systemReady(); 18411 18412 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 18413 StorageManagerInternal.class); 18414 StorageManagerInternal.addExternalStoragePolicy( 18415 new StorageManagerInternal.ExternalStorageMountPolicy() { 18416 @Override 18417 public int getMountMode(int uid, String packageName) { 18418 if (Process.isIsolated(uid)) { 18419 return Zygote.MOUNT_EXTERNAL_NONE; 18420 } 18421 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18422 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18423 } 18424 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18425 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18426 } 18427 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18428 return Zygote.MOUNT_EXTERNAL_READ; 18429 } 18430 return Zygote.MOUNT_EXTERNAL_WRITE; 18431 } 18432 18433 @Override 18434 public boolean hasExternalStorage(int uid, String packageName) { 18435 return true; 18436 } 18437 }); 18438 18439 // Now that we're mostly running, clean up stale users and apps 18440 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18441 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18442 } 18443 18444 @Override 18445 public boolean isSafeMode() { 18446 return mSafeMode; 18447 } 18448 18449 @Override 18450 public boolean hasSystemUidErrors() { 18451 return mHasSystemUidErrors; 18452 } 18453 18454 static String arrayToString(int[] array) { 18455 StringBuffer buf = new StringBuffer(128); 18456 buf.append('['); 18457 if (array != null) { 18458 for (int i=0; i<array.length; i++) { 18459 if (i > 0) buf.append(", "); 18460 buf.append(array[i]); 18461 } 18462 } 18463 buf.append(']'); 18464 return buf.toString(); 18465 } 18466 18467 static class DumpState { 18468 public static final int DUMP_LIBS = 1 << 0; 18469 public static final int DUMP_FEATURES = 1 << 1; 18470 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18471 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18472 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18473 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18474 public static final int DUMP_PERMISSIONS = 1 << 6; 18475 public static final int DUMP_PACKAGES = 1 << 7; 18476 public static final int DUMP_SHARED_USERS = 1 << 8; 18477 public static final int DUMP_MESSAGES = 1 << 9; 18478 public static final int DUMP_PROVIDERS = 1 << 10; 18479 public static final int DUMP_VERIFIERS = 1 << 11; 18480 public static final int DUMP_PREFERRED = 1 << 12; 18481 public static final int DUMP_PREFERRED_XML = 1 << 13; 18482 public static final int DUMP_KEYSETS = 1 << 14; 18483 public static final int DUMP_VERSION = 1 << 15; 18484 public static final int DUMP_INSTALLS = 1 << 16; 18485 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18486 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18487 public static final int DUMP_FROZEN = 1 << 19; 18488 public static final int DUMP_DEXOPT = 1 << 20; 18489 public static final int DUMP_COMPILER_STATS = 1 << 21; 18490 18491 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18492 18493 private int mTypes; 18494 18495 private int mOptions; 18496 18497 private boolean mTitlePrinted; 18498 18499 private SharedUserSetting mSharedUser; 18500 18501 public boolean isDumping(int type) { 18502 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18503 return true; 18504 } 18505 18506 return (mTypes & type) != 0; 18507 } 18508 18509 public void setDump(int type) { 18510 mTypes |= type; 18511 } 18512 18513 public boolean isOptionEnabled(int option) { 18514 return (mOptions & option) != 0; 18515 } 18516 18517 public void setOptionEnabled(int option) { 18518 mOptions |= option; 18519 } 18520 18521 public boolean onTitlePrinted() { 18522 final boolean printed = mTitlePrinted; 18523 mTitlePrinted = true; 18524 return printed; 18525 } 18526 18527 public boolean getTitlePrinted() { 18528 return mTitlePrinted; 18529 } 18530 18531 public void setTitlePrinted(boolean enabled) { 18532 mTitlePrinted = enabled; 18533 } 18534 18535 public SharedUserSetting getSharedUser() { 18536 return mSharedUser; 18537 } 18538 18539 public void setSharedUser(SharedUserSetting user) { 18540 mSharedUser = user; 18541 } 18542 } 18543 18544 @Override 18545 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18546 FileDescriptor err, String[] args, ShellCallback callback, 18547 ResultReceiver resultReceiver) { 18548 (new PackageManagerShellCommand(this)).exec( 18549 this, in, out, err, args, callback, resultReceiver); 18550 } 18551 18552 @Override 18553 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18554 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18555 != PackageManager.PERMISSION_GRANTED) { 18556 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18557 + Binder.getCallingPid() 18558 + ", uid=" + Binder.getCallingUid() 18559 + " without permission " 18560 + android.Manifest.permission.DUMP); 18561 return; 18562 } 18563 18564 DumpState dumpState = new DumpState(); 18565 boolean fullPreferred = false; 18566 boolean checkin = false; 18567 18568 String packageName = null; 18569 ArraySet<String> permissionNames = null; 18570 18571 int opti = 0; 18572 while (opti < args.length) { 18573 String opt = args[opti]; 18574 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18575 break; 18576 } 18577 opti++; 18578 18579 if ("-a".equals(opt)) { 18580 // Right now we only know how to print all. 18581 } else if ("-h".equals(opt)) { 18582 pw.println("Package manager dump options:"); 18583 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18584 pw.println(" --checkin: dump for a checkin"); 18585 pw.println(" -f: print details of intent filters"); 18586 pw.println(" -h: print this help"); 18587 pw.println(" cmd may be one of:"); 18588 pw.println(" l[ibraries]: list known shared libraries"); 18589 pw.println(" f[eatures]: list device features"); 18590 pw.println(" k[eysets]: print known keysets"); 18591 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18592 pw.println(" perm[issions]: dump permissions"); 18593 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18594 pw.println(" pref[erred]: print preferred package settings"); 18595 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18596 pw.println(" prov[iders]: dump content providers"); 18597 pw.println(" p[ackages]: dump installed packages"); 18598 pw.println(" s[hared-users]: dump shared user IDs"); 18599 pw.println(" m[essages]: print collected runtime messages"); 18600 pw.println(" v[erifiers]: print package verifier info"); 18601 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18602 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18603 pw.println(" version: print database version info"); 18604 pw.println(" write: write current settings now"); 18605 pw.println(" installs: details about install sessions"); 18606 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18607 pw.println(" dexopt: dump dexopt state"); 18608 pw.println(" compiler-stats: dump compiler statistics"); 18609 pw.println(" <package.name>: info about given package"); 18610 return; 18611 } else if ("--checkin".equals(opt)) { 18612 checkin = true; 18613 } else if ("-f".equals(opt)) { 18614 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18615 } else { 18616 pw.println("Unknown argument: " + opt + "; use -h for help"); 18617 } 18618 } 18619 18620 // Is the caller requesting to dump a particular piece of data? 18621 if (opti < args.length) { 18622 String cmd = args[opti]; 18623 opti++; 18624 // Is this a package name? 18625 if ("android".equals(cmd) || cmd.contains(".")) { 18626 packageName = cmd; 18627 // When dumping a single package, we always dump all of its 18628 // filter information since the amount of data will be reasonable. 18629 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18630 } else if ("check-permission".equals(cmd)) { 18631 if (opti >= args.length) { 18632 pw.println("Error: check-permission missing permission argument"); 18633 return; 18634 } 18635 String perm = args[opti]; 18636 opti++; 18637 if (opti >= args.length) { 18638 pw.println("Error: check-permission missing package argument"); 18639 return; 18640 } 18641 String pkg = args[opti]; 18642 opti++; 18643 int user = UserHandle.getUserId(Binder.getCallingUid()); 18644 if (opti < args.length) { 18645 try { 18646 user = Integer.parseInt(args[opti]); 18647 } catch (NumberFormatException e) { 18648 pw.println("Error: check-permission user argument is not a number: " 18649 + args[opti]); 18650 return; 18651 } 18652 } 18653 pw.println(checkPermission(perm, pkg, user)); 18654 return; 18655 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18656 dumpState.setDump(DumpState.DUMP_LIBS); 18657 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18658 dumpState.setDump(DumpState.DUMP_FEATURES); 18659 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18660 if (opti >= args.length) { 18661 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18662 | DumpState.DUMP_SERVICE_RESOLVERS 18663 | DumpState.DUMP_RECEIVER_RESOLVERS 18664 | DumpState.DUMP_CONTENT_RESOLVERS); 18665 } else { 18666 while (opti < args.length) { 18667 String name = args[opti]; 18668 if ("a".equals(name) || "activity".equals(name)) { 18669 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18670 } else if ("s".equals(name) || "service".equals(name)) { 18671 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18672 } else if ("r".equals(name) || "receiver".equals(name)) { 18673 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18674 } else if ("c".equals(name) || "content".equals(name)) { 18675 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18676 } else { 18677 pw.println("Error: unknown resolver table type: " + name); 18678 return; 18679 } 18680 opti++; 18681 } 18682 } 18683 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18684 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18685 } else if ("permission".equals(cmd)) { 18686 if (opti >= args.length) { 18687 pw.println("Error: permission requires permission name"); 18688 return; 18689 } 18690 permissionNames = new ArraySet<>(); 18691 while (opti < args.length) { 18692 permissionNames.add(args[opti]); 18693 opti++; 18694 } 18695 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18696 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18697 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18698 dumpState.setDump(DumpState.DUMP_PREFERRED); 18699 } else if ("preferred-xml".equals(cmd)) { 18700 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18701 if (opti < args.length && "--full".equals(args[opti])) { 18702 fullPreferred = true; 18703 opti++; 18704 } 18705 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18706 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18707 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18708 dumpState.setDump(DumpState.DUMP_PACKAGES); 18709 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18710 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18711 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18712 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18713 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18714 dumpState.setDump(DumpState.DUMP_MESSAGES); 18715 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18716 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18717 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18718 || "intent-filter-verifiers".equals(cmd)) { 18719 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18720 } else if ("version".equals(cmd)) { 18721 dumpState.setDump(DumpState.DUMP_VERSION); 18722 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18723 dumpState.setDump(DumpState.DUMP_KEYSETS); 18724 } else if ("installs".equals(cmd)) { 18725 dumpState.setDump(DumpState.DUMP_INSTALLS); 18726 } else if ("frozen".equals(cmd)) { 18727 dumpState.setDump(DumpState.DUMP_FROZEN); 18728 } else if ("dexopt".equals(cmd)) { 18729 dumpState.setDump(DumpState.DUMP_DEXOPT); 18730 } else if ("compiler-stats".equals(cmd)) { 18731 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18732 } else if ("write".equals(cmd)) { 18733 synchronized (mPackages) { 18734 mSettings.writeLPr(); 18735 pw.println("Settings written."); 18736 return; 18737 } 18738 } 18739 } 18740 18741 if (checkin) { 18742 pw.println("vers,1"); 18743 } 18744 18745 // reader 18746 synchronized (mPackages) { 18747 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18748 if (!checkin) { 18749 if (dumpState.onTitlePrinted()) 18750 pw.println(); 18751 pw.println("Database versions:"); 18752 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18753 } 18754 } 18755 18756 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18757 if (!checkin) { 18758 if (dumpState.onTitlePrinted()) 18759 pw.println(); 18760 pw.println("Verifiers:"); 18761 pw.print(" Required: "); 18762 pw.print(mRequiredVerifierPackage); 18763 pw.print(" (uid="); 18764 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18765 UserHandle.USER_SYSTEM)); 18766 pw.println(")"); 18767 } else if (mRequiredVerifierPackage != null) { 18768 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18769 pw.print(","); 18770 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18771 UserHandle.USER_SYSTEM)); 18772 } 18773 } 18774 18775 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18776 packageName == null) { 18777 if (mIntentFilterVerifierComponent != null) { 18778 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18779 if (!checkin) { 18780 if (dumpState.onTitlePrinted()) 18781 pw.println(); 18782 pw.println("Intent Filter Verifier:"); 18783 pw.print(" Using: "); 18784 pw.print(verifierPackageName); 18785 pw.print(" (uid="); 18786 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18787 UserHandle.USER_SYSTEM)); 18788 pw.println(")"); 18789 } else if (verifierPackageName != null) { 18790 pw.print("ifv,"); pw.print(verifierPackageName); 18791 pw.print(","); 18792 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18793 UserHandle.USER_SYSTEM)); 18794 } 18795 } else { 18796 pw.println(); 18797 pw.println("No Intent Filter Verifier available!"); 18798 } 18799 } 18800 18801 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18802 boolean printedHeader = false; 18803 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18804 while (it.hasNext()) { 18805 String name = it.next(); 18806 SharedLibraryEntry ent = mSharedLibraries.get(name); 18807 if (!checkin) { 18808 if (!printedHeader) { 18809 if (dumpState.onTitlePrinted()) 18810 pw.println(); 18811 pw.println("Libraries:"); 18812 printedHeader = true; 18813 } 18814 pw.print(" "); 18815 } else { 18816 pw.print("lib,"); 18817 } 18818 pw.print(name); 18819 if (!checkin) { 18820 pw.print(" -> "); 18821 } 18822 if (ent.path != null) { 18823 if (!checkin) { 18824 pw.print("(jar) "); 18825 pw.print(ent.path); 18826 } else { 18827 pw.print(",jar,"); 18828 pw.print(ent.path); 18829 } 18830 } else { 18831 if (!checkin) { 18832 pw.print("(apk) "); 18833 pw.print(ent.apk); 18834 } else { 18835 pw.print(",apk,"); 18836 pw.print(ent.apk); 18837 } 18838 } 18839 pw.println(); 18840 } 18841 } 18842 18843 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18844 if (dumpState.onTitlePrinted()) 18845 pw.println(); 18846 if (!checkin) { 18847 pw.println("Features:"); 18848 } 18849 18850 for (FeatureInfo feat : mAvailableFeatures.values()) { 18851 if (checkin) { 18852 pw.print("feat,"); 18853 pw.print(feat.name); 18854 pw.print(","); 18855 pw.println(feat.version); 18856 } else { 18857 pw.print(" "); 18858 pw.print(feat.name); 18859 if (feat.version > 0) { 18860 pw.print(" version="); 18861 pw.print(feat.version); 18862 } 18863 pw.println(); 18864 } 18865 } 18866 } 18867 18868 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18869 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18870 : "Activity Resolver Table:", " ", packageName, 18871 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18872 dumpState.setTitlePrinted(true); 18873 } 18874 } 18875 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18876 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18877 : "Receiver Resolver Table:", " ", packageName, 18878 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18879 dumpState.setTitlePrinted(true); 18880 } 18881 } 18882 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18883 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18884 : "Service Resolver Table:", " ", packageName, 18885 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18886 dumpState.setTitlePrinted(true); 18887 } 18888 } 18889 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18890 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18891 : "Provider Resolver Table:", " ", packageName, 18892 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18893 dumpState.setTitlePrinted(true); 18894 } 18895 } 18896 18897 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18898 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18899 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18900 int user = mSettings.mPreferredActivities.keyAt(i); 18901 if (pir.dump(pw, 18902 dumpState.getTitlePrinted() 18903 ? "\nPreferred Activities User " + user + ":" 18904 : "Preferred Activities User " + user + ":", " ", 18905 packageName, true, false)) { 18906 dumpState.setTitlePrinted(true); 18907 } 18908 } 18909 } 18910 18911 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18912 pw.flush(); 18913 FileOutputStream fout = new FileOutputStream(fd); 18914 BufferedOutputStream str = new BufferedOutputStream(fout); 18915 XmlSerializer serializer = new FastXmlSerializer(); 18916 try { 18917 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18918 serializer.startDocument(null, true); 18919 serializer.setFeature( 18920 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18921 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18922 serializer.endDocument(); 18923 serializer.flush(); 18924 } catch (IllegalArgumentException e) { 18925 pw.println("Failed writing: " + e); 18926 } catch (IllegalStateException e) { 18927 pw.println("Failed writing: " + e); 18928 } catch (IOException e) { 18929 pw.println("Failed writing: " + e); 18930 } 18931 } 18932 18933 if (!checkin 18934 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18935 && packageName == null) { 18936 pw.println(); 18937 int count = mSettings.mPackages.size(); 18938 if (count == 0) { 18939 pw.println("No applications!"); 18940 pw.println(); 18941 } else { 18942 final String prefix = " "; 18943 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18944 if (allPackageSettings.size() == 0) { 18945 pw.println("No domain preferred apps!"); 18946 pw.println(); 18947 } else { 18948 pw.println("App verification status:"); 18949 pw.println(); 18950 count = 0; 18951 for (PackageSetting ps : allPackageSettings) { 18952 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18953 if (ivi == null || ivi.getPackageName() == null) continue; 18954 pw.println(prefix + "Package: " + ivi.getPackageName()); 18955 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18956 pw.println(prefix + "Status: " + ivi.getStatusString()); 18957 pw.println(); 18958 count++; 18959 } 18960 if (count == 0) { 18961 pw.println(prefix + "No app verification established."); 18962 pw.println(); 18963 } 18964 for (int userId : sUserManager.getUserIds()) { 18965 pw.println("App linkages for user " + userId + ":"); 18966 pw.println(); 18967 count = 0; 18968 for (PackageSetting ps : allPackageSettings) { 18969 final long status = ps.getDomainVerificationStatusForUser(userId); 18970 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18971 continue; 18972 } 18973 pw.println(prefix + "Package: " + ps.name); 18974 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18975 String statusStr = IntentFilterVerificationInfo. 18976 getStatusStringFromValue(status); 18977 pw.println(prefix + "Status: " + statusStr); 18978 pw.println(); 18979 count++; 18980 } 18981 if (count == 0) { 18982 pw.println(prefix + "No configured app linkages."); 18983 pw.println(); 18984 } 18985 } 18986 } 18987 } 18988 } 18989 18990 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18991 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18992 if (packageName == null && permissionNames == null) { 18993 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18994 if (iperm == 0) { 18995 if (dumpState.onTitlePrinted()) 18996 pw.println(); 18997 pw.println("AppOp Permissions:"); 18998 } 18999 pw.print(" AppOp Permission "); 19000 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 19001 pw.println(":"); 19002 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 19003 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 19004 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 19005 } 19006 } 19007 } 19008 } 19009 19010 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 19011 boolean printedSomething = false; 19012 for (PackageParser.Provider p : mProviders.mProviders.values()) { 19013 if (packageName != null && !packageName.equals(p.info.packageName)) { 19014 continue; 19015 } 19016 if (!printedSomething) { 19017 if (dumpState.onTitlePrinted()) 19018 pw.println(); 19019 pw.println("Registered ContentProviders:"); 19020 printedSomething = true; 19021 } 19022 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 19023 pw.print(" "); pw.println(p.toString()); 19024 } 19025 printedSomething = false; 19026 for (Map.Entry<String, PackageParser.Provider> entry : 19027 mProvidersByAuthority.entrySet()) { 19028 PackageParser.Provider p = entry.getValue(); 19029 if (packageName != null && !packageName.equals(p.info.packageName)) { 19030 continue; 19031 } 19032 if (!printedSomething) { 19033 if (dumpState.onTitlePrinted()) 19034 pw.println(); 19035 pw.println("ContentProvider Authorities:"); 19036 printedSomething = true; 19037 } 19038 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 19039 pw.print(" "); pw.println(p.toString()); 19040 if (p.info != null && p.info.applicationInfo != null) { 19041 final String appInfo = p.info.applicationInfo.toString(); 19042 pw.print(" applicationInfo="); pw.println(appInfo); 19043 } 19044 } 19045 } 19046 19047 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 19048 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 19049 } 19050 19051 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 19052 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 19053 } 19054 19055 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 19056 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 19057 } 19058 19059 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 19060 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 19061 } 19062 19063 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 19064 // XXX should handle packageName != null by dumping only install data that 19065 // the given package is involved with. 19066 if (dumpState.onTitlePrinted()) pw.println(); 19067 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 19068 } 19069 19070 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 19071 // XXX should handle packageName != null by dumping only install data that 19072 // the given package is involved with. 19073 if (dumpState.onTitlePrinted()) pw.println(); 19074 19075 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19076 ipw.println(); 19077 ipw.println("Frozen packages:"); 19078 ipw.increaseIndent(); 19079 if (mFrozenPackages.size() == 0) { 19080 ipw.println("(none)"); 19081 } else { 19082 for (int i = 0; i < mFrozenPackages.size(); i++) { 19083 ipw.println(mFrozenPackages.valueAt(i)); 19084 } 19085 } 19086 ipw.decreaseIndent(); 19087 } 19088 19089 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 19090 if (dumpState.onTitlePrinted()) pw.println(); 19091 dumpDexoptStateLPr(pw, packageName); 19092 } 19093 19094 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 19095 if (dumpState.onTitlePrinted()) pw.println(); 19096 dumpCompilerStatsLPr(pw, packageName); 19097 } 19098 19099 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 19100 if (dumpState.onTitlePrinted()) pw.println(); 19101 mSettings.dumpReadMessagesLPr(pw, dumpState); 19102 19103 pw.println(); 19104 pw.println("Package warning messages:"); 19105 BufferedReader in = null; 19106 String line = null; 19107 try { 19108 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19109 while ((line = in.readLine()) != null) { 19110 if (line.contains("ignored: updated version")) continue; 19111 pw.println(line); 19112 } 19113 } catch (IOException ignored) { 19114 } finally { 19115 IoUtils.closeQuietly(in); 19116 } 19117 } 19118 19119 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 19120 BufferedReader in = null; 19121 String line = null; 19122 try { 19123 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19124 while ((line = in.readLine()) != null) { 19125 if (line.contains("ignored: updated version")) continue; 19126 pw.print("msg,"); 19127 pw.println(line); 19128 } 19129 } catch (IOException ignored) { 19130 } finally { 19131 IoUtils.closeQuietly(in); 19132 } 19133 } 19134 } 19135 } 19136 19137 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 19138 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19139 ipw.println(); 19140 ipw.println("Dexopt state:"); 19141 ipw.increaseIndent(); 19142 Collection<PackageParser.Package> packages = null; 19143 if (packageName != null) { 19144 PackageParser.Package targetPackage = mPackages.get(packageName); 19145 if (targetPackage != null) { 19146 packages = Collections.singletonList(targetPackage); 19147 } else { 19148 ipw.println("Unable to find package: " + packageName); 19149 return; 19150 } 19151 } else { 19152 packages = mPackages.values(); 19153 } 19154 19155 for (PackageParser.Package pkg : packages) { 19156 ipw.println("[" + pkg.packageName + "]"); 19157 ipw.increaseIndent(); 19158 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 19159 ipw.decreaseIndent(); 19160 } 19161 } 19162 19163 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 19164 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19165 ipw.println(); 19166 ipw.println("Compiler stats:"); 19167 ipw.increaseIndent(); 19168 Collection<PackageParser.Package> packages = null; 19169 if (packageName != null) { 19170 PackageParser.Package targetPackage = mPackages.get(packageName); 19171 if (targetPackage != null) { 19172 packages = Collections.singletonList(targetPackage); 19173 } else { 19174 ipw.println("Unable to find package: " + packageName); 19175 return; 19176 } 19177 } else { 19178 packages = mPackages.values(); 19179 } 19180 19181 for (PackageParser.Package pkg : packages) { 19182 ipw.println("[" + pkg.packageName + "]"); 19183 ipw.increaseIndent(); 19184 19185 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 19186 if (stats == null) { 19187 ipw.println("(No recorded stats)"); 19188 } else { 19189 stats.dump(ipw); 19190 } 19191 ipw.decreaseIndent(); 19192 } 19193 } 19194 19195 private String dumpDomainString(String packageName) { 19196 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 19197 .getList(); 19198 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 19199 19200 ArraySet<String> result = new ArraySet<>(); 19201 if (iviList.size() > 0) { 19202 for (IntentFilterVerificationInfo ivi : iviList) { 19203 for (String host : ivi.getDomains()) { 19204 result.add(host); 19205 } 19206 } 19207 } 19208 if (filters != null && filters.size() > 0) { 19209 for (IntentFilter filter : filters) { 19210 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 19211 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19212 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19213 result.addAll(filter.getHostsList()); 19214 } 19215 } 19216 } 19217 19218 StringBuilder sb = new StringBuilder(result.size() * 16); 19219 for (String domain : result) { 19220 if (sb.length() > 0) sb.append(" "); 19221 sb.append(domain); 19222 } 19223 return sb.toString(); 19224 } 19225 19226 // ------- apps on sdcard specific code ------- 19227 static final boolean DEBUG_SD_INSTALL = false; 19228 19229 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19230 19231 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19232 19233 private boolean mMediaMounted = false; 19234 19235 static String getEncryptKey() { 19236 try { 19237 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19238 SD_ENCRYPTION_KEYSTORE_NAME); 19239 if (sdEncKey == null) { 19240 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19241 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19242 if (sdEncKey == null) { 19243 Slog.e(TAG, "Failed to create encryption keys"); 19244 return null; 19245 } 19246 } 19247 return sdEncKey; 19248 } catch (NoSuchAlgorithmException nsae) { 19249 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19250 return null; 19251 } catch (IOException ioe) { 19252 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19253 return null; 19254 } 19255 } 19256 19257 /* 19258 * Update media status on PackageManager. 19259 */ 19260 @Override 19261 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19262 int callingUid = Binder.getCallingUid(); 19263 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19264 throw new SecurityException("Media status can only be updated by the system"); 19265 } 19266 // reader; this apparently protects mMediaMounted, but should probably 19267 // be a different lock in that case. 19268 synchronized (mPackages) { 19269 Log.i(TAG, "Updating external media status from " 19270 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19271 + (mediaStatus ? "mounted" : "unmounted")); 19272 if (DEBUG_SD_INSTALL) 19273 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19274 + ", mMediaMounted=" + mMediaMounted); 19275 if (mediaStatus == mMediaMounted) { 19276 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19277 : 0, -1); 19278 mHandler.sendMessage(msg); 19279 return; 19280 } 19281 mMediaMounted = mediaStatus; 19282 } 19283 // Queue up an async operation since the package installation may take a 19284 // little while. 19285 mHandler.post(new Runnable() { 19286 public void run() { 19287 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19288 } 19289 }); 19290 } 19291 19292 /** 19293 * Called by StorageManagerService when the initial ASECs to scan are available. 19294 * Should block until all the ASEC containers are finished being scanned. 19295 */ 19296 public void scanAvailableAsecs() { 19297 updateExternalMediaStatusInner(true, false, false); 19298 } 19299 19300 /* 19301 * Collect information of applications on external media, map them against 19302 * existing containers and update information based on current mount status. 19303 * Please note that we always have to report status if reportStatus has been 19304 * set to true especially when unloading packages. 19305 */ 19306 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19307 boolean externalStorage) { 19308 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19309 int[] uidArr = EmptyArray.INT; 19310 19311 final String[] list = PackageHelper.getSecureContainerList(); 19312 if (ArrayUtils.isEmpty(list)) { 19313 Log.i(TAG, "No secure containers found"); 19314 } else { 19315 // Process list of secure containers and categorize them 19316 // as active or stale based on their package internal state. 19317 19318 // reader 19319 synchronized (mPackages) { 19320 for (String cid : list) { 19321 // Leave stages untouched for now; installer service owns them 19322 if (PackageInstallerService.isStageName(cid)) continue; 19323 19324 if (DEBUG_SD_INSTALL) 19325 Log.i(TAG, "Processing container " + cid); 19326 String pkgName = getAsecPackageName(cid); 19327 if (pkgName == null) { 19328 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19329 continue; 19330 } 19331 if (DEBUG_SD_INSTALL) 19332 Log.i(TAG, "Looking for pkg : " + pkgName); 19333 19334 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19335 if (ps == null) { 19336 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19337 continue; 19338 } 19339 19340 /* 19341 * Skip packages that are not external if we're unmounting 19342 * external storage. 19343 */ 19344 if (externalStorage && !isMounted && !isExternal(ps)) { 19345 continue; 19346 } 19347 19348 final AsecInstallArgs args = new AsecInstallArgs(cid, 19349 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19350 // The package status is changed only if the code path 19351 // matches between settings and the container id. 19352 if (ps.codePathString != null 19353 && ps.codePathString.startsWith(args.getCodePath())) { 19354 if (DEBUG_SD_INSTALL) { 19355 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19356 + " at code path: " + ps.codePathString); 19357 } 19358 19359 // We do have a valid package installed on sdcard 19360 processCids.put(args, ps.codePathString); 19361 final int uid = ps.appId; 19362 if (uid != -1) { 19363 uidArr = ArrayUtils.appendInt(uidArr, uid); 19364 } 19365 } else { 19366 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19367 + ps.codePathString); 19368 } 19369 } 19370 } 19371 19372 Arrays.sort(uidArr); 19373 } 19374 19375 // Process packages with valid entries. 19376 if (isMounted) { 19377 if (DEBUG_SD_INSTALL) 19378 Log.i(TAG, "Loading packages"); 19379 loadMediaPackages(processCids, uidArr, externalStorage); 19380 startCleaningPackages(); 19381 mInstallerService.onSecureContainersAvailable(); 19382 } else { 19383 if (DEBUG_SD_INSTALL) 19384 Log.i(TAG, "Unloading packages"); 19385 unloadMediaPackages(processCids, uidArr, reportStatus); 19386 } 19387 } 19388 19389 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19390 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19391 final int size = infos.size(); 19392 final String[] packageNames = new String[size]; 19393 final int[] packageUids = new int[size]; 19394 for (int i = 0; i < size; i++) { 19395 final ApplicationInfo info = infos.get(i); 19396 packageNames[i] = info.packageName; 19397 packageUids[i] = info.uid; 19398 } 19399 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19400 finishedReceiver); 19401 } 19402 19403 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19404 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19405 sendResourcesChangedBroadcast(mediaStatus, replacing, 19406 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19407 } 19408 19409 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19410 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19411 int size = pkgList.length; 19412 if (size > 0) { 19413 // Send broadcasts here 19414 Bundle extras = new Bundle(); 19415 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19416 if (uidArr != null) { 19417 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19418 } 19419 if (replacing) { 19420 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19421 } 19422 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19423 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19424 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19425 } 19426 } 19427 19428 /* 19429 * Look at potentially valid container ids from processCids If package 19430 * information doesn't match the one on record or package scanning fails, 19431 * the cid is added to list of removeCids. We currently don't delete stale 19432 * containers. 19433 */ 19434 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19435 boolean externalStorage) { 19436 ArrayList<String> pkgList = new ArrayList<String>(); 19437 Set<AsecInstallArgs> keys = processCids.keySet(); 19438 19439 for (AsecInstallArgs args : keys) { 19440 String codePath = processCids.get(args); 19441 if (DEBUG_SD_INSTALL) 19442 Log.i(TAG, "Loading container : " + args.cid); 19443 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19444 try { 19445 // Make sure there are no container errors first. 19446 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19447 Slog.e(TAG, "Failed to mount cid : " + args.cid 19448 + " when installing from sdcard"); 19449 continue; 19450 } 19451 // Check code path here. 19452 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19453 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19454 + " does not match one in settings " + codePath); 19455 continue; 19456 } 19457 // Parse package 19458 int parseFlags = mDefParseFlags; 19459 if (args.isExternalAsec()) { 19460 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19461 } 19462 if (args.isFwdLocked()) { 19463 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19464 } 19465 19466 synchronized (mInstallLock) { 19467 PackageParser.Package pkg = null; 19468 try { 19469 // Sadly we don't know the package name yet to freeze it 19470 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19471 SCAN_IGNORE_FROZEN, 0, null); 19472 } catch (PackageManagerException e) { 19473 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19474 } 19475 // Scan the package 19476 if (pkg != null) { 19477 /* 19478 * TODO why is the lock being held? doPostInstall is 19479 * called in other places without the lock. This needs 19480 * to be straightened out. 19481 */ 19482 // writer 19483 synchronized (mPackages) { 19484 retCode = PackageManager.INSTALL_SUCCEEDED; 19485 pkgList.add(pkg.packageName); 19486 // Post process args 19487 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19488 pkg.applicationInfo.uid); 19489 } 19490 } else { 19491 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19492 } 19493 } 19494 19495 } finally { 19496 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19497 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19498 } 19499 } 19500 } 19501 // writer 19502 synchronized (mPackages) { 19503 // If the platform SDK has changed since the last time we booted, 19504 // we need to re-grant app permission to catch any new ones that 19505 // appear. This is really a hack, and means that apps can in some 19506 // cases get permissions that the user didn't initially explicitly 19507 // allow... it would be nice to have some better way to handle 19508 // this situation. 19509 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19510 : mSettings.getInternalVersion(); 19511 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19512 : StorageManager.UUID_PRIVATE_INTERNAL; 19513 19514 int updateFlags = UPDATE_PERMISSIONS_ALL; 19515 if (ver.sdkVersion != mSdkVersion) { 19516 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19517 + mSdkVersion + "; regranting permissions for external"); 19518 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19519 } 19520 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19521 19522 // Yay, everything is now upgraded 19523 ver.forceCurrent(); 19524 19525 // can downgrade to reader 19526 // Persist settings 19527 mSettings.writeLPr(); 19528 } 19529 // Send a broadcast to let everyone know we are done processing 19530 if (pkgList.size() > 0) { 19531 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19532 } 19533 } 19534 19535 /* 19536 * Utility method to unload a list of specified containers 19537 */ 19538 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19539 // Just unmount all valid containers. 19540 for (AsecInstallArgs arg : cidArgs) { 19541 synchronized (mInstallLock) { 19542 arg.doPostDeleteLI(false); 19543 } 19544 } 19545 } 19546 19547 /* 19548 * Unload packages mounted on external media. This involves deleting package 19549 * data from internal structures, sending broadcasts about disabled packages, 19550 * gc'ing to free up references, unmounting all secure containers 19551 * corresponding to packages on external media, and posting a 19552 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19553 * that we always have to post this message if status has been requested no 19554 * matter what. 19555 */ 19556 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19557 final boolean reportStatus) { 19558 if (DEBUG_SD_INSTALL) 19559 Log.i(TAG, "unloading media packages"); 19560 ArrayList<String> pkgList = new ArrayList<String>(); 19561 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19562 final Set<AsecInstallArgs> keys = processCids.keySet(); 19563 for (AsecInstallArgs args : keys) { 19564 String pkgName = args.getPackageName(); 19565 if (DEBUG_SD_INSTALL) 19566 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19567 // Delete package internally 19568 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19569 synchronized (mInstallLock) { 19570 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19571 final boolean res; 19572 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19573 "unloadMediaPackages")) { 19574 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19575 null); 19576 } 19577 if (res) { 19578 pkgList.add(pkgName); 19579 } else { 19580 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19581 failedList.add(args); 19582 } 19583 } 19584 } 19585 19586 // reader 19587 synchronized (mPackages) { 19588 // We didn't update the settings after removing each package; 19589 // write them now for all packages. 19590 mSettings.writeLPr(); 19591 } 19592 19593 // We have to absolutely send UPDATED_MEDIA_STATUS only 19594 // after confirming that all the receivers processed the ordered 19595 // broadcast when packages get disabled, force a gc to clean things up. 19596 // and unload all the containers. 19597 if (pkgList.size() > 0) { 19598 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19599 new IIntentReceiver.Stub() { 19600 public void performReceive(Intent intent, int resultCode, String data, 19601 Bundle extras, boolean ordered, boolean sticky, 19602 int sendingUser) throws RemoteException { 19603 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19604 reportStatus ? 1 : 0, 1, keys); 19605 mHandler.sendMessage(msg); 19606 } 19607 }); 19608 } else { 19609 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19610 keys); 19611 mHandler.sendMessage(msg); 19612 } 19613 } 19614 19615 private void loadPrivatePackages(final VolumeInfo vol) { 19616 mHandler.post(new Runnable() { 19617 @Override 19618 public void run() { 19619 loadPrivatePackagesInner(vol); 19620 } 19621 }); 19622 } 19623 19624 private void loadPrivatePackagesInner(VolumeInfo vol) { 19625 final String volumeUuid = vol.fsUuid; 19626 if (TextUtils.isEmpty(volumeUuid)) { 19627 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19628 return; 19629 } 19630 19631 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19632 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19633 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19634 19635 final VersionInfo ver; 19636 final List<PackageSetting> packages; 19637 synchronized (mPackages) { 19638 ver = mSettings.findOrCreateVersion(volumeUuid); 19639 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19640 } 19641 19642 for (PackageSetting ps : packages) { 19643 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19644 synchronized (mInstallLock) { 19645 final PackageParser.Package pkg; 19646 try { 19647 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19648 loaded.add(pkg.applicationInfo); 19649 19650 } catch (PackageManagerException e) { 19651 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19652 } 19653 19654 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19655 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19656 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19657 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19658 } 19659 } 19660 } 19661 19662 // Reconcile app data for all started/unlocked users 19663 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19664 final UserManager um = mContext.getSystemService(UserManager.class); 19665 UserManagerInternal umInternal = getUserManagerInternal(); 19666 for (UserInfo user : um.getUsers()) { 19667 final int flags; 19668 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19669 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19670 } else if (umInternal.isUserRunning(user.id)) { 19671 flags = StorageManager.FLAG_STORAGE_DE; 19672 } else { 19673 continue; 19674 } 19675 19676 try { 19677 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19678 synchronized (mInstallLock) { 19679 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 19680 } 19681 } catch (IllegalStateException e) { 19682 // Device was probably ejected, and we'll process that event momentarily 19683 Slog.w(TAG, "Failed to prepare storage: " + e); 19684 } 19685 } 19686 19687 synchronized (mPackages) { 19688 int updateFlags = UPDATE_PERMISSIONS_ALL; 19689 if (ver.sdkVersion != mSdkVersion) { 19690 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19691 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19692 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19693 } 19694 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19695 19696 // Yay, everything is now upgraded 19697 ver.forceCurrent(); 19698 19699 mSettings.writeLPr(); 19700 } 19701 19702 for (PackageFreezer freezer : freezers) { 19703 freezer.close(); 19704 } 19705 19706 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19707 sendResourcesChangedBroadcast(true, false, loaded, null); 19708 } 19709 19710 private void unloadPrivatePackages(final VolumeInfo vol) { 19711 mHandler.post(new Runnable() { 19712 @Override 19713 public void run() { 19714 unloadPrivatePackagesInner(vol); 19715 } 19716 }); 19717 } 19718 19719 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19720 final String volumeUuid = vol.fsUuid; 19721 if (TextUtils.isEmpty(volumeUuid)) { 19722 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19723 return; 19724 } 19725 19726 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19727 synchronized (mInstallLock) { 19728 synchronized (mPackages) { 19729 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19730 for (PackageSetting ps : packages) { 19731 if (ps.pkg == null) continue; 19732 19733 final ApplicationInfo info = ps.pkg.applicationInfo; 19734 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19735 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19736 19737 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19738 "unloadPrivatePackagesInner")) { 19739 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19740 false, null)) { 19741 unloaded.add(info); 19742 } else { 19743 Slog.w(TAG, "Failed to unload " + ps.codePath); 19744 } 19745 } 19746 19747 // Try very hard to release any references to this package 19748 // so we don't risk the system server being killed due to 19749 // open FDs 19750 AttributeCache.instance().removePackage(ps.name); 19751 } 19752 19753 mSettings.writeLPr(); 19754 } 19755 } 19756 19757 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19758 sendResourcesChangedBroadcast(false, false, unloaded, null); 19759 19760 // Try very hard to release any references to this path so we don't risk 19761 // the system server being killed due to open FDs 19762 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19763 19764 for (int i = 0; i < 3; i++) { 19765 System.gc(); 19766 System.runFinalization(); 19767 } 19768 } 19769 19770 /** 19771 * Prepare storage areas for given user on all mounted devices. 19772 */ 19773 void prepareUserData(int userId, int userSerial, int flags) { 19774 synchronized (mInstallLock) { 19775 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19776 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19777 final String volumeUuid = vol.getFsUuid(); 19778 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19779 } 19780 } 19781 } 19782 19783 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19784 boolean allowRecover) { 19785 // Prepare storage and verify that serial numbers are consistent; if 19786 // there's a mismatch we need to destroy to avoid leaking data 19787 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19788 try { 19789 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19790 19791 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19792 UserManagerService.enforceSerialNumber( 19793 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19794 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19795 UserManagerService.enforceSerialNumber( 19796 Environment.getDataSystemDeDirectory(userId), userSerial); 19797 } 19798 } 19799 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19800 UserManagerService.enforceSerialNumber( 19801 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19802 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19803 UserManagerService.enforceSerialNumber( 19804 Environment.getDataSystemCeDirectory(userId), userSerial); 19805 } 19806 } 19807 19808 synchronized (mInstallLock) { 19809 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19810 } 19811 } catch (Exception e) { 19812 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19813 + " because we failed to prepare: " + e); 19814 destroyUserDataLI(volumeUuid, userId, 19815 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19816 19817 if (allowRecover) { 19818 // Try one last time; if we fail again we're really in trouble 19819 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19820 } 19821 } 19822 } 19823 19824 /** 19825 * Destroy storage areas for given user on all mounted devices. 19826 */ 19827 void destroyUserData(int userId, int flags) { 19828 synchronized (mInstallLock) { 19829 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19830 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19831 final String volumeUuid = vol.getFsUuid(); 19832 destroyUserDataLI(volumeUuid, userId, flags); 19833 } 19834 } 19835 } 19836 19837 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19838 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19839 try { 19840 // Clean up app data, profile data, and media data 19841 mInstaller.destroyUserData(volumeUuid, userId, flags); 19842 19843 // Clean up system data 19844 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19845 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19846 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19847 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19848 } 19849 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19850 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19851 } 19852 } 19853 19854 // Data with special labels is now gone, so finish the job 19855 storage.destroyUserStorage(volumeUuid, userId, flags); 19856 19857 } catch (Exception e) { 19858 logCriticalInfo(Log.WARN, 19859 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19860 } 19861 } 19862 19863 /** 19864 * Examine all users present on given mounted volume, and destroy data 19865 * belonging to users that are no longer valid, or whose user ID has been 19866 * recycled. 19867 */ 19868 private void reconcileUsers(String volumeUuid) { 19869 final List<File> files = new ArrayList<>(); 19870 Collections.addAll(files, FileUtils 19871 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19872 Collections.addAll(files, FileUtils 19873 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19874 Collections.addAll(files, FileUtils 19875 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19876 Collections.addAll(files, FileUtils 19877 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19878 for (File file : files) { 19879 if (!file.isDirectory()) continue; 19880 19881 final int userId; 19882 final UserInfo info; 19883 try { 19884 userId = Integer.parseInt(file.getName()); 19885 info = sUserManager.getUserInfo(userId); 19886 } catch (NumberFormatException e) { 19887 Slog.w(TAG, "Invalid user directory " + file); 19888 continue; 19889 } 19890 19891 boolean destroyUser = false; 19892 if (info == null) { 19893 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19894 + " because no matching user was found"); 19895 destroyUser = true; 19896 } else if (!mOnlyCore) { 19897 try { 19898 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19899 } catch (IOException e) { 19900 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19901 + " because we failed to enforce serial number: " + e); 19902 destroyUser = true; 19903 } 19904 } 19905 19906 if (destroyUser) { 19907 synchronized (mInstallLock) { 19908 destroyUserDataLI(volumeUuid, userId, 19909 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19910 } 19911 } 19912 } 19913 } 19914 19915 private void assertPackageKnown(String volumeUuid, String packageName) 19916 throws PackageManagerException { 19917 synchronized (mPackages) { 19918 final PackageSetting ps = mSettings.mPackages.get(packageName); 19919 if (ps == null) { 19920 throw new PackageManagerException("Package " + packageName + " is unknown"); 19921 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19922 throw new PackageManagerException( 19923 "Package " + packageName + " found on unknown volume " + volumeUuid 19924 + "; expected volume " + ps.volumeUuid); 19925 } 19926 } 19927 } 19928 19929 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19930 throws PackageManagerException { 19931 synchronized (mPackages) { 19932 final PackageSetting ps = mSettings.mPackages.get(packageName); 19933 if (ps == null) { 19934 throw new PackageManagerException("Package " + packageName + " is unknown"); 19935 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19936 throw new PackageManagerException( 19937 "Package " + packageName + " found on unknown volume " + volumeUuid 19938 + "; expected volume " + ps.volumeUuid); 19939 } else if (!ps.getInstalled(userId)) { 19940 throw new PackageManagerException( 19941 "Package " + packageName + " not installed for user " + userId); 19942 } 19943 } 19944 } 19945 19946 /** 19947 * Examine all apps present on given mounted volume, and destroy apps that 19948 * aren't expected, either due to uninstallation or reinstallation on 19949 * another volume. 19950 */ 19951 private void reconcileApps(String volumeUuid) { 19952 final File[] files = FileUtils 19953 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19954 for (File file : files) { 19955 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19956 && !PackageInstallerService.isStageName(file.getName()); 19957 if (!isPackage) { 19958 // Ignore entries which are not packages 19959 continue; 19960 } 19961 19962 try { 19963 final PackageLite pkg = PackageParser.parsePackageLite(file, 19964 PackageParser.PARSE_MUST_BE_APK); 19965 assertPackageKnown(volumeUuid, pkg.packageName); 19966 19967 } catch (PackageParserException | PackageManagerException e) { 19968 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19969 synchronized (mInstallLock) { 19970 removeCodePathLI(file); 19971 } 19972 } 19973 } 19974 } 19975 19976 /** 19977 * Reconcile all app data for the given user. 19978 * <p> 19979 * Verifies that directories exist and that ownership and labeling is 19980 * correct for all installed apps on all mounted volumes. 19981 */ 19982 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 19983 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19984 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19985 final String volumeUuid = vol.getFsUuid(); 19986 synchronized (mInstallLock) { 19987 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 19988 } 19989 } 19990 } 19991 19992 /** 19993 * Reconcile all app data on given mounted volume. 19994 * <p> 19995 * Destroys app data that isn't expected, either due to uninstallation or 19996 * reinstallation on another volume. 19997 * <p> 19998 * Verifies that directories exist and that ownership and labeling is 19999 * correct for all installed apps. 20000 */ 20001 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 20002 boolean migrateAppData) { 20003 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 20004 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 20005 20006 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 20007 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 20008 20009 // First look for stale data that doesn't belong, and check if things 20010 // have changed since we did our last restorecon 20011 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20012 if (StorageManager.isFileEncryptedNativeOrEmulated() 20013 && !StorageManager.isUserKeyUnlocked(userId)) { 20014 throw new RuntimeException( 20015 "Yikes, someone asked us to reconcile CE storage while " + userId 20016 + " was still locked; this would have caused massive data loss!"); 20017 } 20018 20019 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 20020 for (File file : files) { 20021 final String packageName = file.getName(); 20022 try { 20023 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20024 } catch (PackageManagerException e) { 20025 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20026 try { 20027 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20028 StorageManager.FLAG_STORAGE_CE, 0); 20029 } catch (InstallerException e2) { 20030 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20031 } 20032 } 20033 } 20034 } 20035 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20036 final File[] files = FileUtils.listFilesOrEmpty(deDir); 20037 for (File file : files) { 20038 final String packageName = file.getName(); 20039 try { 20040 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20041 } catch (PackageManagerException e) { 20042 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20043 try { 20044 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20045 StorageManager.FLAG_STORAGE_DE, 0); 20046 } catch (InstallerException e2) { 20047 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20048 } 20049 } 20050 } 20051 } 20052 20053 // Ensure that data directories are ready to roll for all packages 20054 // installed for this volume and user 20055 final List<PackageSetting> packages; 20056 synchronized (mPackages) { 20057 packages = mSettings.getVolumePackagesLPr(volumeUuid); 20058 } 20059 int preparedCount = 0; 20060 for (PackageSetting ps : packages) { 20061 final String packageName = ps.name; 20062 if (ps.pkg == null) { 20063 Slog.w(TAG, "Odd, missing scanned package " + packageName); 20064 // TODO: might be due to legacy ASEC apps; we should circle back 20065 // and reconcile again once they're scanned 20066 continue; 20067 } 20068 20069 if (ps.getInstalled(userId)) { 20070 prepareAppDataLIF(ps.pkg, userId, flags); 20071 20072 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 20073 // We may have just shuffled around app data directories, so 20074 // prepare them one more time 20075 prepareAppDataLIF(ps.pkg, userId, flags); 20076 } 20077 20078 preparedCount++; 20079 } 20080 } 20081 20082 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 20083 } 20084 20085 /** 20086 * Prepare app data for the given app just after it was installed or 20087 * upgraded. This method carefully only touches users that it's installed 20088 * for, and it forces a restorecon to handle any seinfo changes. 20089 * <p> 20090 * Verifies that directories exist and that ownership and labeling is 20091 * correct for all installed apps. If there is an ownership mismatch, it 20092 * will try recovering system apps by wiping data; third-party app data is 20093 * left intact. 20094 * <p> 20095 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 20096 */ 20097 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 20098 final PackageSetting ps; 20099 synchronized (mPackages) { 20100 ps = mSettings.mPackages.get(pkg.packageName); 20101 mSettings.writeKernelMappingLPr(ps); 20102 } 20103 20104 final UserManager um = mContext.getSystemService(UserManager.class); 20105 UserManagerInternal umInternal = getUserManagerInternal(); 20106 for (UserInfo user : um.getUsers()) { 20107 final int flags; 20108 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20109 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20110 } else if (umInternal.isUserRunning(user.id)) { 20111 flags = StorageManager.FLAG_STORAGE_DE; 20112 } else { 20113 continue; 20114 } 20115 20116 if (ps.getInstalled(user.id)) { 20117 // TODO: when user data is locked, mark that we're still dirty 20118 prepareAppDataLIF(pkg, user.id, flags); 20119 } 20120 } 20121 } 20122 20123 /** 20124 * Prepare app data for the given app. 20125 * <p> 20126 * Verifies that directories exist and that ownership and labeling is 20127 * correct for all installed apps. If there is an ownership mismatch, this 20128 * will try recovering system apps by wiping data; third-party app data is 20129 * left intact. 20130 */ 20131 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 20132 if (pkg == null) { 20133 Slog.wtf(TAG, "Package was null!", new Throwable()); 20134 return; 20135 } 20136 prepareAppDataLeafLIF(pkg, userId, flags); 20137 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20138 for (int i = 0; i < childCount; i++) { 20139 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 20140 } 20141 } 20142 20143 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20144 if (DEBUG_APP_DATA) { 20145 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 20146 + Integer.toHexString(flags)); 20147 } 20148 20149 final String volumeUuid = pkg.volumeUuid; 20150 final String packageName = pkg.packageName; 20151 final ApplicationInfo app = pkg.applicationInfo; 20152 final int appId = UserHandle.getAppId(app.uid); 20153 20154 Preconditions.checkNotNull(app.seinfo); 20155 20156 try { 20157 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20158 appId, app.seinfo, app.targetSdkVersion); 20159 } catch (InstallerException e) { 20160 if (app.isSystemApp()) { 20161 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 20162 + ", but trying to recover: " + e); 20163 destroyAppDataLeafLIF(pkg, userId, flags); 20164 try { 20165 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20166 appId, app.seinfo, app.targetSdkVersion); 20167 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 20168 } catch (InstallerException e2) { 20169 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 20170 } 20171 } else { 20172 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 20173 } 20174 } 20175 20176 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20177 try { 20178 // CE storage is unlocked right now, so read out the inode and 20179 // remember for use later when it's locked 20180 // TODO: mark this structure as dirty so we persist it! 20181 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 20182 StorageManager.FLAG_STORAGE_CE); 20183 synchronized (mPackages) { 20184 final PackageSetting ps = mSettings.mPackages.get(packageName); 20185 if (ps != null) { 20186 ps.setCeDataInode(ceDataInode, userId); 20187 } 20188 } 20189 } catch (InstallerException e) { 20190 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 20191 } 20192 } 20193 20194 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20195 } 20196 20197 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 20198 if (pkg == null) { 20199 Slog.wtf(TAG, "Package was null!", new Throwable()); 20200 return; 20201 } 20202 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20203 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20204 for (int i = 0; i < childCount; i++) { 20205 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 20206 } 20207 } 20208 20209 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20210 final String volumeUuid = pkg.volumeUuid; 20211 final String packageName = pkg.packageName; 20212 final ApplicationInfo app = pkg.applicationInfo; 20213 20214 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20215 // Create a native library symlink only if we have native libraries 20216 // and if the native libraries are 32 bit libraries. We do not provide 20217 // this symlink for 64 bit libraries. 20218 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20219 final String nativeLibPath = app.nativeLibraryDir; 20220 try { 20221 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20222 nativeLibPath, userId); 20223 } catch (InstallerException e) { 20224 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20225 } 20226 } 20227 } 20228 } 20229 20230 /** 20231 * For system apps on non-FBE devices, this method migrates any existing 20232 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20233 * requested by the app. 20234 */ 20235 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20236 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20237 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20238 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20239 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20240 try { 20241 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20242 storageTarget); 20243 } catch (InstallerException e) { 20244 logCriticalInfo(Log.WARN, 20245 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20246 } 20247 return true; 20248 } else { 20249 return false; 20250 } 20251 } 20252 20253 public PackageFreezer freezePackage(String packageName, String killReason) { 20254 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20255 } 20256 20257 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20258 return new PackageFreezer(packageName, userId, killReason); 20259 } 20260 20261 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20262 String killReason) { 20263 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20264 } 20265 20266 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20267 String killReason) { 20268 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20269 return new PackageFreezer(); 20270 } else { 20271 return freezePackage(packageName, userId, killReason); 20272 } 20273 } 20274 20275 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20276 String killReason) { 20277 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20278 } 20279 20280 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20281 String killReason) { 20282 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20283 return new PackageFreezer(); 20284 } else { 20285 return freezePackage(packageName, userId, killReason); 20286 } 20287 } 20288 20289 /** 20290 * Class that freezes and kills the given package upon creation, and 20291 * unfreezes it upon closing. This is typically used when doing surgery on 20292 * app code/data to prevent the app from running while you're working. 20293 */ 20294 private class PackageFreezer implements AutoCloseable { 20295 private final String mPackageName; 20296 private final PackageFreezer[] mChildren; 20297 20298 private final boolean mWeFroze; 20299 20300 private final AtomicBoolean mClosed = new AtomicBoolean(); 20301 private final CloseGuard mCloseGuard = CloseGuard.get(); 20302 20303 /** 20304 * Create and return a stub freezer that doesn't actually do anything, 20305 * typically used when someone requested 20306 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20307 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20308 */ 20309 public PackageFreezer() { 20310 mPackageName = null; 20311 mChildren = null; 20312 mWeFroze = false; 20313 mCloseGuard.open("close"); 20314 } 20315 20316 public PackageFreezer(String packageName, int userId, String killReason) { 20317 synchronized (mPackages) { 20318 mPackageName = packageName; 20319 mWeFroze = mFrozenPackages.add(mPackageName); 20320 20321 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20322 if (ps != null) { 20323 killApplication(ps.name, ps.appId, userId, killReason); 20324 } 20325 20326 final PackageParser.Package p = mPackages.get(packageName); 20327 if (p != null && p.childPackages != null) { 20328 final int N = p.childPackages.size(); 20329 mChildren = new PackageFreezer[N]; 20330 for (int i = 0; i < N; i++) { 20331 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20332 userId, killReason); 20333 } 20334 } else { 20335 mChildren = null; 20336 } 20337 } 20338 mCloseGuard.open("close"); 20339 } 20340 20341 @Override 20342 protected void finalize() throws Throwable { 20343 try { 20344 mCloseGuard.warnIfOpen(); 20345 close(); 20346 } finally { 20347 super.finalize(); 20348 } 20349 } 20350 20351 @Override 20352 public void close() { 20353 mCloseGuard.close(); 20354 if (mClosed.compareAndSet(false, true)) { 20355 synchronized (mPackages) { 20356 if (mWeFroze) { 20357 mFrozenPackages.remove(mPackageName); 20358 } 20359 20360 if (mChildren != null) { 20361 for (PackageFreezer freezer : mChildren) { 20362 freezer.close(); 20363 } 20364 } 20365 } 20366 } 20367 } 20368 } 20369 20370 /** 20371 * Verify that given package is currently frozen. 20372 */ 20373 private void checkPackageFrozen(String packageName) { 20374 synchronized (mPackages) { 20375 if (!mFrozenPackages.contains(packageName)) { 20376 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20377 } 20378 } 20379 } 20380 20381 @Override 20382 public int movePackage(final String packageName, final String volumeUuid) { 20383 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20384 20385 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20386 final int moveId = mNextMoveId.getAndIncrement(); 20387 mHandler.post(new Runnable() { 20388 @Override 20389 public void run() { 20390 try { 20391 movePackageInternal(packageName, volumeUuid, moveId, user); 20392 } catch (PackageManagerException e) { 20393 Slog.w(TAG, "Failed to move " + packageName, e); 20394 mMoveCallbacks.notifyStatusChanged(moveId, 20395 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20396 } 20397 } 20398 }); 20399 return moveId; 20400 } 20401 20402 private void movePackageInternal(final String packageName, final String volumeUuid, 20403 final int moveId, UserHandle user) throws PackageManagerException { 20404 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20405 final PackageManager pm = mContext.getPackageManager(); 20406 20407 final boolean currentAsec; 20408 final String currentVolumeUuid; 20409 final File codeFile; 20410 final String installerPackageName; 20411 final String packageAbiOverride; 20412 final int appId; 20413 final String seinfo; 20414 final String label; 20415 final int targetSdkVersion; 20416 final PackageFreezer freezer; 20417 final int[] installedUserIds; 20418 20419 // reader 20420 synchronized (mPackages) { 20421 final PackageParser.Package pkg = mPackages.get(packageName); 20422 final PackageSetting ps = mSettings.mPackages.get(packageName); 20423 if (pkg == null || ps == null) { 20424 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20425 } 20426 20427 if (pkg.applicationInfo.isSystemApp()) { 20428 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20429 "Cannot move system application"); 20430 } 20431 20432 if (pkg.applicationInfo.isExternalAsec()) { 20433 currentAsec = true; 20434 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20435 } else if (pkg.applicationInfo.isForwardLocked()) { 20436 currentAsec = true; 20437 currentVolumeUuid = "forward_locked"; 20438 } else { 20439 currentAsec = false; 20440 currentVolumeUuid = ps.volumeUuid; 20441 20442 final File probe = new File(pkg.codePath); 20443 final File probeOat = new File(probe, "oat"); 20444 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20445 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20446 "Move only supported for modern cluster style installs"); 20447 } 20448 } 20449 20450 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20451 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20452 "Package already moved to " + volumeUuid); 20453 } 20454 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20455 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20456 "Device admin cannot be moved"); 20457 } 20458 20459 if (mFrozenPackages.contains(packageName)) { 20460 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20461 "Failed to move already frozen package"); 20462 } 20463 20464 codeFile = new File(pkg.codePath); 20465 installerPackageName = ps.installerPackageName; 20466 packageAbiOverride = ps.cpuAbiOverrideString; 20467 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20468 seinfo = pkg.applicationInfo.seinfo; 20469 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20470 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20471 freezer = freezePackage(packageName, "movePackageInternal"); 20472 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20473 } 20474 20475 final Bundle extras = new Bundle(); 20476 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20477 extras.putString(Intent.EXTRA_TITLE, label); 20478 mMoveCallbacks.notifyCreated(moveId, extras); 20479 20480 int installFlags; 20481 final boolean moveCompleteApp; 20482 final File measurePath; 20483 20484 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20485 installFlags = INSTALL_INTERNAL; 20486 moveCompleteApp = !currentAsec; 20487 measurePath = Environment.getDataAppDirectory(volumeUuid); 20488 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20489 installFlags = INSTALL_EXTERNAL; 20490 moveCompleteApp = false; 20491 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20492 } else { 20493 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20494 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20495 || !volume.isMountedWritable()) { 20496 freezer.close(); 20497 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20498 "Move location not mounted private volume"); 20499 } 20500 20501 Preconditions.checkState(!currentAsec); 20502 20503 installFlags = INSTALL_INTERNAL; 20504 moveCompleteApp = true; 20505 measurePath = Environment.getDataAppDirectory(volumeUuid); 20506 } 20507 20508 final PackageStats stats = new PackageStats(null, -1); 20509 synchronized (mInstaller) { 20510 for (int userId : installedUserIds) { 20511 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20512 freezer.close(); 20513 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20514 "Failed to measure package size"); 20515 } 20516 } 20517 } 20518 20519 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20520 + stats.dataSize); 20521 20522 final long startFreeBytes = measurePath.getFreeSpace(); 20523 final long sizeBytes; 20524 if (moveCompleteApp) { 20525 sizeBytes = stats.codeSize + stats.dataSize; 20526 } else { 20527 sizeBytes = stats.codeSize; 20528 } 20529 20530 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20531 freezer.close(); 20532 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20533 "Not enough free space to move"); 20534 } 20535 20536 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20537 20538 final CountDownLatch installedLatch = new CountDownLatch(1); 20539 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20540 @Override 20541 public void onUserActionRequired(Intent intent) throws RemoteException { 20542 throw new IllegalStateException(); 20543 } 20544 20545 @Override 20546 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20547 Bundle extras) throws RemoteException { 20548 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20549 + PackageManager.installStatusToString(returnCode, msg)); 20550 20551 installedLatch.countDown(); 20552 freezer.close(); 20553 20554 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20555 switch (status) { 20556 case PackageInstaller.STATUS_SUCCESS: 20557 mMoveCallbacks.notifyStatusChanged(moveId, 20558 PackageManager.MOVE_SUCCEEDED); 20559 break; 20560 case PackageInstaller.STATUS_FAILURE_STORAGE: 20561 mMoveCallbacks.notifyStatusChanged(moveId, 20562 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20563 break; 20564 default: 20565 mMoveCallbacks.notifyStatusChanged(moveId, 20566 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20567 break; 20568 } 20569 } 20570 }; 20571 20572 final MoveInfo move; 20573 if (moveCompleteApp) { 20574 // Kick off a thread to report progress estimates 20575 new Thread() { 20576 @Override 20577 public void run() { 20578 while (true) { 20579 try { 20580 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20581 break; 20582 } 20583 } catch (InterruptedException ignored) { 20584 } 20585 20586 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20587 final int progress = 10 + (int) MathUtils.constrain( 20588 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20589 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20590 } 20591 } 20592 }.start(); 20593 20594 final String dataAppName = codeFile.getName(); 20595 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20596 dataAppName, appId, seinfo, targetSdkVersion); 20597 } else { 20598 move = null; 20599 } 20600 20601 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20602 20603 final Message msg = mHandler.obtainMessage(INIT_COPY); 20604 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20605 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20606 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20607 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20608 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20609 msg.obj = params; 20610 20611 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20612 System.identityHashCode(msg.obj)); 20613 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20614 System.identityHashCode(msg.obj)); 20615 20616 mHandler.sendMessage(msg); 20617 } 20618 20619 @Override 20620 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20621 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20622 20623 final int realMoveId = mNextMoveId.getAndIncrement(); 20624 final Bundle extras = new Bundle(); 20625 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20626 mMoveCallbacks.notifyCreated(realMoveId, extras); 20627 20628 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20629 @Override 20630 public void onCreated(int moveId, Bundle extras) { 20631 // Ignored 20632 } 20633 20634 @Override 20635 public void onStatusChanged(int moveId, int status, long estMillis) { 20636 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20637 } 20638 }; 20639 20640 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20641 storage.setPrimaryStorageUuid(volumeUuid, callback); 20642 return realMoveId; 20643 } 20644 20645 @Override 20646 public int getMoveStatus(int moveId) { 20647 mContext.enforceCallingOrSelfPermission( 20648 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20649 return mMoveCallbacks.mLastStatus.get(moveId); 20650 } 20651 20652 @Override 20653 public void registerMoveCallback(IPackageMoveObserver callback) { 20654 mContext.enforceCallingOrSelfPermission( 20655 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20656 mMoveCallbacks.register(callback); 20657 } 20658 20659 @Override 20660 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20661 mContext.enforceCallingOrSelfPermission( 20662 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20663 mMoveCallbacks.unregister(callback); 20664 } 20665 20666 @Override 20667 public boolean setInstallLocation(int loc) { 20668 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20669 null); 20670 if (getInstallLocation() == loc) { 20671 return true; 20672 } 20673 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20674 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20675 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20676 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20677 return true; 20678 } 20679 return false; 20680 } 20681 20682 @Override 20683 public int getInstallLocation() { 20684 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20685 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20686 PackageHelper.APP_INSTALL_AUTO); 20687 } 20688 20689 /** Called by UserManagerService */ 20690 void cleanUpUser(UserManagerService userManager, int userHandle) { 20691 synchronized (mPackages) { 20692 mDirtyUsers.remove(userHandle); 20693 mUserNeedsBadging.delete(userHandle); 20694 mSettings.removeUserLPw(userHandle); 20695 mPendingBroadcasts.remove(userHandle); 20696 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20697 removeUnusedPackagesLPw(userManager, userHandle); 20698 } 20699 } 20700 20701 /** 20702 * We're removing userHandle and would like to remove any downloaded packages 20703 * that are no longer in use by any other user. 20704 * @param userHandle the user being removed 20705 */ 20706 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20707 final boolean DEBUG_CLEAN_APKS = false; 20708 int [] users = userManager.getUserIds(); 20709 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20710 while (psit.hasNext()) { 20711 PackageSetting ps = psit.next(); 20712 if (ps.pkg == null) { 20713 continue; 20714 } 20715 final String packageName = ps.pkg.packageName; 20716 // Skip over if system app 20717 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20718 continue; 20719 } 20720 if (DEBUG_CLEAN_APKS) { 20721 Slog.i(TAG, "Checking package " + packageName); 20722 } 20723 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20724 if (keep) { 20725 if (DEBUG_CLEAN_APKS) { 20726 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20727 } 20728 } else { 20729 for (int i = 0; i < users.length; i++) { 20730 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20731 keep = true; 20732 if (DEBUG_CLEAN_APKS) { 20733 Slog.i(TAG, " Keeping package " + packageName + " for user " 20734 + users[i]); 20735 } 20736 break; 20737 } 20738 } 20739 } 20740 if (!keep) { 20741 if (DEBUG_CLEAN_APKS) { 20742 Slog.i(TAG, " Removing package " + packageName); 20743 } 20744 mHandler.post(new Runnable() { 20745 public void run() { 20746 deletePackageX(packageName, userHandle, 0); 20747 } //end run 20748 }); 20749 } 20750 } 20751 } 20752 20753 /** Called by UserManagerService */ 20754 void createNewUser(int userId, String[] disallowedPackages) { 20755 synchronized (mInstallLock) { 20756 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 20757 } 20758 synchronized (mPackages) { 20759 scheduleWritePackageRestrictionsLocked(userId); 20760 scheduleWritePackageListLocked(userId); 20761 applyFactoryDefaultBrowserLPw(userId); 20762 primeDomainVerificationsLPw(userId); 20763 } 20764 } 20765 20766 void onNewUserCreated(final int userId) { 20767 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20768 // If permission review for legacy apps is required, we represent 20769 // dagerous permissions for such apps as always granted runtime 20770 // permissions to keep per user flag state whether review is needed. 20771 // Hence, if a new user is added we have to propagate dangerous 20772 // permission grants for these legacy apps. 20773 if (mPermissionReviewRequired) { 20774 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20775 | UPDATE_PERMISSIONS_REPLACE_ALL); 20776 } 20777 } 20778 20779 @Override 20780 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20781 mContext.enforceCallingOrSelfPermission( 20782 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20783 "Only package verification agents can read the verifier device identity"); 20784 20785 synchronized (mPackages) { 20786 return mSettings.getVerifierDeviceIdentityLPw(); 20787 } 20788 } 20789 20790 @Override 20791 public void setPermissionEnforced(String permission, boolean enforced) { 20792 // TODO: Now that we no longer change GID for storage, this should to away. 20793 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20794 "setPermissionEnforced"); 20795 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20796 synchronized (mPackages) { 20797 if (mSettings.mReadExternalStorageEnforced == null 20798 || mSettings.mReadExternalStorageEnforced != enforced) { 20799 mSettings.mReadExternalStorageEnforced = enforced; 20800 mSettings.writeLPr(); 20801 } 20802 } 20803 // kill any non-foreground processes so we restart them and 20804 // grant/revoke the GID. 20805 final IActivityManager am = ActivityManager.getService(); 20806 if (am != null) { 20807 final long token = Binder.clearCallingIdentity(); 20808 try { 20809 am.killProcessesBelowForeground("setPermissionEnforcement"); 20810 } catch (RemoteException e) { 20811 } finally { 20812 Binder.restoreCallingIdentity(token); 20813 } 20814 } 20815 } else { 20816 throw new IllegalArgumentException("No selective enforcement for " + permission); 20817 } 20818 } 20819 20820 @Override 20821 @Deprecated 20822 public boolean isPermissionEnforced(String permission) { 20823 return true; 20824 } 20825 20826 @Override 20827 public boolean isStorageLow() { 20828 final long token = Binder.clearCallingIdentity(); 20829 try { 20830 final DeviceStorageMonitorInternal 20831 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20832 if (dsm != null) { 20833 return dsm.isMemoryLow(); 20834 } else { 20835 return false; 20836 } 20837 } finally { 20838 Binder.restoreCallingIdentity(token); 20839 } 20840 } 20841 20842 @Override 20843 public IPackageInstaller getPackageInstaller() { 20844 return mInstallerService; 20845 } 20846 20847 private boolean userNeedsBadging(int userId) { 20848 int index = mUserNeedsBadging.indexOfKey(userId); 20849 if (index < 0) { 20850 final UserInfo userInfo; 20851 final long token = Binder.clearCallingIdentity(); 20852 try { 20853 userInfo = sUserManager.getUserInfo(userId); 20854 } finally { 20855 Binder.restoreCallingIdentity(token); 20856 } 20857 final boolean b; 20858 if (userInfo != null && userInfo.isManagedProfile()) { 20859 b = true; 20860 } else { 20861 b = false; 20862 } 20863 mUserNeedsBadging.put(userId, b); 20864 return b; 20865 } 20866 return mUserNeedsBadging.valueAt(index); 20867 } 20868 20869 @Override 20870 public KeySet getKeySetByAlias(String packageName, String alias) { 20871 if (packageName == null || alias == null) { 20872 return null; 20873 } 20874 synchronized(mPackages) { 20875 final PackageParser.Package pkg = mPackages.get(packageName); 20876 if (pkg == null) { 20877 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20878 throw new IllegalArgumentException("Unknown package: " + packageName); 20879 } 20880 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20881 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20882 } 20883 } 20884 20885 @Override 20886 public KeySet getSigningKeySet(String packageName) { 20887 if (packageName == null) { 20888 return null; 20889 } 20890 synchronized(mPackages) { 20891 final PackageParser.Package pkg = mPackages.get(packageName); 20892 if (pkg == null) { 20893 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20894 throw new IllegalArgumentException("Unknown package: " + packageName); 20895 } 20896 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20897 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20898 throw new SecurityException("May not access signing KeySet of other apps."); 20899 } 20900 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20901 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20902 } 20903 } 20904 20905 @Override 20906 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20907 if (packageName == null || ks == null) { 20908 return false; 20909 } 20910 synchronized(mPackages) { 20911 final PackageParser.Package pkg = mPackages.get(packageName); 20912 if (pkg == null) { 20913 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20914 throw new IllegalArgumentException("Unknown package: " + packageName); 20915 } 20916 IBinder ksh = ks.getToken(); 20917 if (ksh instanceof KeySetHandle) { 20918 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20919 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20920 } 20921 return false; 20922 } 20923 } 20924 20925 @Override 20926 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20927 if (packageName == null || ks == null) { 20928 return false; 20929 } 20930 synchronized(mPackages) { 20931 final PackageParser.Package pkg = mPackages.get(packageName); 20932 if (pkg == null) { 20933 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20934 throw new IllegalArgumentException("Unknown package: " + packageName); 20935 } 20936 IBinder ksh = ks.getToken(); 20937 if (ksh instanceof KeySetHandle) { 20938 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20939 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20940 } 20941 return false; 20942 } 20943 } 20944 20945 private void deletePackageIfUnusedLPr(final String packageName) { 20946 PackageSetting ps = mSettings.mPackages.get(packageName); 20947 if (ps == null) { 20948 return; 20949 } 20950 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20951 // TODO Implement atomic delete if package is unused 20952 // It is currently possible that the package will be deleted even if it is installed 20953 // after this method returns. 20954 mHandler.post(new Runnable() { 20955 public void run() { 20956 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20957 } 20958 }); 20959 } 20960 } 20961 20962 /** 20963 * Check and throw if the given before/after packages would be considered a 20964 * downgrade. 20965 */ 20966 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20967 throws PackageManagerException { 20968 if (after.versionCode < before.mVersionCode) { 20969 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20970 "Update version code " + after.versionCode + " is older than current " 20971 + before.mVersionCode); 20972 } else if (after.versionCode == before.mVersionCode) { 20973 if (after.baseRevisionCode < before.baseRevisionCode) { 20974 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20975 "Update base revision code " + after.baseRevisionCode 20976 + " is older than current " + before.baseRevisionCode); 20977 } 20978 20979 if (!ArrayUtils.isEmpty(after.splitNames)) { 20980 for (int i = 0; i < after.splitNames.length; i++) { 20981 final String splitName = after.splitNames[i]; 20982 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20983 if (j != -1) { 20984 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20985 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20986 "Update split " + splitName + " revision code " 20987 + after.splitRevisionCodes[i] + " is older than current " 20988 + before.splitRevisionCodes[j]); 20989 } 20990 } 20991 } 20992 } 20993 } 20994 } 20995 20996 private static class MoveCallbacks extends Handler { 20997 private static final int MSG_CREATED = 1; 20998 private static final int MSG_STATUS_CHANGED = 2; 20999 21000 private final RemoteCallbackList<IPackageMoveObserver> 21001 mCallbacks = new RemoteCallbackList<>(); 21002 21003 private final SparseIntArray mLastStatus = new SparseIntArray(); 21004 21005 public MoveCallbacks(Looper looper) { 21006 super(looper); 21007 } 21008 21009 public void register(IPackageMoveObserver callback) { 21010 mCallbacks.register(callback); 21011 } 21012 21013 public void unregister(IPackageMoveObserver callback) { 21014 mCallbacks.unregister(callback); 21015 } 21016 21017 @Override 21018 public void handleMessage(Message msg) { 21019 final SomeArgs args = (SomeArgs) msg.obj; 21020 final int n = mCallbacks.beginBroadcast(); 21021 for (int i = 0; i < n; i++) { 21022 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 21023 try { 21024 invokeCallback(callback, msg.what, args); 21025 } catch (RemoteException ignored) { 21026 } 21027 } 21028 mCallbacks.finishBroadcast(); 21029 args.recycle(); 21030 } 21031 21032 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 21033 throws RemoteException { 21034 switch (what) { 21035 case MSG_CREATED: { 21036 callback.onCreated(args.argi1, (Bundle) args.arg2); 21037 break; 21038 } 21039 case MSG_STATUS_CHANGED: { 21040 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 21041 break; 21042 } 21043 } 21044 } 21045 21046 private void notifyCreated(int moveId, Bundle extras) { 21047 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 21048 21049 final SomeArgs args = SomeArgs.obtain(); 21050 args.argi1 = moveId; 21051 args.arg2 = extras; 21052 obtainMessage(MSG_CREATED, args).sendToTarget(); 21053 } 21054 21055 private void notifyStatusChanged(int moveId, int status) { 21056 notifyStatusChanged(moveId, status, -1); 21057 } 21058 21059 private void notifyStatusChanged(int moveId, int status, long estMillis) { 21060 Slog.v(TAG, "Move " + moveId + " status " + status); 21061 21062 final SomeArgs args = SomeArgs.obtain(); 21063 args.argi1 = moveId; 21064 args.argi2 = status; 21065 args.arg3 = estMillis; 21066 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 21067 21068 synchronized (mLastStatus) { 21069 mLastStatus.put(moveId, status); 21070 } 21071 } 21072 } 21073 21074 private final static class OnPermissionChangeListeners extends Handler { 21075 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 21076 21077 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 21078 new RemoteCallbackList<>(); 21079 21080 public OnPermissionChangeListeners(Looper looper) { 21081 super(looper); 21082 } 21083 21084 @Override 21085 public void handleMessage(Message msg) { 21086 switch (msg.what) { 21087 case MSG_ON_PERMISSIONS_CHANGED: { 21088 final int uid = msg.arg1; 21089 handleOnPermissionsChanged(uid); 21090 } break; 21091 } 21092 } 21093 21094 public void addListenerLocked(IOnPermissionsChangeListener listener) { 21095 mPermissionListeners.register(listener); 21096 21097 } 21098 21099 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 21100 mPermissionListeners.unregister(listener); 21101 } 21102 21103 public void onPermissionsChanged(int uid) { 21104 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 21105 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 21106 } 21107 } 21108 21109 private void handleOnPermissionsChanged(int uid) { 21110 final int count = mPermissionListeners.beginBroadcast(); 21111 try { 21112 for (int i = 0; i < count; i++) { 21113 IOnPermissionsChangeListener callback = mPermissionListeners 21114 .getBroadcastItem(i); 21115 try { 21116 callback.onPermissionsChanged(uid); 21117 } catch (RemoteException e) { 21118 Log.e(TAG, "Permission listener is dead", e); 21119 } 21120 } 21121 } finally { 21122 mPermissionListeners.finishBroadcast(); 21123 } 21124 } 21125 } 21126 21127 private class PackageManagerInternalImpl extends PackageManagerInternal { 21128 @Override 21129 public void setLocationPackagesProvider(PackagesProvider provider) { 21130 synchronized (mPackages) { 21131 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 21132 } 21133 } 21134 21135 @Override 21136 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 21137 synchronized (mPackages) { 21138 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 21139 } 21140 } 21141 21142 @Override 21143 public void setSmsAppPackagesProvider(PackagesProvider provider) { 21144 synchronized (mPackages) { 21145 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 21146 } 21147 } 21148 21149 @Override 21150 public void setDialerAppPackagesProvider(PackagesProvider provider) { 21151 synchronized (mPackages) { 21152 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 21153 } 21154 } 21155 21156 @Override 21157 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 21158 synchronized (mPackages) { 21159 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 21160 } 21161 } 21162 21163 @Override 21164 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 21165 synchronized (mPackages) { 21166 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 21167 } 21168 } 21169 21170 @Override 21171 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 21172 synchronized (mPackages) { 21173 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 21174 packageName, userId); 21175 } 21176 } 21177 21178 @Override 21179 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 21180 synchronized (mPackages) { 21181 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 21182 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 21183 packageName, userId); 21184 } 21185 } 21186 21187 @Override 21188 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 21189 synchronized (mPackages) { 21190 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 21191 packageName, userId); 21192 } 21193 } 21194 21195 @Override 21196 public void setKeepUninstalledPackages(final List<String> packageList) { 21197 Preconditions.checkNotNull(packageList); 21198 List<String> removedFromList = null; 21199 synchronized (mPackages) { 21200 if (mKeepUninstalledPackages != null) { 21201 final int packagesCount = mKeepUninstalledPackages.size(); 21202 for (int i = 0; i < packagesCount; i++) { 21203 String oldPackage = mKeepUninstalledPackages.get(i); 21204 if (packageList != null && packageList.contains(oldPackage)) { 21205 continue; 21206 } 21207 if (removedFromList == null) { 21208 removedFromList = new ArrayList<>(); 21209 } 21210 removedFromList.add(oldPackage); 21211 } 21212 } 21213 mKeepUninstalledPackages = new ArrayList<>(packageList); 21214 if (removedFromList != null) { 21215 final int removedCount = removedFromList.size(); 21216 for (int i = 0; i < removedCount; i++) { 21217 deletePackageIfUnusedLPr(removedFromList.get(i)); 21218 } 21219 } 21220 } 21221 } 21222 21223 @Override 21224 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21225 synchronized (mPackages) { 21226 // If we do not support permission review, done. 21227 if (!mPermissionReviewRequired) { 21228 return false; 21229 } 21230 21231 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21232 if (packageSetting == null) { 21233 return false; 21234 } 21235 21236 // Permission review applies only to apps not supporting the new permission model. 21237 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21238 return false; 21239 } 21240 21241 // Legacy apps have the permission and get user consent on launch. 21242 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21243 return permissionsState.isPermissionReviewRequired(userId); 21244 } 21245 } 21246 21247 @Override 21248 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21249 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21250 } 21251 21252 @Override 21253 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21254 int userId) { 21255 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21256 } 21257 21258 @Override 21259 public void setDeviceAndProfileOwnerPackages( 21260 int deviceOwnerUserId, String deviceOwnerPackage, 21261 SparseArray<String> profileOwnerPackages) { 21262 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21263 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21264 } 21265 21266 @Override 21267 public boolean isPackageDataProtected(int userId, String packageName) { 21268 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21269 } 21270 21271 @Override 21272 public boolean isPackageEphemeral(int userId, String packageName) { 21273 synchronized (mPackages) { 21274 PackageParser.Package p = mPackages.get(packageName); 21275 return p != null ? p.applicationInfo.isEphemeralApp() : false; 21276 } 21277 } 21278 21279 @Override 21280 public boolean wasPackageEverLaunched(String packageName, int userId) { 21281 synchronized (mPackages) { 21282 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21283 } 21284 } 21285 21286 @Override 21287 public void grantRuntimePermission(String packageName, String name, int userId, 21288 boolean overridePolicy) { 21289 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 21290 overridePolicy); 21291 } 21292 21293 @Override 21294 public void revokeRuntimePermission(String packageName, String name, int userId, 21295 boolean overridePolicy) { 21296 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 21297 overridePolicy); 21298 } 21299 21300 @Override 21301 public String getNameForUid(int uid) { 21302 return PackageManagerService.this.getNameForUid(uid); 21303 } 21304 21305 @Override 21306 public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 21307 Intent origIntent, String resolvedType, Intent launchIntent, 21308 String callingPackage, int userId) { 21309 PackageManagerService.this.requestEphemeralResolutionPhaseTwo( 21310 responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId); 21311 } 21312 } 21313 21314 @Override 21315 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21316 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21317 synchronized (mPackages) { 21318 final long identity = Binder.clearCallingIdentity(); 21319 try { 21320 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21321 packageNames, userId); 21322 } finally { 21323 Binder.restoreCallingIdentity(identity); 21324 } 21325 } 21326 } 21327 21328 private static void enforceSystemOrPhoneCaller(String tag) { 21329 int callingUid = Binder.getCallingUid(); 21330 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21331 throw new SecurityException( 21332 "Cannot call " + tag + " from UID " + callingUid); 21333 } 21334 } 21335 21336 boolean isHistoricalPackageUsageAvailable() { 21337 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21338 } 21339 21340 /** 21341 * Return a <b>copy</b> of the collection of packages known to the package manager. 21342 * @return A copy of the values of mPackages. 21343 */ 21344 Collection<PackageParser.Package> getPackages() { 21345 synchronized (mPackages) { 21346 return new ArrayList<>(mPackages.values()); 21347 } 21348 } 21349 21350 /** 21351 * Logs process start information (including base APK hash) to the security log. 21352 * @hide 21353 */ 21354 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21355 String apkFile, int pid) { 21356 if (!SecurityLog.isLoggingEnabled()) { 21357 return; 21358 } 21359 Bundle data = new Bundle(); 21360 data.putLong("startTimestamp", System.currentTimeMillis()); 21361 data.putString("processName", processName); 21362 data.putInt("uid", uid); 21363 data.putString("seinfo", seinfo); 21364 data.putString("apkFile", apkFile); 21365 data.putInt("pid", pid); 21366 Message msg = mProcessLoggingHandler.obtainMessage( 21367 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21368 msg.setData(data); 21369 mProcessLoggingHandler.sendMessage(msg); 21370 } 21371 21372 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21373 return mCompilerStats.getPackageStats(pkgName); 21374 } 21375 21376 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21377 return getOrCreateCompilerPackageStats(pkg.packageName); 21378 } 21379 21380 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21381 return mCompilerStats.getOrCreatePackageStats(pkgName); 21382 } 21383 21384 public void deleteCompilerPackageStats(String pkgName) { 21385 mCompilerStats.deletePackageStats(pkgName); 21386 } 21387} 21388