PackageManagerService.java revision bdcdeb4cc470130db9ddb7abe7763c2170755e22
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 static final int REMOVE_CHATTY = 1<<16; 406 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17; 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 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2219 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2220 2221 if (bootClassPath == null) { 2222 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2223 } 2224 2225 if (systemServerClassPath == null) { 2226 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2227 } 2228 2229 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2230 final String[] dexCodeInstructionSets = 2231 getDexCodeInstructionSets( 2232 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2233 2234 /** 2235 * Ensure all external libraries have had dexopt run on them. 2236 */ 2237 if (mSharedLibraries.size() > 0) { 2238 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2239 // NOTE: For now, we're compiling these system "shared libraries" 2240 // (and framework jars) into all available architectures. It's possible 2241 // to compile them only when we come across an app that uses them (there's 2242 // already logic for that in scanPackageLI) but that adds some complexity. 2243 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2244 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2245 final String lib = libEntry.path; 2246 if (lib == null) { 2247 continue; 2248 } 2249 2250 try { 2251 // Shared libraries do not have profiles so we perform a full 2252 // AOT compilation (if needed). 2253 int dexoptNeeded = DexFile.getDexOptNeeded( 2254 lib, dexCodeInstructionSet, 2255 getCompilerFilterForReason(REASON_SHARED_APK), 2256 false /* newProfile */); 2257 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2258 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2259 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2260 getCompilerFilterForReason(REASON_SHARED_APK), 2261 StorageManager.UUID_PRIVATE_INTERNAL, 2262 SKIP_SHARED_LIBRARY_CHECK); 2263 } 2264 } catch (FileNotFoundException e) { 2265 Slog.w(TAG, "Library not found: " + lib); 2266 } catch (IOException | InstallerException e) { 2267 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2268 + e.getMessage()); 2269 } 2270 } 2271 } 2272 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2273 } 2274 2275 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2276 2277 final VersionInfo ver = mSettings.getInternalVersion(); 2278 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2279 2280 // when upgrading from pre-M, promote system app permissions from install to runtime 2281 mPromoteSystemApps = 2282 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2283 2284 // When upgrading from pre-N, we need to handle package extraction like first boot, 2285 // as there is no profiling data available. 2286 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2287 2288 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2289 2290 // save off the names of pre-existing system packages prior to scanning; we don't 2291 // want to automatically grant runtime permissions for new system apps 2292 if (mPromoteSystemApps) { 2293 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2294 while (pkgSettingIter.hasNext()) { 2295 PackageSetting ps = pkgSettingIter.next(); 2296 if (isSystemApp(ps)) { 2297 mExistingSystemPackages.add(ps.name); 2298 } 2299 } 2300 } 2301 2302 // Set flag to monitor and not change apk file paths when 2303 // scanning install directories. 2304 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2305 2306 if (mIsUpgrade || mFirstBoot) { 2307 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2308 } 2309 2310 // Collect vendor overlay packages. (Do this before scanning any apps.) 2311 // For security and version matching reason, only consider 2312 // overlay packages if they reside in the right directory. 2313 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2314 if (overlayThemeDir.isEmpty()) { 2315 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2316 } 2317 if (!overlayThemeDir.isEmpty()) { 2318 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2319 | PackageParser.PARSE_IS_SYSTEM 2320 | PackageParser.PARSE_IS_SYSTEM_DIR 2321 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2322 } 2323 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2324 | PackageParser.PARSE_IS_SYSTEM 2325 | PackageParser.PARSE_IS_SYSTEM_DIR 2326 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2327 2328 // Find base frameworks (resource packages without code). 2329 scanDirTracedLI(frameworkDir, mDefParseFlags 2330 | PackageParser.PARSE_IS_SYSTEM 2331 | PackageParser.PARSE_IS_SYSTEM_DIR 2332 | PackageParser.PARSE_IS_PRIVILEGED, 2333 scanFlags | SCAN_NO_DEX, 0); 2334 2335 // Collected privileged system packages. 2336 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2337 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2338 | PackageParser.PARSE_IS_SYSTEM 2339 | PackageParser.PARSE_IS_SYSTEM_DIR 2340 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2341 2342 // Collect ordinary system packages. 2343 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2344 scanDirTracedLI(systemAppDir, mDefParseFlags 2345 | PackageParser.PARSE_IS_SYSTEM 2346 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2347 2348 // Collect all vendor packages. 2349 File vendorAppDir = new File("/vendor/app"); 2350 try { 2351 vendorAppDir = vendorAppDir.getCanonicalFile(); 2352 } catch (IOException e) { 2353 // failed to look up canonical path, continue with original one 2354 } 2355 scanDirTracedLI(vendorAppDir, mDefParseFlags 2356 | PackageParser.PARSE_IS_SYSTEM 2357 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2358 2359 // Collect all OEM packages. 2360 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2361 scanDirTracedLI(oemAppDir, mDefParseFlags 2362 | PackageParser.PARSE_IS_SYSTEM 2363 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2364 2365 // Prune any system packages that no longer exist. 2366 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2367 if (!mOnlyCore) { 2368 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2369 while (psit.hasNext()) { 2370 PackageSetting ps = psit.next(); 2371 2372 /* 2373 * If this is not a system app, it can't be a 2374 * disable system app. 2375 */ 2376 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2377 continue; 2378 } 2379 2380 /* 2381 * If the package is scanned, it's not erased. 2382 */ 2383 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2384 if (scannedPkg != null) { 2385 /* 2386 * If the system app is both scanned and in the 2387 * disabled packages list, then it must have been 2388 * added via OTA. Remove it from the currently 2389 * scanned package so the previously user-installed 2390 * application can be scanned. 2391 */ 2392 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2393 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2394 + ps.name + "; removing system app. Last known codePath=" 2395 + ps.codePathString + ", installStatus=" + ps.installStatus 2396 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2397 + scannedPkg.mVersionCode); 2398 removePackageLI(scannedPkg, true); 2399 mExpectingBetter.put(ps.name, ps.codePath); 2400 } 2401 2402 continue; 2403 } 2404 2405 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2406 psit.remove(); 2407 logCriticalInfo(Log.WARN, "System package " + ps.name 2408 + " no longer exists; it's data will be wiped"); 2409 // Actual deletion of code and data will be handled by later 2410 // reconciliation step 2411 } else { 2412 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2413 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2414 possiblyDeletedUpdatedSystemApps.add(ps.name); 2415 } 2416 } 2417 } 2418 } 2419 2420 //look for any incomplete package installations 2421 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2422 for (int i = 0; i < deletePkgsList.size(); i++) { 2423 // Actual deletion of code and data will be handled by later 2424 // reconciliation step 2425 final String packageName = deletePkgsList.get(i).name; 2426 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2427 synchronized (mPackages) { 2428 mSettings.removePackageLPw(packageName); 2429 } 2430 } 2431 2432 //delete tmp files 2433 deleteTempPackageFiles(); 2434 2435 // Remove any shared userIDs that have no associated packages 2436 mSettings.pruneSharedUsersLPw(); 2437 2438 if (!mOnlyCore) { 2439 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2440 SystemClock.uptimeMillis()); 2441 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2442 2443 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2444 | PackageParser.PARSE_FORWARD_LOCK, 2445 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2446 2447 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2448 | PackageParser.PARSE_IS_EPHEMERAL, 2449 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2450 2451 /** 2452 * Remove disable package settings for any updated system 2453 * apps that were removed via an OTA. If they're not a 2454 * previously-updated app, remove them completely. 2455 * Otherwise, just revoke their system-level permissions. 2456 */ 2457 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2458 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2459 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2460 2461 String msg; 2462 if (deletedPkg == null) { 2463 msg = "Updated system package " + deletedAppName 2464 + " no longer exists; it's data will be wiped"; 2465 // Actual deletion of code and data will be handled by later 2466 // reconciliation step 2467 } else { 2468 msg = "Updated system app + " + deletedAppName 2469 + " no longer present; removing system privileges for " 2470 + deletedAppName; 2471 2472 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2473 2474 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2475 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2476 } 2477 logCriticalInfo(Log.WARN, msg); 2478 } 2479 2480 /** 2481 * Make sure all system apps that we expected to appear on 2482 * the userdata partition actually showed up. If they never 2483 * appeared, crawl back and revive the system version. 2484 */ 2485 for (int i = 0; i < mExpectingBetter.size(); i++) { 2486 final String packageName = mExpectingBetter.keyAt(i); 2487 if (!mPackages.containsKey(packageName)) { 2488 final File scanFile = mExpectingBetter.valueAt(i); 2489 2490 logCriticalInfo(Log.WARN, "Expected better " + packageName 2491 + " but never showed up; reverting to system"); 2492 2493 int reparseFlags = mDefParseFlags; 2494 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2495 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2496 | PackageParser.PARSE_IS_SYSTEM_DIR 2497 | PackageParser.PARSE_IS_PRIVILEGED; 2498 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2499 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2500 | PackageParser.PARSE_IS_SYSTEM_DIR; 2501 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2502 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2503 | PackageParser.PARSE_IS_SYSTEM_DIR; 2504 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2505 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2506 | PackageParser.PARSE_IS_SYSTEM_DIR; 2507 } else { 2508 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2509 continue; 2510 } 2511 2512 mSettings.enableSystemPackageLPw(packageName); 2513 2514 try { 2515 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2516 } catch (PackageManagerException e) { 2517 Slog.e(TAG, "Failed to parse original system package: " 2518 + e.getMessage()); 2519 } 2520 } 2521 } 2522 } 2523 mExpectingBetter.clear(); 2524 2525 // Resolve the storage manager. 2526 mStorageManagerPackage = getStorageManagerPackageName(); 2527 2528 // Resolve protected action filters. Only the setup wizard is allowed to 2529 // have a high priority filter for these actions. 2530 mSetupWizardPackage = getSetupWizardPackageName(); 2531 if (mProtectedFilters.size() > 0) { 2532 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2533 Slog.i(TAG, "No setup wizard;" 2534 + " All protected intents capped to priority 0"); 2535 } 2536 for (ActivityIntentInfo filter : mProtectedFilters) { 2537 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2538 if (DEBUG_FILTERS) { 2539 Slog.i(TAG, "Found setup wizard;" 2540 + " allow priority " + filter.getPriority() + ";" 2541 + " package: " + filter.activity.info.packageName 2542 + " activity: " + filter.activity.className 2543 + " priority: " + filter.getPriority()); 2544 } 2545 // skip setup wizard; allow it to keep the high priority filter 2546 continue; 2547 } 2548 Slog.w(TAG, "Protected action; cap priority to 0;" 2549 + " package: " + filter.activity.info.packageName 2550 + " activity: " + filter.activity.className 2551 + " origPrio: " + filter.getPriority()); 2552 filter.setPriority(0); 2553 } 2554 } 2555 mDeferProtectedFilters = false; 2556 mProtectedFilters.clear(); 2557 2558 // Now that we know all of the shared libraries, update all clients to have 2559 // the correct library paths. 2560 updateAllSharedLibrariesLPw(); 2561 2562 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2563 // NOTE: We ignore potential failures here during a system scan (like 2564 // the rest of the commands above) because there's precious little we 2565 // can do about it. A settings error is reported, though. 2566 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2567 } 2568 2569 // Now that we know all the packages we are keeping, 2570 // read and update their last usage times. 2571 mPackageUsage.read(mPackages); 2572 mCompilerStats.read(); 2573 2574 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2575 SystemClock.uptimeMillis()); 2576 Slog.i(TAG, "Time to scan packages: " 2577 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2578 + " seconds"); 2579 2580 // If the platform SDK has changed since the last time we booted, 2581 // we need to re-grant app permission to catch any new ones that 2582 // appear. This is really a hack, and means that apps can in some 2583 // cases get permissions that the user didn't initially explicitly 2584 // allow... it would be nice to have some better way to handle 2585 // this situation. 2586 int updateFlags = UPDATE_PERMISSIONS_ALL; 2587 if (ver.sdkVersion != mSdkVersion) { 2588 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2589 + mSdkVersion + "; regranting permissions for internal storage"); 2590 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2591 } 2592 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2593 ver.sdkVersion = mSdkVersion; 2594 2595 // If this is the first boot or an update from pre-M, and it is a normal 2596 // boot, then we need to initialize the default preferred apps across 2597 // all defined users. 2598 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2599 for (UserInfo user : sUserManager.getUsers(true)) { 2600 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2601 applyFactoryDefaultBrowserLPw(user.id); 2602 primeDomainVerificationsLPw(user.id); 2603 } 2604 } 2605 2606 // Prepare storage for system user really early during boot, 2607 // since core system apps like SettingsProvider and SystemUI 2608 // can't wait for user to start 2609 final int storageFlags; 2610 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2611 storageFlags = StorageManager.FLAG_STORAGE_DE; 2612 } else { 2613 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2614 } 2615 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2616 storageFlags, true /* migrateAppData */); 2617 2618 // If this is first boot after an OTA, and a normal boot, then 2619 // we need to clear code cache directories. 2620 // Note that we do *not* clear the application profiles. These remain valid 2621 // across OTAs and are used to drive profile verification (post OTA) and 2622 // profile compilation (without waiting to collect a fresh set of profiles). 2623 if (mIsUpgrade && !onlyCore) { 2624 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2625 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2626 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2627 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2628 // No apps are running this early, so no need to freeze 2629 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2630 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2631 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2632 } 2633 } 2634 ver.fingerprint = Build.FINGERPRINT; 2635 } 2636 2637 checkDefaultBrowser(); 2638 2639 // clear only after permissions and other defaults have been updated 2640 mExistingSystemPackages.clear(); 2641 mPromoteSystemApps = false; 2642 2643 // All the changes are done during package scanning. 2644 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2645 2646 // can downgrade to reader 2647 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2648 mSettings.writeLPr(); 2649 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2650 2651 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2652 // early on (before the package manager declares itself as early) because other 2653 // components in the system server might ask for package contexts for these apps. 2654 // 2655 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2656 // (i.e, that the data partition is unavailable). 2657 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2658 long start = System.nanoTime(); 2659 List<PackageParser.Package> coreApps = new ArrayList<>(); 2660 for (PackageParser.Package pkg : mPackages.values()) { 2661 if (pkg.coreApp) { 2662 coreApps.add(pkg); 2663 } 2664 } 2665 2666 int[] stats = performDexOptUpgrade(coreApps, false, 2667 getCompilerFilterForReason(REASON_CORE_APP)); 2668 2669 final int elapsedTimeSeconds = 2670 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2671 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2672 2673 if (DEBUG_DEXOPT) { 2674 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2675 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2676 } 2677 2678 2679 // TODO: Should we log these stats to tron too ? 2680 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2681 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2682 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2683 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2684 } 2685 2686 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2687 SystemClock.uptimeMillis()); 2688 2689 if (!mOnlyCore) { 2690 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2691 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2692 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2693 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2694 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2695 mIntentFilterVerifierComponent); 2696 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2697 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2698 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2699 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2700 } else { 2701 mRequiredVerifierPackage = null; 2702 mRequiredInstallerPackage = null; 2703 mRequiredUninstallerPackage = null; 2704 mIntentFilterVerifierComponent = null; 2705 mIntentFilterVerifier = null; 2706 mServicesSystemSharedLibraryPackageName = null; 2707 mSharedSystemSharedLibraryPackageName = null; 2708 } 2709 2710 mInstallerService = new PackageInstallerService(context, this); 2711 2712 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2713 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2714 // both the installer and resolver must be present to enable ephemeral 2715 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2716 if (DEBUG_EPHEMERAL) { 2717 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2718 + " installer:" + ephemeralInstallerComponent); 2719 } 2720 mEphemeralResolverComponent = ephemeralResolverComponent; 2721 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2722 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2723 mEphemeralResolverConnection = 2724 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2725 } else { 2726 if (DEBUG_EPHEMERAL) { 2727 final String missingComponent = 2728 (ephemeralResolverComponent == null) 2729 ? (ephemeralInstallerComponent == null) 2730 ? "resolver and installer" 2731 : "resolver" 2732 : "installer"; 2733 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2734 } 2735 mEphemeralResolverComponent = null; 2736 mEphemeralInstallerComponent = null; 2737 mEphemeralResolverConnection = null; 2738 } 2739 2740 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2741 } // synchronized (mPackages) 2742 } // synchronized (mInstallLock) 2743 2744 // Now after opening every single application zip, make sure they 2745 // are all flushed. Not really needed, but keeps things nice and 2746 // tidy. 2747 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2748 Runtime.getRuntime().gc(); 2749 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2750 2751 // The initial scanning above does many calls into installd while 2752 // holding the mPackages lock, but we're mostly interested in yelling 2753 // once we have a booted system. 2754 mInstaller.setWarnIfHeld(mPackages); 2755 2756 // Expose private service for system components to use. 2757 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2758 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2759 } 2760 2761 @Override 2762 public boolean isFirstBoot() { 2763 return mFirstBoot; 2764 } 2765 2766 @Override 2767 public boolean isOnlyCoreApps() { 2768 return mOnlyCore; 2769 } 2770 2771 @Override 2772 public boolean isUpgrade() { 2773 return mIsUpgrade; 2774 } 2775 2776 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2777 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2778 2779 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2780 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2781 UserHandle.USER_SYSTEM); 2782 if (matches.size() == 1) { 2783 return matches.get(0).getComponentInfo().packageName; 2784 } else if (matches.size() == 0) { 2785 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2786 return null; 2787 } 2788 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2789 } 2790 2791 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2792 synchronized (mPackages) { 2793 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2794 if (libraryEntry == null) { 2795 throw new IllegalStateException("Missing required shared library:" + libraryName); 2796 } 2797 return libraryEntry.apk; 2798 } 2799 } 2800 2801 private @NonNull String getRequiredInstallerLPr() { 2802 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2803 intent.addCategory(Intent.CATEGORY_DEFAULT); 2804 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2805 2806 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2807 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2808 UserHandle.USER_SYSTEM); 2809 if (matches.size() == 1) { 2810 ResolveInfo resolveInfo = matches.get(0); 2811 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2812 throw new RuntimeException("The installer must be a privileged app"); 2813 } 2814 return matches.get(0).getComponentInfo().packageName; 2815 } else { 2816 throw new RuntimeException("There must be exactly one installer; found " + matches); 2817 } 2818 } 2819 2820 private @NonNull String getRequiredUninstallerLPr() { 2821 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2822 intent.addCategory(Intent.CATEGORY_DEFAULT); 2823 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2824 2825 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2826 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2827 UserHandle.USER_SYSTEM); 2828 if (resolveInfo == null || 2829 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2830 throw new RuntimeException("There must be exactly one uninstaller; found " 2831 + resolveInfo); 2832 } 2833 return resolveInfo.getComponentInfo().packageName; 2834 } 2835 2836 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2837 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2838 2839 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2840 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2841 UserHandle.USER_SYSTEM); 2842 ResolveInfo best = null; 2843 final int N = matches.size(); 2844 for (int i = 0; i < N; i++) { 2845 final ResolveInfo cur = matches.get(i); 2846 final String packageName = cur.getComponentInfo().packageName; 2847 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2848 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2849 continue; 2850 } 2851 2852 if (best == null || cur.priority > best.priority) { 2853 best = cur; 2854 } 2855 } 2856 2857 if (best != null) { 2858 return best.getComponentInfo().getComponentName(); 2859 } else { 2860 throw new RuntimeException("There must be at least one intent filter verifier"); 2861 } 2862 } 2863 2864 private @Nullable ComponentName getEphemeralResolverLPr() { 2865 final String[] packageArray = 2866 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2867 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2868 if (DEBUG_EPHEMERAL) { 2869 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2870 } 2871 return null; 2872 } 2873 2874 final int resolveFlags = 2875 MATCH_DIRECT_BOOT_AWARE 2876 | MATCH_DIRECT_BOOT_UNAWARE 2877 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2878 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2879 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2880 resolveFlags, UserHandle.USER_SYSTEM); 2881 2882 final int N = resolvers.size(); 2883 if (N == 0) { 2884 if (DEBUG_EPHEMERAL) { 2885 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2886 } 2887 return null; 2888 } 2889 2890 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2891 for (int i = 0; i < N; i++) { 2892 final ResolveInfo info = resolvers.get(i); 2893 2894 if (info.serviceInfo == null) { 2895 continue; 2896 } 2897 2898 final String packageName = info.serviceInfo.packageName; 2899 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2900 if (DEBUG_EPHEMERAL) { 2901 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2902 + " pkg: " + packageName + ", info:" + info); 2903 } 2904 continue; 2905 } 2906 2907 if (DEBUG_EPHEMERAL) { 2908 Slog.v(TAG, "Ephemeral resolver found;" 2909 + " pkg: " + packageName + ", info:" + info); 2910 } 2911 return new ComponentName(packageName, info.serviceInfo.name); 2912 } 2913 if (DEBUG_EPHEMERAL) { 2914 Slog.v(TAG, "Ephemeral resolver NOT found"); 2915 } 2916 return null; 2917 } 2918 2919 private @Nullable ComponentName getEphemeralInstallerLPr() { 2920 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2921 intent.addCategory(Intent.CATEGORY_DEFAULT); 2922 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2923 2924 final int resolveFlags = 2925 MATCH_DIRECT_BOOT_AWARE 2926 | MATCH_DIRECT_BOOT_UNAWARE 2927 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2928 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2929 resolveFlags, UserHandle.USER_SYSTEM); 2930 if (matches.size() == 0) { 2931 return null; 2932 } else if (matches.size() == 1) { 2933 return matches.get(0).getComponentInfo().getComponentName(); 2934 } else { 2935 throw new RuntimeException( 2936 "There must be at most one ephemeral installer; found " + matches); 2937 } 2938 } 2939 2940 private void primeDomainVerificationsLPw(int userId) { 2941 if (DEBUG_DOMAIN_VERIFICATION) { 2942 Slog.d(TAG, "Priming domain verifications in user " + userId); 2943 } 2944 2945 SystemConfig systemConfig = SystemConfig.getInstance(); 2946 ArraySet<String> packages = systemConfig.getLinkedApps(); 2947 2948 for (String packageName : packages) { 2949 PackageParser.Package pkg = mPackages.get(packageName); 2950 if (pkg != null) { 2951 if (!pkg.isSystemApp()) { 2952 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2953 continue; 2954 } 2955 2956 ArraySet<String> domains = null; 2957 for (PackageParser.Activity a : pkg.activities) { 2958 for (ActivityIntentInfo filter : a.intents) { 2959 if (hasValidDomains(filter)) { 2960 if (domains == null) { 2961 domains = new ArraySet<String>(); 2962 } 2963 domains.addAll(filter.getHostsList()); 2964 } 2965 } 2966 } 2967 2968 if (domains != null && domains.size() > 0) { 2969 if (DEBUG_DOMAIN_VERIFICATION) { 2970 Slog.v(TAG, " + " + packageName); 2971 } 2972 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2973 // state w.r.t. the formal app-linkage "no verification attempted" state; 2974 // and then 'always' in the per-user state actually used for intent resolution. 2975 final IntentFilterVerificationInfo ivi; 2976 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 2977 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2978 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2979 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2980 } else { 2981 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2982 + "' does not handle web links"); 2983 } 2984 } else { 2985 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2986 } 2987 } 2988 2989 scheduleWritePackageRestrictionsLocked(userId); 2990 scheduleWriteSettingsLocked(); 2991 } 2992 2993 private void applyFactoryDefaultBrowserLPw(int userId) { 2994 // The default browser app's package name is stored in a string resource, 2995 // with a product-specific overlay used for vendor customization. 2996 String browserPkg = mContext.getResources().getString( 2997 com.android.internal.R.string.default_browser); 2998 if (!TextUtils.isEmpty(browserPkg)) { 2999 // non-empty string => required to be a known package 3000 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3001 if (ps == null) { 3002 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3003 browserPkg = null; 3004 } else { 3005 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3006 } 3007 } 3008 3009 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3010 // default. If there's more than one, just leave everything alone. 3011 if (browserPkg == null) { 3012 calculateDefaultBrowserLPw(userId); 3013 } 3014 } 3015 3016 private void calculateDefaultBrowserLPw(int userId) { 3017 List<String> allBrowsers = resolveAllBrowserApps(userId); 3018 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3019 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3020 } 3021 3022 private List<String> resolveAllBrowserApps(int userId) { 3023 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3024 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3025 PackageManager.MATCH_ALL, userId); 3026 3027 final int count = list.size(); 3028 List<String> result = new ArrayList<String>(count); 3029 for (int i=0; i<count; i++) { 3030 ResolveInfo info = list.get(i); 3031 if (info.activityInfo == null 3032 || !info.handleAllWebDataURI 3033 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3034 || result.contains(info.activityInfo.packageName)) { 3035 continue; 3036 } 3037 result.add(info.activityInfo.packageName); 3038 } 3039 3040 return result; 3041 } 3042 3043 private boolean packageIsBrowser(String packageName, int userId) { 3044 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3045 PackageManager.MATCH_ALL, userId); 3046 final int N = list.size(); 3047 for (int i = 0; i < N; i++) { 3048 ResolveInfo info = list.get(i); 3049 if (packageName.equals(info.activityInfo.packageName)) { 3050 return true; 3051 } 3052 } 3053 return false; 3054 } 3055 3056 private void checkDefaultBrowser() { 3057 final int myUserId = UserHandle.myUserId(); 3058 final String packageName = getDefaultBrowserPackageName(myUserId); 3059 if (packageName != null) { 3060 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3061 if (info == null) { 3062 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3063 synchronized (mPackages) { 3064 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3065 } 3066 } 3067 } 3068 } 3069 3070 @Override 3071 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3072 throws RemoteException { 3073 try { 3074 return super.onTransact(code, data, reply, flags); 3075 } catch (RuntimeException e) { 3076 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3077 Slog.wtf(TAG, "Package Manager Crash", e); 3078 } 3079 throw e; 3080 } 3081 } 3082 3083 static int[] appendInts(int[] cur, int[] add) { 3084 if (add == null) return cur; 3085 if (cur == null) return add; 3086 final int N = add.length; 3087 for (int i=0; i<N; i++) { 3088 cur = appendInt(cur, add[i]); 3089 } 3090 return cur; 3091 } 3092 3093 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3094 if (!sUserManager.exists(userId)) return null; 3095 if (ps == null) { 3096 return null; 3097 } 3098 final PackageParser.Package p = ps.pkg; 3099 if (p == null) { 3100 return null; 3101 } 3102 3103 final PermissionsState permissionsState = ps.getPermissionsState(); 3104 3105 // Compute GIDs only if requested 3106 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3107 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3108 // Compute granted permissions only if package has requested permissions 3109 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3110 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3111 final PackageUserState state = ps.readUserState(userId); 3112 3113 return PackageParser.generatePackageInfo(p, gids, flags, 3114 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3115 } 3116 3117 @Override 3118 public void checkPackageStartable(String packageName, int userId) { 3119 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3120 3121 synchronized (mPackages) { 3122 final PackageSetting ps = mSettings.mPackages.get(packageName); 3123 if (ps == null) { 3124 throw new SecurityException("Package " + packageName + " was not found!"); 3125 } 3126 3127 if (!ps.getInstalled(userId)) { 3128 throw new SecurityException( 3129 "Package " + packageName + " was not installed for user " + userId + "!"); 3130 } 3131 3132 if (mSafeMode && !ps.isSystem()) { 3133 throw new SecurityException("Package " + packageName + " not a system app!"); 3134 } 3135 3136 if (mFrozenPackages.contains(packageName)) { 3137 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3138 } 3139 3140 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3141 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3142 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3143 } 3144 } 3145 } 3146 3147 @Override 3148 public boolean isPackageAvailable(String packageName, int userId) { 3149 if (!sUserManager.exists(userId)) return false; 3150 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3151 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3152 synchronized (mPackages) { 3153 PackageParser.Package p = mPackages.get(packageName); 3154 if (p != null) { 3155 final PackageSetting ps = (PackageSetting) p.mExtras; 3156 if (ps != null) { 3157 final PackageUserState state = ps.readUserState(userId); 3158 if (state != null) { 3159 return PackageParser.isAvailable(state); 3160 } 3161 } 3162 } 3163 } 3164 return false; 3165 } 3166 3167 @Override 3168 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3169 if (!sUserManager.exists(userId)) return null; 3170 flags = updateFlagsForPackage(flags, userId, packageName); 3171 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3172 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3173 // reader 3174 synchronized (mPackages) { 3175 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3176 PackageParser.Package p = null; 3177 if (matchFactoryOnly) { 3178 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3179 if (ps != null) { 3180 return generatePackageInfo(ps, flags, userId); 3181 } 3182 } 3183 if (p == null) { 3184 p = mPackages.get(packageName); 3185 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3186 return null; 3187 } 3188 } 3189 if (DEBUG_PACKAGE_INFO) 3190 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3191 if (p != null) { 3192 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3193 } 3194 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3195 final PackageSetting ps = mSettings.mPackages.get(packageName); 3196 return generatePackageInfo(ps, flags, userId); 3197 } 3198 } 3199 return null; 3200 } 3201 3202 @Override 3203 public String[] currentToCanonicalPackageNames(String[] names) { 3204 String[] out = new String[names.length]; 3205 // reader 3206 synchronized (mPackages) { 3207 for (int i=names.length-1; i>=0; i--) { 3208 PackageSetting ps = mSettings.mPackages.get(names[i]); 3209 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3210 } 3211 } 3212 return out; 3213 } 3214 3215 @Override 3216 public String[] canonicalToCurrentPackageNames(String[] names) { 3217 String[] out = new String[names.length]; 3218 // reader 3219 synchronized (mPackages) { 3220 for (int i=names.length-1; i>=0; i--) { 3221 String cur = mSettings.getRenamedPackageLPr(names[i]); 3222 out[i] = cur != null ? cur : names[i]; 3223 } 3224 } 3225 return out; 3226 } 3227 3228 @Override 3229 public int getPackageUid(String packageName, int flags, int userId) { 3230 if (!sUserManager.exists(userId)) return -1; 3231 flags = updateFlagsForPackage(flags, userId, packageName); 3232 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3233 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3234 3235 // reader 3236 synchronized (mPackages) { 3237 final PackageParser.Package p = mPackages.get(packageName); 3238 if (p != null && p.isMatch(flags)) { 3239 return UserHandle.getUid(userId, p.applicationInfo.uid); 3240 } 3241 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3242 final PackageSetting ps = mSettings.mPackages.get(packageName); 3243 if (ps != null && ps.isMatch(flags)) { 3244 return UserHandle.getUid(userId, ps.appId); 3245 } 3246 } 3247 } 3248 3249 return -1; 3250 } 3251 3252 @Override 3253 public int[] getPackageGids(String packageName, int flags, int userId) { 3254 if (!sUserManager.exists(userId)) return null; 3255 flags = updateFlagsForPackage(flags, userId, packageName); 3256 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3257 false /* requireFullPermission */, false /* checkShell */, 3258 "getPackageGids"); 3259 3260 // reader 3261 synchronized (mPackages) { 3262 final PackageParser.Package p = mPackages.get(packageName); 3263 if (p != null && p.isMatch(flags)) { 3264 PackageSetting ps = (PackageSetting) p.mExtras; 3265 return ps.getPermissionsState().computeGids(userId); 3266 } 3267 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3268 final PackageSetting ps = mSettings.mPackages.get(packageName); 3269 if (ps != null && ps.isMatch(flags)) { 3270 return ps.getPermissionsState().computeGids(userId); 3271 } 3272 } 3273 } 3274 3275 return null; 3276 } 3277 3278 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3279 if (bp.perm != null) { 3280 return PackageParser.generatePermissionInfo(bp.perm, flags); 3281 } 3282 PermissionInfo pi = new PermissionInfo(); 3283 pi.name = bp.name; 3284 pi.packageName = bp.sourcePackage; 3285 pi.nonLocalizedLabel = bp.name; 3286 pi.protectionLevel = bp.protectionLevel; 3287 return pi; 3288 } 3289 3290 @Override 3291 public PermissionInfo getPermissionInfo(String name, int flags) { 3292 // reader 3293 synchronized (mPackages) { 3294 final BasePermission p = mSettings.mPermissions.get(name); 3295 if (p != null) { 3296 return generatePermissionInfo(p, flags); 3297 } 3298 return null; 3299 } 3300 } 3301 3302 @Override 3303 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3304 int flags) { 3305 // reader 3306 synchronized (mPackages) { 3307 if (group != null && !mPermissionGroups.containsKey(group)) { 3308 // This is thrown as NameNotFoundException 3309 return null; 3310 } 3311 3312 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3313 for (BasePermission p : mSettings.mPermissions.values()) { 3314 if (group == null) { 3315 if (p.perm == null || p.perm.info.group == null) { 3316 out.add(generatePermissionInfo(p, flags)); 3317 } 3318 } else { 3319 if (p.perm != null && group.equals(p.perm.info.group)) { 3320 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3321 } 3322 } 3323 } 3324 return new ParceledListSlice<>(out); 3325 } 3326 } 3327 3328 @Override 3329 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3330 // reader 3331 synchronized (mPackages) { 3332 return PackageParser.generatePermissionGroupInfo( 3333 mPermissionGroups.get(name), flags); 3334 } 3335 } 3336 3337 @Override 3338 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3339 // reader 3340 synchronized (mPackages) { 3341 final int N = mPermissionGroups.size(); 3342 ArrayList<PermissionGroupInfo> out 3343 = new ArrayList<PermissionGroupInfo>(N); 3344 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3345 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3346 } 3347 return new ParceledListSlice<>(out); 3348 } 3349 } 3350 3351 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3352 int userId) { 3353 if (!sUserManager.exists(userId)) return null; 3354 PackageSetting ps = mSettings.mPackages.get(packageName); 3355 if (ps != null) { 3356 if (ps.pkg == null) { 3357 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3358 if (pInfo != null) { 3359 return pInfo.applicationInfo; 3360 } 3361 return null; 3362 } 3363 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3364 ps.readUserState(userId), userId); 3365 } 3366 return null; 3367 } 3368 3369 @Override 3370 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3371 if (!sUserManager.exists(userId)) return null; 3372 flags = updateFlagsForApplication(flags, userId, packageName); 3373 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3374 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3375 // writer 3376 synchronized (mPackages) { 3377 PackageParser.Package p = mPackages.get(packageName); 3378 if (DEBUG_PACKAGE_INFO) Log.v( 3379 TAG, "getApplicationInfo " + packageName 3380 + ": " + p); 3381 if (p != null) { 3382 PackageSetting ps = mSettings.mPackages.get(packageName); 3383 if (ps == null) return null; 3384 // Note: isEnabledLP() does not apply here - always return info 3385 return PackageParser.generateApplicationInfo( 3386 p, flags, ps.readUserState(userId), userId); 3387 } 3388 if ("android".equals(packageName)||"system".equals(packageName)) { 3389 return mAndroidApplication; 3390 } 3391 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3392 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3393 } 3394 } 3395 return null; 3396 } 3397 3398 @Override 3399 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3400 final IPackageDataObserver observer) { 3401 mContext.enforceCallingOrSelfPermission( 3402 android.Manifest.permission.CLEAR_APP_CACHE, null); 3403 // Queue up an async operation since clearing cache may take a little while. 3404 mHandler.post(new Runnable() { 3405 public void run() { 3406 mHandler.removeCallbacks(this); 3407 boolean success = true; 3408 synchronized (mInstallLock) { 3409 try { 3410 mInstaller.freeCache(volumeUuid, freeStorageSize); 3411 } catch (InstallerException e) { 3412 Slog.w(TAG, "Couldn't clear application caches: " + e); 3413 success = false; 3414 } 3415 } 3416 if (observer != null) { 3417 try { 3418 observer.onRemoveCompleted(null, success); 3419 } catch (RemoteException e) { 3420 Slog.w(TAG, "RemoveException when invoking call back"); 3421 } 3422 } 3423 } 3424 }); 3425 } 3426 3427 @Override 3428 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3429 final IntentSender pi) { 3430 mContext.enforceCallingOrSelfPermission( 3431 android.Manifest.permission.CLEAR_APP_CACHE, null); 3432 // Queue up an async operation since clearing cache may take a little while. 3433 mHandler.post(new Runnable() { 3434 public void run() { 3435 mHandler.removeCallbacks(this); 3436 boolean success = true; 3437 synchronized (mInstallLock) { 3438 try { 3439 mInstaller.freeCache(volumeUuid, freeStorageSize); 3440 } catch (InstallerException e) { 3441 Slog.w(TAG, "Couldn't clear application caches: " + e); 3442 success = false; 3443 } 3444 } 3445 if(pi != null) { 3446 try { 3447 // Callback via pending intent 3448 int code = success ? 1 : 0; 3449 pi.sendIntent(null, code, null, 3450 null, null); 3451 } catch (SendIntentException e1) { 3452 Slog.i(TAG, "Failed to send pending intent"); 3453 } 3454 } 3455 } 3456 }); 3457 } 3458 3459 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3460 synchronized (mInstallLock) { 3461 try { 3462 mInstaller.freeCache(volumeUuid, freeStorageSize); 3463 } catch (InstallerException e) { 3464 throw new IOException("Failed to free enough space", e); 3465 } 3466 } 3467 } 3468 3469 /** 3470 * Update given flags based on encryption status of current user. 3471 */ 3472 private int updateFlags(int flags, int userId) { 3473 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3474 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3475 // Caller expressed an explicit opinion about what encryption 3476 // aware/unaware components they want to see, so fall through and 3477 // give them what they want 3478 } else { 3479 // Caller expressed no opinion, so match based on user state 3480 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3481 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3482 } else { 3483 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3484 } 3485 } 3486 return flags; 3487 } 3488 3489 private UserManagerInternal getUserManagerInternal() { 3490 if (mUserManagerInternal == null) { 3491 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3492 } 3493 return mUserManagerInternal; 3494 } 3495 3496 /** 3497 * Update given flags when being used to request {@link PackageInfo}. 3498 */ 3499 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3500 boolean triaged = true; 3501 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3502 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3503 // Caller is asking for component details, so they'd better be 3504 // asking for specific encryption matching behavior, or be triaged 3505 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3506 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3507 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3508 triaged = false; 3509 } 3510 } 3511 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3512 | PackageManager.MATCH_SYSTEM_ONLY 3513 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3514 triaged = false; 3515 } 3516 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3517 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3518 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3519 } 3520 return updateFlags(flags, userId); 3521 } 3522 3523 /** 3524 * Update given flags when being used to request {@link ApplicationInfo}. 3525 */ 3526 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3527 return updateFlagsForPackage(flags, userId, cookie); 3528 } 3529 3530 /** 3531 * Update given flags when being used to request {@link ComponentInfo}. 3532 */ 3533 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3534 if (cookie instanceof Intent) { 3535 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3536 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3537 } 3538 } 3539 3540 boolean triaged = true; 3541 // Caller is asking for component details, so they'd better be 3542 // asking for specific encryption matching behavior, or be triaged 3543 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3544 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3545 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3546 triaged = false; 3547 } 3548 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3549 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3550 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3551 } 3552 3553 return updateFlags(flags, userId); 3554 } 3555 3556 /** 3557 * Update given flags when being used to request {@link ResolveInfo}. 3558 */ 3559 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3560 // Safe mode means we shouldn't match any third-party components 3561 if (mSafeMode) { 3562 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3563 } 3564 3565 return updateFlagsForComponent(flags, userId, cookie); 3566 } 3567 3568 @Override 3569 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3570 if (!sUserManager.exists(userId)) return null; 3571 flags = updateFlagsForComponent(flags, userId, component); 3572 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3573 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3574 synchronized (mPackages) { 3575 PackageParser.Activity a = mActivities.mActivities.get(component); 3576 3577 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3578 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3579 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3580 if (ps == null) return null; 3581 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3582 userId); 3583 } 3584 if (mResolveComponentName.equals(component)) { 3585 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3586 new PackageUserState(), userId); 3587 } 3588 } 3589 return null; 3590 } 3591 3592 @Override 3593 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3594 String resolvedType) { 3595 synchronized (mPackages) { 3596 if (component.equals(mResolveComponentName)) { 3597 // The resolver supports EVERYTHING! 3598 return true; 3599 } 3600 PackageParser.Activity a = mActivities.mActivities.get(component); 3601 if (a == null) { 3602 return false; 3603 } 3604 for (int i=0; i<a.intents.size(); i++) { 3605 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3606 intent.getData(), intent.getCategories(), TAG) >= 0) { 3607 return true; 3608 } 3609 } 3610 return false; 3611 } 3612 } 3613 3614 @Override 3615 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3616 if (!sUserManager.exists(userId)) return null; 3617 flags = updateFlagsForComponent(flags, userId, component); 3618 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3619 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3620 synchronized (mPackages) { 3621 PackageParser.Activity a = mReceivers.mActivities.get(component); 3622 if (DEBUG_PACKAGE_INFO) Log.v( 3623 TAG, "getReceiverInfo " + component + ": " + a); 3624 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3625 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3626 if (ps == null) return null; 3627 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3628 userId); 3629 } 3630 } 3631 return null; 3632 } 3633 3634 @Override 3635 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3636 if (!sUserManager.exists(userId)) return null; 3637 flags = updateFlagsForComponent(flags, userId, component); 3638 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3639 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3640 synchronized (mPackages) { 3641 PackageParser.Service s = mServices.mServices.get(component); 3642 if (DEBUG_PACKAGE_INFO) Log.v( 3643 TAG, "getServiceInfo " + component + ": " + s); 3644 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3645 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3646 if (ps == null) return null; 3647 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3648 userId); 3649 } 3650 } 3651 return null; 3652 } 3653 3654 @Override 3655 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3656 if (!sUserManager.exists(userId)) return null; 3657 flags = updateFlagsForComponent(flags, userId, component); 3658 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3659 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3660 synchronized (mPackages) { 3661 PackageParser.Provider p = mProviders.mProviders.get(component); 3662 if (DEBUG_PACKAGE_INFO) Log.v( 3663 TAG, "getProviderInfo " + component + ": " + p); 3664 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3665 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3666 if (ps == null) return null; 3667 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3668 userId); 3669 } 3670 } 3671 return null; 3672 } 3673 3674 @Override 3675 public String[] getSystemSharedLibraryNames() { 3676 Set<String> libSet; 3677 synchronized (mPackages) { 3678 libSet = mSharedLibraries.keySet(); 3679 int size = libSet.size(); 3680 if (size > 0) { 3681 String[] libs = new String[size]; 3682 libSet.toArray(libs); 3683 return libs; 3684 } 3685 } 3686 return null; 3687 } 3688 3689 @Override 3690 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3691 synchronized (mPackages) { 3692 return mServicesSystemSharedLibraryPackageName; 3693 } 3694 } 3695 3696 @Override 3697 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3698 synchronized (mPackages) { 3699 return mSharedSystemSharedLibraryPackageName; 3700 } 3701 } 3702 3703 @Override 3704 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3705 synchronized (mPackages) { 3706 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3707 3708 final FeatureInfo fi = new FeatureInfo(); 3709 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3710 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3711 res.add(fi); 3712 3713 return new ParceledListSlice<>(res); 3714 } 3715 } 3716 3717 @Override 3718 public boolean hasSystemFeature(String name, int version) { 3719 synchronized (mPackages) { 3720 final FeatureInfo feat = mAvailableFeatures.get(name); 3721 if (feat == null) { 3722 return false; 3723 } else { 3724 return feat.version >= version; 3725 } 3726 } 3727 } 3728 3729 @Override 3730 public int checkPermission(String permName, String pkgName, int userId) { 3731 if (!sUserManager.exists(userId)) { 3732 return PackageManager.PERMISSION_DENIED; 3733 } 3734 3735 synchronized (mPackages) { 3736 final PackageParser.Package p = mPackages.get(pkgName); 3737 if (p != null && p.mExtras != null) { 3738 final PackageSetting ps = (PackageSetting) p.mExtras; 3739 final PermissionsState permissionsState = ps.getPermissionsState(); 3740 if (permissionsState.hasPermission(permName, userId)) { 3741 return PackageManager.PERMISSION_GRANTED; 3742 } 3743 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3744 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3745 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3746 return PackageManager.PERMISSION_GRANTED; 3747 } 3748 } 3749 } 3750 3751 return PackageManager.PERMISSION_DENIED; 3752 } 3753 3754 @Override 3755 public int checkUidPermission(String permName, int uid) { 3756 final int userId = UserHandle.getUserId(uid); 3757 3758 if (!sUserManager.exists(userId)) { 3759 return PackageManager.PERMISSION_DENIED; 3760 } 3761 3762 synchronized (mPackages) { 3763 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3764 if (obj != null) { 3765 final SettingBase ps = (SettingBase) obj; 3766 final PermissionsState permissionsState = ps.getPermissionsState(); 3767 if (permissionsState.hasPermission(permName, userId)) { 3768 return PackageManager.PERMISSION_GRANTED; 3769 } 3770 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3771 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3772 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3773 return PackageManager.PERMISSION_GRANTED; 3774 } 3775 } else { 3776 ArraySet<String> perms = mSystemPermissions.get(uid); 3777 if (perms != null) { 3778 if (perms.contains(permName)) { 3779 return PackageManager.PERMISSION_GRANTED; 3780 } 3781 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3782 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3783 return PackageManager.PERMISSION_GRANTED; 3784 } 3785 } 3786 } 3787 } 3788 3789 return PackageManager.PERMISSION_DENIED; 3790 } 3791 3792 @Override 3793 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3794 if (UserHandle.getCallingUserId() != userId) { 3795 mContext.enforceCallingPermission( 3796 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3797 "isPermissionRevokedByPolicy for user " + userId); 3798 } 3799 3800 if (checkPermission(permission, packageName, userId) 3801 == PackageManager.PERMISSION_GRANTED) { 3802 return false; 3803 } 3804 3805 final long identity = Binder.clearCallingIdentity(); 3806 try { 3807 final int flags = getPermissionFlags(permission, packageName, userId); 3808 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3809 } finally { 3810 Binder.restoreCallingIdentity(identity); 3811 } 3812 } 3813 3814 @Override 3815 public String getPermissionControllerPackageName() { 3816 synchronized (mPackages) { 3817 return mRequiredInstallerPackage; 3818 } 3819 } 3820 3821 /** 3822 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3823 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3824 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3825 * @param message the message to log on security exception 3826 */ 3827 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3828 boolean checkShell, String message) { 3829 if (userId < 0) { 3830 throw new IllegalArgumentException("Invalid userId " + userId); 3831 } 3832 if (checkShell) { 3833 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3834 } 3835 if (userId == UserHandle.getUserId(callingUid)) return; 3836 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3837 if (requireFullPermission) { 3838 mContext.enforceCallingOrSelfPermission( 3839 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3840 } else { 3841 try { 3842 mContext.enforceCallingOrSelfPermission( 3843 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3844 } catch (SecurityException se) { 3845 mContext.enforceCallingOrSelfPermission( 3846 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3847 } 3848 } 3849 } 3850 } 3851 3852 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3853 if (callingUid == Process.SHELL_UID) { 3854 if (userHandle >= 0 3855 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3856 throw new SecurityException("Shell does not have permission to access user " 3857 + userHandle); 3858 } else if (userHandle < 0) { 3859 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3860 + Debug.getCallers(3)); 3861 } 3862 } 3863 } 3864 3865 private BasePermission findPermissionTreeLP(String permName) { 3866 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3867 if (permName.startsWith(bp.name) && 3868 permName.length() > bp.name.length() && 3869 permName.charAt(bp.name.length()) == '.') { 3870 return bp; 3871 } 3872 } 3873 return null; 3874 } 3875 3876 private BasePermission checkPermissionTreeLP(String permName) { 3877 if (permName != null) { 3878 BasePermission bp = findPermissionTreeLP(permName); 3879 if (bp != null) { 3880 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3881 return bp; 3882 } 3883 throw new SecurityException("Calling uid " 3884 + Binder.getCallingUid() 3885 + " is not allowed to add to permission tree " 3886 + bp.name + " owned by uid " + bp.uid); 3887 } 3888 } 3889 throw new SecurityException("No permission tree found for " + permName); 3890 } 3891 3892 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3893 if (s1 == null) { 3894 return s2 == null; 3895 } 3896 if (s2 == null) { 3897 return false; 3898 } 3899 if (s1.getClass() != s2.getClass()) { 3900 return false; 3901 } 3902 return s1.equals(s2); 3903 } 3904 3905 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3906 if (pi1.icon != pi2.icon) return false; 3907 if (pi1.logo != pi2.logo) return false; 3908 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3909 if (!compareStrings(pi1.name, pi2.name)) return false; 3910 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3911 // We'll take care of setting this one. 3912 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3913 // These are not currently stored in settings. 3914 //if (!compareStrings(pi1.group, pi2.group)) return false; 3915 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3916 //if (pi1.labelRes != pi2.labelRes) return false; 3917 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3918 return true; 3919 } 3920 3921 int permissionInfoFootprint(PermissionInfo info) { 3922 int size = info.name.length(); 3923 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3924 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3925 return size; 3926 } 3927 3928 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3929 int size = 0; 3930 for (BasePermission perm : mSettings.mPermissions.values()) { 3931 if (perm.uid == tree.uid) { 3932 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3933 } 3934 } 3935 return size; 3936 } 3937 3938 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3939 // We calculate the max size of permissions defined by this uid and throw 3940 // if that plus the size of 'info' would exceed our stated maximum. 3941 if (tree.uid != Process.SYSTEM_UID) { 3942 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3943 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3944 throw new SecurityException("Permission tree size cap exceeded"); 3945 } 3946 } 3947 } 3948 3949 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3950 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3951 throw new SecurityException("Label must be specified in permission"); 3952 } 3953 BasePermission tree = checkPermissionTreeLP(info.name); 3954 BasePermission bp = mSettings.mPermissions.get(info.name); 3955 boolean added = bp == null; 3956 boolean changed = true; 3957 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3958 if (added) { 3959 enforcePermissionCapLocked(info, tree); 3960 bp = new BasePermission(info.name, tree.sourcePackage, 3961 BasePermission.TYPE_DYNAMIC); 3962 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3963 throw new SecurityException( 3964 "Not allowed to modify non-dynamic permission " 3965 + info.name); 3966 } else { 3967 if (bp.protectionLevel == fixedLevel 3968 && bp.perm.owner.equals(tree.perm.owner) 3969 && bp.uid == tree.uid 3970 && comparePermissionInfos(bp.perm.info, info)) { 3971 changed = false; 3972 } 3973 } 3974 bp.protectionLevel = fixedLevel; 3975 info = new PermissionInfo(info); 3976 info.protectionLevel = fixedLevel; 3977 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3978 bp.perm.info.packageName = tree.perm.info.packageName; 3979 bp.uid = tree.uid; 3980 if (added) { 3981 mSettings.mPermissions.put(info.name, bp); 3982 } 3983 if (changed) { 3984 if (!async) { 3985 mSettings.writeLPr(); 3986 } else { 3987 scheduleWriteSettingsLocked(); 3988 } 3989 } 3990 return added; 3991 } 3992 3993 @Override 3994 public boolean addPermission(PermissionInfo info) { 3995 synchronized (mPackages) { 3996 return addPermissionLocked(info, false); 3997 } 3998 } 3999 4000 @Override 4001 public boolean addPermissionAsync(PermissionInfo info) { 4002 synchronized (mPackages) { 4003 return addPermissionLocked(info, true); 4004 } 4005 } 4006 4007 @Override 4008 public void removePermission(String name) { 4009 synchronized (mPackages) { 4010 checkPermissionTreeLP(name); 4011 BasePermission bp = mSettings.mPermissions.get(name); 4012 if (bp != null) { 4013 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4014 throw new SecurityException( 4015 "Not allowed to modify non-dynamic permission " 4016 + name); 4017 } 4018 mSettings.mPermissions.remove(name); 4019 mSettings.writeLPr(); 4020 } 4021 } 4022 } 4023 4024 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4025 BasePermission bp) { 4026 int index = pkg.requestedPermissions.indexOf(bp.name); 4027 if (index == -1) { 4028 throw new SecurityException("Package " + pkg.packageName 4029 + " has not requested permission " + bp.name); 4030 } 4031 if (!bp.isRuntime() && !bp.isDevelopment()) { 4032 throw new SecurityException("Permission " + bp.name 4033 + " is not a changeable permission type"); 4034 } 4035 } 4036 4037 @Override 4038 public void grantRuntimePermission(String packageName, String name, final int userId) { 4039 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4040 } 4041 4042 private void grantRuntimePermission(String packageName, String name, final int userId, 4043 boolean overridePolicy) { 4044 if (!sUserManager.exists(userId)) { 4045 Log.e(TAG, "No such user:" + userId); 4046 return; 4047 } 4048 4049 mContext.enforceCallingOrSelfPermission( 4050 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4051 "grantRuntimePermission"); 4052 4053 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4054 true /* requireFullPermission */, true /* checkShell */, 4055 "grantRuntimePermission"); 4056 4057 final int uid; 4058 final SettingBase sb; 4059 4060 synchronized (mPackages) { 4061 final PackageParser.Package pkg = mPackages.get(packageName); 4062 if (pkg == null) { 4063 throw new IllegalArgumentException("Unknown package: " + packageName); 4064 } 4065 4066 final BasePermission bp = mSettings.mPermissions.get(name); 4067 if (bp == null) { 4068 throw new IllegalArgumentException("Unknown permission: " + name); 4069 } 4070 4071 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4072 4073 // If a permission review is required for legacy apps we represent 4074 // their permissions as always granted runtime ones since we need 4075 // to keep the review required permission flag per user while an 4076 // install permission's state is shared across all users. 4077 if (mPermissionReviewRequired 4078 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4079 && bp.isRuntime()) { 4080 return; 4081 } 4082 4083 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4084 sb = (SettingBase) pkg.mExtras; 4085 if (sb == null) { 4086 throw new IllegalArgumentException("Unknown package: " + packageName); 4087 } 4088 4089 final PermissionsState permissionsState = sb.getPermissionsState(); 4090 4091 final int flags = permissionsState.getPermissionFlags(name, userId); 4092 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4093 throw new SecurityException("Cannot grant system fixed permission " 4094 + name + " for package " + packageName); 4095 } 4096 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4097 throw new SecurityException("Cannot grant policy fixed permission " 4098 + name + " for package " + packageName); 4099 } 4100 4101 if (bp.isDevelopment()) { 4102 // Development permissions must be handled specially, since they are not 4103 // normal runtime permissions. For now they apply to all users. 4104 if (permissionsState.grantInstallPermission(bp) != 4105 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4106 scheduleWriteSettingsLocked(); 4107 } 4108 return; 4109 } 4110 4111 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 4112 throw new SecurityException("Cannot grant non-ephemeral permission" 4113 + name + " for package " + packageName); 4114 } 4115 4116 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4117 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4118 return; 4119 } 4120 4121 final int result = permissionsState.grantRuntimePermission(bp, userId); 4122 switch (result) { 4123 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4124 return; 4125 } 4126 4127 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4128 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4129 mHandler.post(new Runnable() { 4130 @Override 4131 public void run() { 4132 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4133 } 4134 }); 4135 } 4136 break; 4137 } 4138 4139 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4140 4141 // Not critical if that is lost - app has to request again. 4142 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4143 } 4144 4145 // Only need to do this if user is initialized. Otherwise it's a new user 4146 // and there are no processes running as the user yet and there's no need 4147 // to make an expensive call to remount processes for the changed permissions. 4148 if (READ_EXTERNAL_STORAGE.equals(name) 4149 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4150 final long token = Binder.clearCallingIdentity(); 4151 try { 4152 if (sUserManager.isInitialized(userId)) { 4153 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4154 StorageManagerInternal.class); 4155 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4156 } 4157 } finally { 4158 Binder.restoreCallingIdentity(token); 4159 } 4160 } 4161 } 4162 4163 @Override 4164 public void revokeRuntimePermission(String packageName, String name, int userId) { 4165 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4166 } 4167 4168 private void revokeRuntimePermission(String packageName, String name, int userId, 4169 boolean overridePolicy) { 4170 if (!sUserManager.exists(userId)) { 4171 Log.e(TAG, "No such user:" + userId); 4172 return; 4173 } 4174 4175 mContext.enforceCallingOrSelfPermission( 4176 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4177 "revokeRuntimePermission"); 4178 4179 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4180 true /* requireFullPermission */, true /* checkShell */, 4181 "revokeRuntimePermission"); 4182 4183 final int appId; 4184 4185 synchronized (mPackages) { 4186 final PackageParser.Package pkg = mPackages.get(packageName); 4187 if (pkg == null) { 4188 throw new IllegalArgumentException("Unknown package: " + packageName); 4189 } 4190 4191 final BasePermission bp = mSettings.mPermissions.get(name); 4192 if (bp == null) { 4193 throw new IllegalArgumentException("Unknown permission: " + name); 4194 } 4195 4196 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4197 4198 // If a permission review is required for legacy apps we represent 4199 // their permissions as always granted runtime ones since we need 4200 // to keep the review required permission flag per user while an 4201 // install permission's state is shared across all users. 4202 if (mPermissionReviewRequired 4203 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4204 && bp.isRuntime()) { 4205 return; 4206 } 4207 4208 SettingBase sb = (SettingBase) pkg.mExtras; 4209 if (sb == null) { 4210 throw new IllegalArgumentException("Unknown package: " + packageName); 4211 } 4212 4213 final PermissionsState permissionsState = sb.getPermissionsState(); 4214 4215 final int flags = permissionsState.getPermissionFlags(name, userId); 4216 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4217 throw new SecurityException("Cannot revoke system fixed permission " 4218 + name + " for package " + packageName); 4219 } 4220 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4221 throw new SecurityException("Cannot revoke policy fixed permission " 4222 + name + " for package " + packageName); 4223 } 4224 4225 if (bp.isDevelopment()) { 4226 // Development permissions must be handled specially, since they are not 4227 // normal runtime permissions. For now they apply to all users. 4228 if (permissionsState.revokeInstallPermission(bp) != 4229 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4230 scheduleWriteSettingsLocked(); 4231 } 4232 return; 4233 } 4234 4235 if (permissionsState.revokeRuntimePermission(bp, userId) == 4236 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4237 return; 4238 } 4239 4240 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4241 4242 // Critical, after this call app should never have the permission. 4243 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4244 4245 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4246 } 4247 4248 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4249 } 4250 4251 @Override 4252 public void resetRuntimePermissions() { 4253 mContext.enforceCallingOrSelfPermission( 4254 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4255 "revokeRuntimePermission"); 4256 4257 int callingUid = Binder.getCallingUid(); 4258 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4259 mContext.enforceCallingOrSelfPermission( 4260 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4261 "resetRuntimePermissions"); 4262 } 4263 4264 synchronized (mPackages) { 4265 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4266 for (int userId : UserManagerService.getInstance().getUserIds()) { 4267 final int packageCount = mPackages.size(); 4268 for (int i = 0; i < packageCount; i++) { 4269 PackageParser.Package pkg = mPackages.valueAt(i); 4270 if (!(pkg.mExtras instanceof PackageSetting)) { 4271 continue; 4272 } 4273 PackageSetting ps = (PackageSetting) pkg.mExtras; 4274 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4275 } 4276 } 4277 } 4278 } 4279 4280 @Override 4281 public int getPermissionFlags(String name, String packageName, int userId) { 4282 if (!sUserManager.exists(userId)) { 4283 return 0; 4284 } 4285 4286 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4287 4288 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4289 true /* requireFullPermission */, false /* checkShell */, 4290 "getPermissionFlags"); 4291 4292 synchronized (mPackages) { 4293 final PackageParser.Package pkg = mPackages.get(packageName); 4294 if (pkg == null) { 4295 return 0; 4296 } 4297 4298 final BasePermission bp = mSettings.mPermissions.get(name); 4299 if (bp == null) { 4300 return 0; 4301 } 4302 4303 SettingBase sb = (SettingBase) pkg.mExtras; 4304 if (sb == null) { 4305 return 0; 4306 } 4307 4308 PermissionsState permissionsState = sb.getPermissionsState(); 4309 return permissionsState.getPermissionFlags(name, userId); 4310 } 4311 } 4312 4313 @Override 4314 public void updatePermissionFlags(String name, String packageName, int flagMask, 4315 int flagValues, int userId) { 4316 if (!sUserManager.exists(userId)) { 4317 return; 4318 } 4319 4320 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4321 4322 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4323 true /* requireFullPermission */, true /* checkShell */, 4324 "updatePermissionFlags"); 4325 4326 // Only the system can change these flags and nothing else. 4327 if (getCallingUid() != Process.SYSTEM_UID) { 4328 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4329 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4330 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4331 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4332 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4333 } 4334 4335 synchronized (mPackages) { 4336 final PackageParser.Package pkg = mPackages.get(packageName); 4337 if (pkg == null) { 4338 throw new IllegalArgumentException("Unknown package: " + packageName); 4339 } 4340 4341 final BasePermission bp = mSettings.mPermissions.get(name); 4342 if (bp == null) { 4343 throw new IllegalArgumentException("Unknown permission: " + name); 4344 } 4345 4346 SettingBase sb = (SettingBase) pkg.mExtras; 4347 if (sb == null) { 4348 throw new IllegalArgumentException("Unknown package: " + packageName); 4349 } 4350 4351 PermissionsState permissionsState = sb.getPermissionsState(); 4352 4353 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4354 4355 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4356 // Install and runtime permissions are stored in different places, 4357 // so figure out what permission changed and persist the change. 4358 if (permissionsState.getInstallPermissionState(name) != null) { 4359 scheduleWriteSettingsLocked(); 4360 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4361 || hadState) { 4362 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4363 } 4364 } 4365 } 4366 } 4367 4368 /** 4369 * Update the permission flags for all packages and runtime permissions of a user in order 4370 * to allow device or profile owner to remove POLICY_FIXED. 4371 */ 4372 @Override 4373 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4374 if (!sUserManager.exists(userId)) { 4375 return; 4376 } 4377 4378 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4379 4380 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4381 true /* requireFullPermission */, true /* checkShell */, 4382 "updatePermissionFlagsForAllApps"); 4383 4384 // Only the system can change system fixed flags. 4385 if (getCallingUid() != Process.SYSTEM_UID) { 4386 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4387 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4388 } 4389 4390 synchronized (mPackages) { 4391 boolean changed = false; 4392 final int packageCount = mPackages.size(); 4393 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4394 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4395 SettingBase sb = (SettingBase) pkg.mExtras; 4396 if (sb == null) { 4397 continue; 4398 } 4399 PermissionsState permissionsState = sb.getPermissionsState(); 4400 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4401 userId, flagMask, flagValues); 4402 } 4403 if (changed) { 4404 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4405 } 4406 } 4407 } 4408 4409 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4410 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4411 != PackageManager.PERMISSION_GRANTED 4412 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4413 != PackageManager.PERMISSION_GRANTED) { 4414 throw new SecurityException(message + " requires " 4415 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4416 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4417 } 4418 } 4419 4420 @Override 4421 public boolean shouldShowRequestPermissionRationale(String permissionName, 4422 String packageName, int userId) { 4423 if (UserHandle.getCallingUserId() != userId) { 4424 mContext.enforceCallingPermission( 4425 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4426 "canShowRequestPermissionRationale for user " + userId); 4427 } 4428 4429 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4430 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4431 return false; 4432 } 4433 4434 if (checkPermission(permissionName, packageName, userId) 4435 == PackageManager.PERMISSION_GRANTED) { 4436 return false; 4437 } 4438 4439 final int flags; 4440 4441 final long identity = Binder.clearCallingIdentity(); 4442 try { 4443 flags = getPermissionFlags(permissionName, 4444 packageName, userId); 4445 } finally { 4446 Binder.restoreCallingIdentity(identity); 4447 } 4448 4449 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4450 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4451 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4452 4453 if ((flags & fixedFlags) != 0) { 4454 return false; 4455 } 4456 4457 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4458 } 4459 4460 @Override 4461 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4462 mContext.enforceCallingOrSelfPermission( 4463 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4464 "addOnPermissionsChangeListener"); 4465 4466 synchronized (mPackages) { 4467 mOnPermissionChangeListeners.addListenerLocked(listener); 4468 } 4469 } 4470 4471 @Override 4472 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4473 synchronized (mPackages) { 4474 mOnPermissionChangeListeners.removeListenerLocked(listener); 4475 } 4476 } 4477 4478 @Override 4479 public boolean isProtectedBroadcast(String actionName) { 4480 synchronized (mPackages) { 4481 if (mProtectedBroadcasts.contains(actionName)) { 4482 return true; 4483 } else if (actionName != null) { 4484 // TODO: remove these terrible hacks 4485 if (actionName.startsWith("android.net.netmon.lingerExpired") 4486 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4487 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4488 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4489 return true; 4490 } 4491 } 4492 } 4493 return false; 4494 } 4495 4496 @Override 4497 public int checkSignatures(String pkg1, String pkg2) { 4498 synchronized (mPackages) { 4499 final PackageParser.Package p1 = mPackages.get(pkg1); 4500 final PackageParser.Package p2 = mPackages.get(pkg2); 4501 if (p1 == null || p1.mExtras == null 4502 || p2 == null || p2.mExtras == null) { 4503 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4504 } 4505 return compareSignatures(p1.mSignatures, p2.mSignatures); 4506 } 4507 } 4508 4509 @Override 4510 public int checkUidSignatures(int uid1, int uid2) { 4511 // Map to base uids. 4512 uid1 = UserHandle.getAppId(uid1); 4513 uid2 = UserHandle.getAppId(uid2); 4514 // reader 4515 synchronized (mPackages) { 4516 Signature[] s1; 4517 Signature[] s2; 4518 Object obj = mSettings.getUserIdLPr(uid1); 4519 if (obj != null) { 4520 if (obj instanceof SharedUserSetting) { 4521 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4522 } else if (obj instanceof PackageSetting) { 4523 s1 = ((PackageSetting)obj).signatures.mSignatures; 4524 } else { 4525 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4526 } 4527 } else { 4528 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4529 } 4530 obj = mSettings.getUserIdLPr(uid2); 4531 if (obj != null) { 4532 if (obj instanceof SharedUserSetting) { 4533 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4534 } else if (obj instanceof PackageSetting) { 4535 s2 = ((PackageSetting)obj).signatures.mSignatures; 4536 } else { 4537 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4538 } 4539 } else { 4540 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4541 } 4542 return compareSignatures(s1, s2); 4543 } 4544 } 4545 4546 /** 4547 * This method should typically only be used when granting or revoking 4548 * permissions, since the app may immediately restart after this call. 4549 * <p> 4550 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4551 * guard your work against the app being relaunched. 4552 */ 4553 private void killUid(int appId, int userId, String reason) { 4554 final long identity = Binder.clearCallingIdentity(); 4555 try { 4556 IActivityManager am = ActivityManager.getService(); 4557 if (am != null) { 4558 try { 4559 am.killUid(appId, userId, reason); 4560 } catch (RemoteException e) { 4561 /* ignore - same process */ 4562 } 4563 } 4564 } finally { 4565 Binder.restoreCallingIdentity(identity); 4566 } 4567 } 4568 4569 /** 4570 * Compares two sets of signatures. Returns: 4571 * <br /> 4572 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4573 * <br /> 4574 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4575 * <br /> 4576 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4577 * <br /> 4578 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4579 * <br /> 4580 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4581 */ 4582 static int compareSignatures(Signature[] s1, Signature[] s2) { 4583 if (s1 == null) { 4584 return s2 == null 4585 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4586 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4587 } 4588 4589 if (s2 == null) { 4590 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4591 } 4592 4593 if (s1.length != s2.length) { 4594 return PackageManager.SIGNATURE_NO_MATCH; 4595 } 4596 4597 // Since both signature sets are of size 1, we can compare without HashSets. 4598 if (s1.length == 1) { 4599 return s1[0].equals(s2[0]) ? 4600 PackageManager.SIGNATURE_MATCH : 4601 PackageManager.SIGNATURE_NO_MATCH; 4602 } 4603 4604 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4605 for (Signature sig : s1) { 4606 set1.add(sig); 4607 } 4608 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4609 for (Signature sig : s2) { 4610 set2.add(sig); 4611 } 4612 // Make sure s2 contains all signatures in s1. 4613 if (set1.equals(set2)) { 4614 return PackageManager.SIGNATURE_MATCH; 4615 } 4616 return PackageManager.SIGNATURE_NO_MATCH; 4617 } 4618 4619 /** 4620 * If the database version for this type of package (internal storage or 4621 * external storage) is less than the version where package signatures 4622 * were updated, return true. 4623 */ 4624 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4625 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4626 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4627 } 4628 4629 /** 4630 * Used for backward compatibility to make sure any packages with 4631 * certificate chains get upgraded to the new style. {@code existingSigs} 4632 * will be in the old format (since they were stored on disk from before the 4633 * system upgrade) and {@code scannedSigs} will be in the newer format. 4634 */ 4635 private int compareSignaturesCompat(PackageSignatures existingSigs, 4636 PackageParser.Package scannedPkg) { 4637 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4638 return PackageManager.SIGNATURE_NO_MATCH; 4639 } 4640 4641 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4642 for (Signature sig : existingSigs.mSignatures) { 4643 existingSet.add(sig); 4644 } 4645 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4646 for (Signature sig : scannedPkg.mSignatures) { 4647 try { 4648 Signature[] chainSignatures = sig.getChainSignatures(); 4649 for (Signature chainSig : chainSignatures) { 4650 scannedCompatSet.add(chainSig); 4651 } 4652 } catch (CertificateEncodingException e) { 4653 scannedCompatSet.add(sig); 4654 } 4655 } 4656 /* 4657 * Make sure the expanded scanned set contains all signatures in the 4658 * existing one. 4659 */ 4660 if (scannedCompatSet.equals(existingSet)) { 4661 // Migrate the old signatures to the new scheme. 4662 existingSigs.assignSignatures(scannedPkg.mSignatures); 4663 // The new KeySets will be re-added later in the scanning process. 4664 synchronized (mPackages) { 4665 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4666 } 4667 return PackageManager.SIGNATURE_MATCH; 4668 } 4669 return PackageManager.SIGNATURE_NO_MATCH; 4670 } 4671 4672 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4673 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4674 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4675 } 4676 4677 private int compareSignaturesRecover(PackageSignatures existingSigs, 4678 PackageParser.Package scannedPkg) { 4679 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4680 return PackageManager.SIGNATURE_NO_MATCH; 4681 } 4682 4683 String msg = null; 4684 try { 4685 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4686 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4687 + scannedPkg.packageName); 4688 return PackageManager.SIGNATURE_MATCH; 4689 } 4690 } catch (CertificateException e) { 4691 msg = e.getMessage(); 4692 } 4693 4694 logCriticalInfo(Log.INFO, 4695 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4696 return PackageManager.SIGNATURE_NO_MATCH; 4697 } 4698 4699 @Override 4700 public List<String> getAllPackages() { 4701 synchronized (mPackages) { 4702 return new ArrayList<String>(mPackages.keySet()); 4703 } 4704 } 4705 4706 @Override 4707 public String[] getPackagesForUid(int uid) { 4708 final int userId = UserHandle.getUserId(uid); 4709 uid = UserHandle.getAppId(uid); 4710 // reader 4711 synchronized (mPackages) { 4712 Object obj = mSettings.getUserIdLPr(uid); 4713 if (obj instanceof SharedUserSetting) { 4714 final SharedUserSetting sus = (SharedUserSetting) obj; 4715 final int N = sus.packages.size(); 4716 String[] res = new String[N]; 4717 final Iterator<PackageSetting> it = sus.packages.iterator(); 4718 int i = 0; 4719 while (it.hasNext()) { 4720 PackageSetting ps = it.next(); 4721 if (ps.getInstalled(userId)) { 4722 res[i++] = ps.name; 4723 } else { 4724 res = ArrayUtils.removeElement(String.class, res, res[i]); 4725 } 4726 } 4727 return res; 4728 } else if (obj instanceof PackageSetting) { 4729 final PackageSetting ps = (PackageSetting) obj; 4730 return new String[] { ps.name }; 4731 } 4732 } 4733 return null; 4734 } 4735 4736 @Override 4737 public String getNameForUid(int uid) { 4738 // reader 4739 synchronized (mPackages) { 4740 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4741 if (obj instanceof SharedUserSetting) { 4742 final SharedUserSetting sus = (SharedUserSetting) obj; 4743 return sus.name + ":" + sus.userId; 4744 } else if (obj instanceof PackageSetting) { 4745 final PackageSetting ps = (PackageSetting) obj; 4746 return ps.name; 4747 } 4748 } 4749 return null; 4750 } 4751 4752 @Override 4753 public int getUidForSharedUser(String sharedUserName) { 4754 if(sharedUserName == null) { 4755 return -1; 4756 } 4757 // reader 4758 synchronized (mPackages) { 4759 SharedUserSetting suid; 4760 try { 4761 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4762 if (suid != null) { 4763 return suid.userId; 4764 } 4765 } catch (PackageManagerException ignore) { 4766 // can't happen, but, still need to catch it 4767 } 4768 return -1; 4769 } 4770 } 4771 4772 @Override 4773 public int getFlagsForUid(int uid) { 4774 synchronized (mPackages) { 4775 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4776 if (obj instanceof SharedUserSetting) { 4777 final SharedUserSetting sus = (SharedUserSetting) obj; 4778 return sus.pkgFlags; 4779 } else if (obj instanceof PackageSetting) { 4780 final PackageSetting ps = (PackageSetting) obj; 4781 return ps.pkgFlags; 4782 } 4783 } 4784 return 0; 4785 } 4786 4787 @Override 4788 public int getPrivateFlagsForUid(int uid) { 4789 synchronized (mPackages) { 4790 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4791 if (obj instanceof SharedUserSetting) { 4792 final SharedUserSetting sus = (SharedUserSetting) obj; 4793 return sus.pkgPrivateFlags; 4794 } else if (obj instanceof PackageSetting) { 4795 final PackageSetting ps = (PackageSetting) obj; 4796 return ps.pkgPrivateFlags; 4797 } 4798 } 4799 return 0; 4800 } 4801 4802 @Override 4803 public boolean isUidPrivileged(int uid) { 4804 uid = UserHandle.getAppId(uid); 4805 // reader 4806 synchronized (mPackages) { 4807 Object obj = mSettings.getUserIdLPr(uid); 4808 if (obj instanceof SharedUserSetting) { 4809 final SharedUserSetting sus = (SharedUserSetting) obj; 4810 final Iterator<PackageSetting> it = sus.packages.iterator(); 4811 while (it.hasNext()) { 4812 if (it.next().isPrivileged()) { 4813 return true; 4814 } 4815 } 4816 } else if (obj instanceof PackageSetting) { 4817 final PackageSetting ps = (PackageSetting) obj; 4818 return ps.isPrivileged(); 4819 } 4820 } 4821 return false; 4822 } 4823 4824 @Override 4825 public String[] getAppOpPermissionPackages(String permissionName) { 4826 synchronized (mPackages) { 4827 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4828 if (pkgs == null) { 4829 return null; 4830 } 4831 return pkgs.toArray(new String[pkgs.size()]); 4832 } 4833 } 4834 4835 @Override 4836 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4837 int flags, int userId) { 4838 try { 4839 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4840 4841 if (!sUserManager.exists(userId)) return null; 4842 flags = updateFlagsForResolve(flags, userId, intent); 4843 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4844 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4845 4846 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4847 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4848 flags, userId); 4849 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4850 4851 final ResolveInfo bestChoice = 4852 chooseBestActivity(intent, resolvedType, flags, query, userId); 4853 return bestChoice; 4854 } finally { 4855 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4856 } 4857 } 4858 4859 @Override 4860 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4861 IntentFilter filter, int match, ComponentName activity) { 4862 final int userId = UserHandle.getCallingUserId(); 4863 if (DEBUG_PREFERRED) { 4864 Log.v(TAG, "setLastChosenActivity intent=" + intent 4865 + " resolvedType=" + resolvedType 4866 + " flags=" + flags 4867 + " filter=" + filter 4868 + " match=" + match 4869 + " activity=" + activity); 4870 filter.dump(new PrintStreamPrinter(System.out), " "); 4871 } 4872 intent.setComponent(null); 4873 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4874 userId); 4875 // Find any earlier preferred or last chosen entries and nuke them 4876 findPreferredActivity(intent, resolvedType, 4877 flags, query, 0, false, true, false, userId); 4878 // Add the new activity as the last chosen for this filter 4879 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4880 "Setting last chosen"); 4881 } 4882 4883 @Override 4884 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4885 final int userId = UserHandle.getCallingUserId(); 4886 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4887 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4888 userId); 4889 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4890 false, false, false, userId); 4891 } 4892 4893 private boolean isEphemeralDisabled() { 4894 // ephemeral apps have been disabled across the board 4895 if (DISABLE_EPHEMERAL_APPS) { 4896 return true; 4897 } 4898 // system isn't up yet; can't read settings, so, assume no ephemeral apps 4899 if (!mSystemReady) { 4900 return true; 4901 } 4902 // we can't get a content resolver until the system is ready; these checks must happen last 4903 final ContentResolver resolver = mContext.getContentResolver(); 4904 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 4905 return true; 4906 } 4907 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 4908 } 4909 4910 private boolean isEphemeralAllowed( 4911 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 4912 boolean skipPackageCheck) { 4913 // Short circuit and return early if possible. 4914 if (isEphemeralDisabled()) { 4915 return false; 4916 } 4917 final int callingUser = UserHandle.getCallingUserId(); 4918 if (callingUser != UserHandle.USER_SYSTEM) { 4919 return false; 4920 } 4921 if (mEphemeralResolverConnection == null) { 4922 return false; 4923 } 4924 if (intent.getComponent() != null) { 4925 return false; 4926 } 4927 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 4928 return false; 4929 } 4930 if (!skipPackageCheck && intent.getPackage() != null) { 4931 return false; 4932 } 4933 final boolean isWebUri = hasWebURI(intent); 4934 if (!isWebUri || intent.getData().getHost() == null) { 4935 return false; 4936 } 4937 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4938 synchronized (mPackages) { 4939 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 4940 for (int n = 0; n < count; n++) { 4941 ResolveInfo info = resolvedActivities.get(n); 4942 String packageName = info.activityInfo.packageName; 4943 PackageSetting ps = mSettings.mPackages.get(packageName); 4944 if (ps != null) { 4945 // Try to get the status from User settings first 4946 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4947 int status = (int) (packedStatus >> 32); 4948 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4949 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4950 if (DEBUG_EPHEMERAL) { 4951 Slog.v(TAG, "DENY ephemeral apps;" 4952 + " pkg: " + packageName + ", status: " + status); 4953 } 4954 return false; 4955 } 4956 } 4957 } 4958 } 4959 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4960 return true; 4961 } 4962 4963 private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 4964 Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage, 4965 int userId) { 4966 final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO, 4967 new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent, 4968 callingPackage, userId)); 4969 mHandler.sendMessage(msg); 4970 } 4971 4972 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4973 int flags, List<ResolveInfo> query, int userId) { 4974 if (query != null) { 4975 final int N = query.size(); 4976 if (N == 1) { 4977 return query.get(0); 4978 } else if (N > 1) { 4979 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4980 // If there is more than one activity with the same priority, 4981 // then let the user decide between them. 4982 ResolveInfo r0 = query.get(0); 4983 ResolveInfo r1 = query.get(1); 4984 if (DEBUG_INTENT_MATCHING || debug) { 4985 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4986 + r1.activityInfo.name + "=" + r1.priority); 4987 } 4988 // If the first activity has a higher priority, or a different 4989 // default, then it is always desirable to pick it. 4990 if (r0.priority != r1.priority 4991 || r0.preferredOrder != r1.preferredOrder 4992 || r0.isDefault != r1.isDefault) { 4993 return query.get(0); 4994 } 4995 // If we have saved a preference for a preferred activity for 4996 // this Intent, use that. 4997 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4998 flags, query, r0.priority, true, false, debug, userId); 4999 if (ri != null) { 5000 return ri; 5001 } 5002 ri = new ResolveInfo(mResolveInfo); 5003 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5004 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5005 // If all of the options come from the same package, show the application's 5006 // label and icon instead of the generic resolver's. 5007 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5008 // and then throw away the ResolveInfo itself, meaning that the caller loses 5009 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5010 // a fallback for this case; we only set the target package's resources on 5011 // the ResolveInfo, not the ActivityInfo. 5012 final String intentPackage = intent.getPackage(); 5013 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5014 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5015 ri.resolvePackageName = intentPackage; 5016 if (userNeedsBadging(userId)) { 5017 ri.noResourceId = true; 5018 } else { 5019 ri.icon = appi.icon; 5020 } 5021 ri.iconResourceId = appi.icon; 5022 ri.labelRes = appi.labelRes; 5023 } 5024 ri.activityInfo.applicationInfo = new ApplicationInfo( 5025 ri.activityInfo.applicationInfo); 5026 if (userId != 0) { 5027 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5028 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5029 } 5030 // Make sure that the resolver is displayable in car mode 5031 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5032 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5033 return ri; 5034 } 5035 } 5036 return null; 5037 } 5038 5039 /** 5040 * Return true if the given list is not empty and all of its contents have 5041 * an activityInfo with the given package name. 5042 */ 5043 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5044 if (ArrayUtils.isEmpty(list)) { 5045 return false; 5046 } 5047 for (int i = 0, N = list.size(); i < N; i++) { 5048 final ResolveInfo ri = list.get(i); 5049 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5050 if (ai == null || !packageName.equals(ai.packageName)) { 5051 return false; 5052 } 5053 } 5054 return true; 5055 } 5056 5057 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5058 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5059 final int N = query.size(); 5060 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5061 .get(userId); 5062 // Get the list of persistent preferred activities that handle the intent 5063 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5064 List<PersistentPreferredActivity> pprefs = ppir != null 5065 ? ppir.queryIntent(intent, resolvedType, 5066 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5067 : null; 5068 if (pprefs != null && pprefs.size() > 0) { 5069 final int M = pprefs.size(); 5070 for (int i=0; i<M; i++) { 5071 final PersistentPreferredActivity ppa = pprefs.get(i); 5072 if (DEBUG_PREFERRED || debug) { 5073 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5074 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5075 + "\n component=" + ppa.mComponent); 5076 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5077 } 5078 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5079 flags | MATCH_DISABLED_COMPONENTS, userId); 5080 if (DEBUG_PREFERRED || debug) { 5081 Slog.v(TAG, "Found persistent preferred activity:"); 5082 if (ai != null) { 5083 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5084 } else { 5085 Slog.v(TAG, " null"); 5086 } 5087 } 5088 if (ai == null) { 5089 // This previously registered persistent preferred activity 5090 // component is no longer known. Ignore it and do NOT remove it. 5091 continue; 5092 } 5093 for (int j=0; j<N; j++) { 5094 final ResolveInfo ri = query.get(j); 5095 if (!ri.activityInfo.applicationInfo.packageName 5096 .equals(ai.applicationInfo.packageName)) { 5097 continue; 5098 } 5099 if (!ri.activityInfo.name.equals(ai.name)) { 5100 continue; 5101 } 5102 // Found a persistent preference that can handle the intent. 5103 if (DEBUG_PREFERRED || debug) { 5104 Slog.v(TAG, "Returning persistent preferred activity: " + 5105 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5106 } 5107 return ri; 5108 } 5109 } 5110 } 5111 return null; 5112 } 5113 5114 // TODO: handle preferred activities missing while user has amnesia 5115 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5116 List<ResolveInfo> query, int priority, boolean always, 5117 boolean removeMatches, boolean debug, int userId) { 5118 if (!sUserManager.exists(userId)) return null; 5119 flags = updateFlagsForResolve(flags, userId, intent); 5120 // writer 5121 synchronized (mPackages) { 5122 if (intent.getSelector() != null) { 5123 intent = intent.getSelector(); 5124 } 5125 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5126 5127 // Try to find a matching persistent preferred activity. 5128 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5129 debug, userId); 5130 5131 // If a persistent preferred activity matched, use it. 5132 if (pri != null) { 5133 return pri; 5134 } 5135 5136 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5137 // Get the list of preferred activities that handle the intent 5138 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5139 List<PreferredActivity> prefs = pir != null 5140 ? pir.queryIntent(intent, resolvedType, 5141 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5142 : null; 5143 if (prefs != null && prefs.size() > 0) { 5144 boolean changed = false; 5145 try { 5146 // First figure out how good the original match set is. 5147 // We will only allow preferred activities that came 5148 // from the same match quality. 5149 int match = 0; 5150 5151 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5152 5153 final int N = query.size(); 5154 for (int j=0; j<N; j++) { 5155 final ResolveInfo ri = query.get(j); 5156 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5157 + ": 0x" + Integer.toHexString(match)); 5158 if (ri.match > match) { 5159 match = ri.match; 5160 } 5161 } 5162 5163 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5164 + Integer.toHexString(match)); 5165 5166 match &= IntentFilter.MATCH_CATEGORY_MASK; 5167 final int M = prefs.size(); 5168 for (int i=0; i<M; i++) { 5169 final PreferredActivity pa = prefs.get(i); 5170 if (DEBUG_PREFERRED || debug) { 5171 Slog.v(TAG, "Checking PreferredActivity ds=" 5172 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5173 + "\n component=" + pa.mPref.mComponent); 5174 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5175 } 5176 if (pa.mPref.mMatch != match) { 5177 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5178 + Integer.toHexString(pa.mPref.mMatch)); 5179 continue; 5180 } 5181 // If it's not an "always" type preferred activity and that's what we're 5182 // looking for, skip it. 5183 if (always && !pa.mPref.mAlways) { 5184 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5185 continue; 5186 } 5187 final ActivityInfo ai = getActivityInfo( 5188 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5189 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5190 userId); 5191 if (DEBUG_PREFERRED || debug) { 5192 Slog.v(TAG, "Found preferred activity:"); 5193 if (ai != null) { 5194 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5195 } else { 5196 Slog.v(TAG, " null"); 5197 } 5198 } 5199 if (ai == null) { 5200 // This previously registered preferred activity 5201 // component is no longer known. Most likely an update 5202 // to the app was installed and in the new version this 5203 // component no longer exists. Clean it up by removing 5204 // it from the preferred activities list, and skip it. 5205 Slog.w(TAG, "Removing dangling preferred activity: " 5206 + pa.mPref.mComponent); 5207 pir.removeFilter(pa); 5208 changed = true; 5209 continue; 5210 } 5211 for (int j=0; j<N; j++) { 5212 final ResolveInfo ri = query.get(j); 5213 if (!ri.activityInfo.applicationInfo.packageName 5214 .equals(ai.applicationInfo.packageName)) { 5215 continue; 5216 } 5217 if (!ri.activityInfo.name.equals(ai.name)) { 5218 continue; 5219 } 5220 5221 if (removeMatches) { 5222 pir.removeFilter(pa); 5223 changed = true; 5224 if (DEBUG_PREFERRED) { 5225 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5226 } 5227 break; 5228 } 5229 5230 // Okay we found a previously set preferred or last chosen app. 5231 // If the result set is different from when this 5232 // was created, we need to clear it and re-ask the 5233 // user their preference, if we're looking for an "always" type entry. 5234 if (always && !pa.mPref.sameSet(query)) { 5235 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5236 + intent + " type " + resolvedType); 5237 if (DEBUG_PREFERRED) { 5238 Slog.v(TAG, "Removing preferred activity since set changed " 5239 + pa.mPref.mComponent); 5240 } 5241 pir.removeFilter(pa); 5242 // Re-add the filter as a "last chosen" entry (!always) 5243 PreferredActivity lastChosen = new PreferredActivity( 5244 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5245 pir.addFilter(lastChosen); 5246 changed = true; 5247 return null; 5248 } 5249 5250 // Yay! Either the set matched or we're looking for the last chosen 5251 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5252 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5253 return ri; 5254 } 5255 } 5256 } finally { 5257 if (changed) { 5258 if (DEBUG_PREFERRED) { 5259 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5260 } 5261 scheduleWritePackageRestrictionsLocked(userId); 5262 } 5263 } 5264 } 5265 } 5266 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5267 return null; 5268 } 5269 5270 /* 5271 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5272 */ 5273 @Override 5274 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5275 int targetUserId) { 5276 mContext.enforceCallingOrSelfPermission( 5277 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5278 List<CrossProfileIntentFilter> matches = 5279 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5280 if (matches != null) { 5281 int size = matches.size(); 5282 for (int i = 0; i < size; i++) { 5283 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5284 } 5285 } 5286 if (hasWebURI(intent)) { 5287 // cross-profile app linking works only towards the parent. 5288 final UserInfo parent = getProfileParent(sourceUserId); 5289 synchronized(mPackages) { 5290 int flags = updateFlagsForResolve(0, parent.id, intent); 5291 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5292 intent, resolvedType, flags, sourceUserId, parent.id); 5293 return xpDomainInfo != null; 5294 } 5295 } 5296 return false; 5297 } 5298 5299 private UserInfo getProfileParent(int userId) { 5300 final long identity = Binder.clearCallingIdentity(); 5301 try { 5302 return sUserManager.getProfileParent(userId); 5303 } finally { 5304 Binder.restoreCallingIdentity(identity); 5305 } 5306 } 5307 5308 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5309 String resolvedType, int userId) { 5310 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5311 if (resolver != null) { 5312 return resolver.queryIntent(intent, resolvedType, false, userId); 5313 } 5314 return null; 5315 } 5316 5317 @Override 5318 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5319 String resolvedType, int flags, int userId) { 5320 try { 5321 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5322 5323 return new ParceledListSlice<>( 5324 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5325 } finally { 5326 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5327 } 5328 } 5329 5330 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5331 String resolvedType, int flags, int userId) { 5332 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5333 flags = updateFlagsForResolve(flags, userId, intent); 5334 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5335 false /* requireFullPermission */, false /* checkShell */, 5336 "query intent activities"); 5337 ComponentName comp = intent.getComponent(); 5338 if (comp == null) { 5339 if (intent.getSelector() != null) { 5340 intent = intent.getSelector(); 5341 comp = intent.getComponent(); 5342 } 5343 } 5344 5345 if (comp != null) { 5346 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5347 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5348 if (ai != null) { 5349 final ResolveInfo ri = new ResolveInfo(); 5350 ri.activityInfo = ai; 5351 list.add(ri); 5352 } 5353 return list; 5354 } 5355 5356 // reader 5357 boolean sortResult = false; 5358 boolean addEphemeral = false; 5359 boolean matchEphemeralPackage = false; 5360 List<ResolveInfo> result; 5361 final String pkgName = intent.getPackage(); 5362 synchronized (mPackages) { 5363 if (pkgName == null) { 5364 List<CrossProfileIntentFilter> matchingFilters = 5365 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5366 // Check for results that need to skip the current profile. 5367 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5368 resolvedType, flags, userId); 5369 if (xpResolveInfo != null) { 5370 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5371 xpResult.add(xpResolveInfo); 5372 return filterIfNotSystemUser(xpResult, userId); 5373 } 5374 5375 // Check for results in the current profile. 5376 result = filterIfNotSystemUser(mActivities.queryIntent( 5377 intent, resolvedType, flags, userId), userId); 5378 addEphemeral = 5379 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5380 5381 // Check for cross profile results. 5382 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5383 xpResolveInfo = queryCrossProfileIntents( 5384 matchingFilters, intent, resolvedType, flags, userId, 5385 hasNonNegativePriorityResult); 5386 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5387 boolean isVisibleToUser = filterIfNotSystemUser( 5388 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5389 if (isVisibleToUser) { 5390 result.add(xpResolveInfo); 5391 sortResult = true; 5392 } 5393 } 5394 if (hasWebURI(intent)) { 5395 CrossProfileDomainInfo xpDomainInfo = null; 5396 final UserInfo parent = getProfileParent(userId); 5397 if (parent != null) { 5398 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5399 flags, userId, parent.id); 5400 } 5401 if (xpDomainInfo != null) { 5402 if (xpResolveInfo != null) { 5403 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5404 // in the result. 5405 result.remove(xpResolveInfo); 5406 } 5407 if (result.size() == 0 && !addEphemeral) { 5408 // No result in current profile, but found candidate in parent user. 5409 // And we are not going to add emphemeral app, so we can return the 5410 // result straight away. 5411 result.add(xpDomainInfo.resolveInfo); 5412 return result; 5413 } 5414 } else if (result.size() <= 1 && !addEphemeral) { 5415 // No result in parent user and <= 1 result in current profile, and we 5416 // are not going to add emphemeral app, so we can return the result without 5417 // further processing. 5418 return result; 5419 } 5420 // We have more than one candidate (combining results from current and parent 5421 // profile), so we need filtering and sorting. 5422 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5423 intent, flags, result, xpDomainInfo, userId); 5424 sortResult = true; 5425 } 5426 } else { 5427 final PackageParser.Package pkg = mPackages.get(pkgName); 5428 if (pkg != null) { 5429 result = filterIfNotSystemUser( 5430 mActivities.queryIntentForPackage( 5431 intent, resolvedType, flags, pkg.activities, userId), 5432 userId); 5433 } else { 5434 // the caller wants to resolve for a particular package; however, there 5435 // were no installed results, so, try to find an ephemeral result 5436 addEphemeral = isEphemeralAllowed( 5437 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5438 matchEphemeralPackage = true; 5439 result = new ArrayList<ResolveInfo>(); 5440 } 5441 } 5442 } 5443 if (addEphemeral) { 5444 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5445 final EphemeralRequest requestObject = new EphemeralRequest( 5446 null /*responseObj*/, intent /*origIntent*/, resolvedType, 5447 null /*launchIntent*/, null /*callingPackage*/, userId); 5448 final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne( 5449 mContext, mEphemeralResolverConnection, requestObject); 5450 if (intentInfo != null) { 5451 if (DEBUG_EPHEMERAL) { 5452 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5453 } 5454 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5455 ephemeralInstaller.ephemeralResponse = intentInfo; 5456 // make sure this resolver is the default 5457 ephemeralInstaller.isDefault = true; 5458 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5459 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5460 // add a non-generic filter 5461 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5462 ephemeralInstaller.filter.addDataPath( 5463 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5464 result.add(ephemeralInstaller); 5465 } 5466 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5467 } 5468 if (sortResult) { 5469 Collections.sort(result, mResolvePrioritySorter); 5470 } 5471 return result; 5472 } 5473 5474 private static class CrossProfileDomainInfo { 5475 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5476 ResolveInfo resolveInfo; 5477 /* Best domain verification status of the activities found in the other profile */ 5478 int bestDomainVerificationStatus; 5479 } 5480 5481 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5482 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5483 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5484 sourceUserId)) { 5485 return null; 5486 } 5487 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5488 resolvedType, flags, parentUserId); 5489 5490 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5491 return null; 5492 } 5493 CrossProfileDomainInfo result = null; 5494 int size = resultTargetUser.size(); 5495 for (int i = 0; i < size; i++) { 5496 ResolveInfo riTargetUser = resultTargetUser.get(i); 5497 // Intent filter verification is only for filters that specify a host. So don't return 5498 // those that handle all web uris. 5499 if (riTargetUser.handleAllWebDataURI) { 5500 continue; 5501 } 5502 String packageName = riTargetUser.activityInfo.packageName; 5503 PackageSetting ps = mSettings.mPackages.get(packageName); 5504 if (ps == null) { 5505 continue; 5506 } 5507 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5508 int status = (int)(verificationState >> 32); 5509 if (result == null) { 5510 result = new CrossProfileDomainInfo(); 5511 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5512 sourceUserId, parentUserId); 5513 result.bestDomainVerificationStatus = status; 5514 } else { 5515 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5516 result.bestDomainVerificationStatus); 5517 } 5518 } 5519 // Don't consider matches with status NEVER across profiles. 5520 if (result != null && result.bestDomainVerificationStatus 5521 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5522 return null; 5523 } 5524 return result; 5525 } 5526 5527 /** 5528 * Verification statuses are ordered from the worse to the best, except for 5529 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5530 */ 5531 private int bestDomainVerificationStatus(int status1, int status2) { 5532 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5533 return status2; 5534 } 5535 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5536 return status1; 5537 } 5538 return (int) MathUtils.max(status1, status2); 5539 } 5540 5541 private boolean isUserEnabled(int userId) { 5542 long callingId = Binder.clearCallingIdentity(); 5543 try { 5544 UserInfo userInfo = sUserManager.getUserInfo(userId); 5545 return userInfo != null && userInfo.isEnabled(); 5546 } finally { 5547 Binder.restoreCallingIdentity(callingId); 5548 } 5549 } 5550 5551 /** 5552 * Filter out activities with systemUserOnly flag set, when current user is not System. 5553 * 5554 * @return filtered list 5555 */ 5556 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5557 if (userId == UserHandle.USER_SYSTEM) { 5558 return resolveInfos; 5559 } 5560 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5561 ResolveInfo info = resolveInfos.get(i); 5562 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5563 resolveInfos.remove(i); 5564 } 5565 } 5566 return resolveInfos; 5567 } 5568 5569 /** 5570 * @param resolveInfos list of resolve infos in descending priority order 5571 * @return if the list contains a resolve info with non-negative priority 5572 */ 5573 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5574 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5575 } 5576 5577 private static boolean hasWebURI(Intent intent) { 5578 if (intent.getData() == null) { 5579 return false; 5580 } 5581 final String scheme = intent.getScheme(); 5582 if (TextUtils.isEmpty(scheme)) { 5583 return false; 5584 } 5585 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5586 } 5587 5588 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5589 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5590 int userId) { 5591 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5592 5593 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5594 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5595 candidates.size()); 5596 } 5597 5598 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5599 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5600 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5601 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5602 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5603 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5604 5605 synchronized (mPackages) { 5606 final int count = candidates.size(); 5607 // First, try to use linked apps. Partition the candidates into four lists: 5608 // one for the final results, one for the "do not use ever", one for "undefined status" 5609 // and finally one for "browser app type". 5610 for (int n=0; n<count; n++) { 5611 ResolveInfo info = candidates.get(n); 5612 String packageName = info.activityInfo.packageName; 5613 PackageSetting ps = mSettings.mPackages.get(packageName); 5614 if (ps != null) { 5615 // Add to the special match all list (Browser use case) 5616 if (info.handleAllWebDataURI) { 5617 matchAllList.add(info); 5618 continue; 5619 } 5620 // Try to get the status from User settings first 5621 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5622 int status = (int)(packedStatus >> 32); 5623 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5624 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5625 if (DEBUG_DOMAIN_VERIFICATION) { 5626 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5627 + " : linkgen=" + linkGeneration); 5628 } 5629 // Use link-enabled generation as preferredOrder, i.e. 5630 // prefer newly-enabled over earlier-enabled. 5631 info.preferredOrder = linkGeneration; 5632 alwaysList.add(info); 5633 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5634 if (DEBUG_DOMAIN_VERIFICATION) { 5635 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5636 } 5637 neverList.add(info); 5638 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5639 if (DEBUG_DOMAIN_VERIFICATION) { 5640 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5641 } 5642 alwaysAskList.add(info); 5643 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5644 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5645 if (DEBUG_DOMAIN_VERIFICATION) { 5646 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5647 } 5648 undefinedList.add(info); 5649 } 5650 } 5651 } 5652 5653 // We'll want to include browser possibilities in a few cases 5654 boolean includeBrowser = false; 5655 5656 // First try to add the "always" resolution(s) for the current user, if any 5657 if (alwaysList.size() > 0) { 5658 result.addAll(alwaysList); 5659 } else { 5660 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5661 result.addAll(undefinedList); 5662 // Maybe add one for the other profile. 5663 if (xpDomainInfo != null && ( 5664 xpDomainInfo.bestDomainVerificationStatus 5665 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5666 result.add(xpDomainInfo.resolveInfo); 5667 } 5668 includeBrowser = true; 5669 } 5670 5671 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5672 // If there were 'always' entries their preferred order has been set, so we also 5673 // back that off to make the alternatives equivalent 5674 if (alwaysAskList.size() > 0) { 5675 for (ResolveInfo i : result) { 5676 i.preferredOrder = 0; 5677 } 5678 result.addAll(alwaysAskList); 5679 includeBrowser = true; 5680 } 5681 5682 if (includeBrowser) { 5683 // Also add browsers (all of them or only the default one) 5684 if (DEBUG_DOMAIN_VERIFICATION) { 5685 Slog.v(TAG, " ...including browsers in candidate set"); 5686 } 5687 if ((matchFlags & MATCH_ALL) != 0) { 5688 result.addAll(matchAllList); 5689 } else { 5690 // Browser/generic handling case. If there's a default browser, go straight 5691 // to that (but only if there is no other higher-priority match). 5692 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5693 int maxMatchPrio = 0; 5694 ResolveInfo defaultBrowserMatch = null; 5695 final int numCandidates = matchAllList.size(); 5696 for (int n = 0; n < numCandidates; n++) { 5697 ResolveInfo info = matchAllList.get(n); 5698 // track the highest overall match priority... 5699 if (info.priority > maxMatchPrio) { 5700 maxMatchPrio = info.priority; 5701 } 5702 // ...and the highest-priority default browser match 5703 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5704 if (defaultBrowserMatch == null 5705 || (defaultBrowserMatch.priority < info.priority)) { 5706 if (debug) { 5707 Slog.v(TAG, "Considering default browser match " + info); 5708 } 5709 defaultBrowserMatch = info; 5710 } 5711 } 5712 } 5713 if (defaultBrowserMatch != null 5714 && defaultBrowserMatch.priority >= maxMatchPrio 5715 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5716 { 5717 if (debug) { 5718 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5719 } 5720 result.add(defaultBrowserMatch); 5721 } else { 5722 result.addAll(matchAllList); 5723 } 5724 } 5725 5726 // If there is nothing selected, add all candidates and remove the ones that the user 5727 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5728 if (result.size() == 0) { 5729 result.addAll(candidates); 5730 result.removeAll(neverList); 5731 } 5732 } 5733 } 5734 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5735 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5736 result.size()); 5737 for (ResolveInfo info : result) { 5738 Slog.v(TAG, " + " + info.activityInfo); 5739 } 5740 } 5741 return result; 5742 } 5743 5744 // Returns a packed value as a long: 5745 // 5746 // high 'int'-sized word: link status: undefined/ask/never/always. 5747 // low 'int'-sized word: relative priority among 'always' results. 5748 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5749 long result = ps.getDomainVerificationStatusForUser(userId); 5750 // if none available, get the master status 5751 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5752 if (ps.getIntentFilterVerificationInfo() != null) { 5753 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5754 } 5755 } 5756 return result; 5757 } 5758 5759 private ResolveInfo querySkipCurrentProfileIntents( 5760 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5761 int flags, int sourceUserId) { 5762 if (matchingFilters != null) { 5763 int size = matchingFilters.size(); 5764 for (int i = 0; i < size; i ++) { 5765 CrossProfileIntentFilter filter = matchingFilters.get(i); 5766 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5767 // Checking if there are activities in the target user that can handle the 5768 // intent. 5769 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5770 resolvedType, flags, sourceUserId); 5771 if (resolveInfo != null) { 5772 return resolveInfo; 5773 } 5774 } 5775 } 5776 } 5777 return null; 5778 } 5779 5780 // Return matching ResolveInfo in target user if any. 5781 private ResolveInfo queryCrossProfileIntents( 5782 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5783 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5784 if (matchingFilters != null) { 5785 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5786 // match the same intent. For performance reasons, it is better not to 5787 // run queryIntent twice for the same userId 5788 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5789 int size = matchingFilters.size(); 5790 for (int i = 0; i < size; i++) { 5791 CrossProfileIntentFilter filter = matchingFilters.get(i); 5792 int targetUserId = filter.getTargetUserId(); 5793 boolean skipCurrentProfile = 5794 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5795 boolean skipCurrentProfileIfNoMatchFound = 5796 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5797 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5798 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5799 // Checking if there are activities in the target user that can handle the 5800 // intent. 5801 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5802 resolvedType, flags, sourceUserId); 5803 if (resolveInfo != null) return resolveInfo; 5804 alreadyTriedUserIds.put(targetUserId, true); 5805 } 5806 } 5807 } 5808 return null; 5809 } 5810 5811 /** 5812 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5813 * will forward the intent to the filter's target user. 5814 * Otherwise, returns null. 5815 */ 5816 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5817 String resolvedType, int flags, int sourceUserId) { 5818 int targetUserId = filter.getTargetUserId(); 5819 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5820 resolvedType, flags, targetUserId); 5821 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5822 // If all the matches in the target profile are suspended, return null. 5823 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5824 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5825 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5826 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5827 targetUserId); 5828 } 5829 } 5830 } 5831 return null; 5832 } 5833 5834 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5835 int sourceUserId, int targetUserId) { 5836 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5837 long ident = Binder.clearCallingIdentity(); 5838 boolean targetIsProfile; 5839 try { 5840 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5841 } finally { 5842 Binder.restoreCallingIdentity(ident); 5843 } 5844 String className; 5845 if (targetIsProfile) { 5846 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5847 } else { 5848 className = FORWARD_INTENT_TO_PARENT; 5849 } 5850 ComponentName forwardingActivityComponentName = new ComponentName( 5851 mAndroidApplication.packageName, className); 5852 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5853 sourceUserId); 5854 if (!targetIsProfile) { 5855 forwardingActivityInfo.showUserIcon = targetUserId; 5856 forwardingResolveInfo.noResourceId = true; 5857 } 5858 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5859 forwardingResolveInfo.priority = 0; 5860 forwardingResolveInfo.preferredOrder = 0; 5861 forwardingResolveInfo.match = 0; 5862 forwardingResolveInfo.isDefault = true; 5863 forwardingResolveInfo.filter = filter; 5864 forwardingResolveInfo.targetUserId = targetUserId; 5865 return forwardingResolveInfo; 5866 } 5867 5868 @Override 5869 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5870 Intent[] specifics, String[] specificTypes, Intent intent, 5871 String resolvedType, int flags, int userId) { 5872 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5873 specificTypes, intent, resolvedType, flags, userId)); 5874 } 5875 5876 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5877 Intent[] specifics, String[] specificTypes, Intent intent, 5878 String resolvedType, int flags, int userId) { 5879 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5880 flags = updateFlagsForResolve(flags, userId, intent); 5881 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5882 false /* requireFullPermission */, false /* checkShell */, 5883 "query intent activity options"); 5884 final String resultsAction = intent.getAction(); 5885 5886 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5887 | PackageManager.GET_RESOLVED_FILTER, userId); 5888 5889 if (DEBUG_INTENT_MATCHING) { 5890 Log.v(TAG, "Query " + intent + ": " + results); 5891 } 5892 5893 int specificsPos = 0; 5894 int N; 5895 5896 // todo: note that the algorithm used here is O(N^2). This 5897 // isn't a problem in our current environment, but if we start running 5898 // into situations where we have more than 5 or 10 matches then this 5899 // should probably be changed to something smarter... 5900 5901 // First we go through and resolve each of the specific items 5902 // that were supplied, taking care of removing any corresponding 5903 // duplicate items in the generic resolve list. 5904 if (specifics != null) { 5905 for (int i=0; i<specifics.length; i++) { 5906 final Intent sintent = specifics[i]; 5907 if (sintent == null) { 5908 continue; 5909 } 5910 5911 if (DEBUG_INTENT_MATCHING) { 5912 Log.v(TAG, "Specific #" + i + ": " + sintent); 5913 } 5914 5915 String action = sintent.getAction(); 5916 if (resultsAction != null && resultsAction.equals(action)) { 5917 // If this action was explicitly requested, then don't 5918 // remove things that have it. 5919 action = null; 5920 } 5921 5922 ResolveInfo ri = null; 5923 ActivityInfo ai = null; 5924 5925 ComponentName comp = sintent.getComponent(); 5926 if (comp == null) { 5927 ri = resolveIntent( 5928 sintent, 5929 specificTypes != null ? specificTypes[i] : null, 5930 flags, userId); 5931 if (ri == null) { 5932 continue; 5933 } 5934 if (ri == mResolveInfo) { 5935 // ACK! Must do something better with this. 5936 } 5937 ai = ri.activityInfo; 5938 comp = new ComponentName(ai.applicationInfo.packageName, 5939 ai.name); 5940 } else { 5941 ai = getActivityInfo(comp, flags, userId); 5942 if (ai == null) { 5943 continue; 5944 } 5945 } 5946 5947 // Look for any generic query activities that are duplicates 5948 // of this specific one, and remove them from the results. 5949 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5950 N = results.size(); 5951 int j; 5952 for (j=specificsPos; j<N; j++) { 5953 ResolveInfo sri = results.get(j); 5954 if ((sri.activityInfo.name.equals(comp.getClassName()) 5955 && sri.activityInfo.applicationInfo.packageName.equals( 5956 comp.getPackageName())) 5957 || (action != null && sri.filter.matchAction(action))) { 5958 results.remove(j); 5959 if (DEBUG_INTENT_MATCHING) Log.v( 5960 TAG, "Removing duplicate item from " + j 5961 + " due to specific " + specificsPos); 5962 if (ri == null) { 5963 ri = sri; 5964 } 5965 j--; 5966 N--; 5967 } 5968 } 5969 5970 // Add this specific item to its proper place. 5971 if (ri == null) { 5972 ri = new ResolveInfo(); 5973 ri.activityInfo = ai; 5974 } 5975 results.add(specificsPos, ri); 5976 ri.specificIndex = i; 5977 specificsPos++; 5978 } 5979 } 5980 5981 // Now we go through the remaining generic results and remove any 5982 // duplicate actions that are found here. 5983 N = results.size(); 5984 for (int i=specificsPos; i<N-1; i++) { 5985 final ResolveInfo rii = results.get(i); 5986 if (rii.filter == null) { 5987 continue; 5988 } 5989 5990 // Iterate over all of the actions of this result's intent 5991 // filter... typically this should be just one. 5992 final Iterator<String> it = rii.filter.actionsIterator(); 5993 if (it == null) { 5994 continue; 5995 } 5996 while (it.hasNext()) { 5997 final String action = it.next(); 5998 if (resultsAction != null && resultsAction.equals(action)) { 5999 // If this action was explicitly requested, then don't 6000 // remove things that have it. 6001 continue; 6002 } 6003 for (int j=i+1; j<N; j++) { 6004 final ResolveInfo rij = results.get(j); 6005 if (rij.filter != null && rij.filter.hasAction(action)) { 6006 results.remove(j); 6007 if (DEBUG_INTENT_MATCHING) Log.v( 6008 TAG, "Removing duplicate item from " + j 6009 + " due to action " + action + " at " + i); 6010 j--; 6011 N--; 6012 } 6013 } 6014 } 6015 6016 // If the caller didn't request filter information, drop it now 6017 // so we don't have to marshall/unmarshall it. 6018 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6019 rii.filter = null; 6020 } 6021 } 6022 6023 // Filter out the caller activity if so requested. 6024 if (caller != null) { 6025 N = results.size(); 6026 for (int i=0; i<N; i++) { 6027 ActivityInfo ainfo = results.get(i).activityInfo; 6028 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6029 && caller.getClassName().equals(ainfo.name)) { 6030 results.remove(i); 6031 break; 6032 } 6033 } 6034 } 6035 6036 // If the caller didn't request filter information, 6037 // drop them now so we don't have to 6038 // marshall/unmarshall it. 6039 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6040 N = results.size(); 6041 for (int i=0; i<N; i++) { 6042 results.get(i).filter = null; 6043 } 6044 } 6045 6046 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6047 return results; 6048 } 6049 6050 @Override 6051 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6052 String resolvedType, int flags, int userId) { 6053 return new ParceledListSlice<>( 6054 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6055 } 6056 6057 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6058 String resolvedType, int flags, int userId) { 6059 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6060 flags = updateFlagsForResolve(flags, userId, intent); 6061 ComponentName comp = intent.getComponent(); 6062 if (comp == null) { 6063 if (intent.getSelector() != null) { 6064 intent = intent.getSelector(); 6065 comp = intent.getComponent(); 6066 } 6067 } 6068 if (comp != null) { 6069 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6070 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6071 if (ai != null) { 6072 ResolveInfo ri = new ResolveInfo(); 6073 ri.activityInfo = ai; 6074 list.add(ri); 6075 } 6076 return list; 6077 } 6078 6079 // reader 6080 synchronized (mPackages) { 6081 String pkgName = intent.getPackage(); 6082 if (pkgName == null) { 6083 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6084 } 6085 final PackageParser.Package pkg = mPackages.get(pkgName); 6086 if (pkg != null) { 6087 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6088 userId); 6089 } 6090 return Collections.emptyList(); 6091 } 6092 } 6093 6094 @Override 6095 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6096 if (!sUserManager.exists(userId)) return null; 6097 flags = updateFlagsForResolve(flags, userId, intent); 6098 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6099 if (query != null) { 6100 if (query.size() >= 1) { 6101 // If there is more than one service with the same priority, 6102 // just arbitrarily pick the first one. 6103 return query.get(0); 6104 } 6105 } 6106 return null; 6107 } 6108 6109 @Override 6110 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6111 String resolvedType, int flags, int userId) { 6112 return new ParceledListSlice<>( 6113 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6114 } 6115 6116 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6117 String resolvedType, int flags, int userId) { 6118 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6119 flags = updateFlagsForResolve(flags, userId, intent); 6120 ComponentName comp = intent.getComponent(); 6121 if (comp == null) { 6122 if (intent.getSelector() != null) { 6123 intent = intent.getSelector(); 6124 comp = intent.getComponent(); 6125 } 6126 } 6127 if (comp != null) { 6128 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6129 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6130 if (si != null) { 6131 final ResolveInfo ri = new ResolveInfo(); 6132 ri.serviceInfo = si; 6133 list.add(ri); 6134 } 6135 return list; 6136 } 6137 6138 // reader 6139 synchronized (mPackages) { 6140 String pkgName = intent.getPackage(); 6141 if (pkgName == null) { 6142 return mServices.queryIntent(intent, resolvedType, flags, userId); 6143 } 6144 final PackageParser.Package pkg = mPackages.get(pkgName); 6145 if (pkg != null) { 6146 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6147 userId); 6148 } 6149 return Collections.emptyList(); 6150 } 6151 } 6152 6153 @Override 6154 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6155 String resolvedType, int flags, int userId) { 6156 return new ParceledListSlice<>( 6157 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6158 } 6159 6160 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6161 Intent intent, String resolvedType, int flags, int userId) { 6162 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6163 flags = updateFlagsForResolve(flags, userId, intent); 6164 ComponentName comp = intent.getComponent(); 6165 if (comp == null) { 6166 if (intent.getSelector() != null) { 6167 intent = intent.getSelector(); 6168 comp = intent.getComponent(); 6169 } 6170 } 6171 if (comp != null) { 6172 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6173 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6174 if (pi != null) { 6175 final ResolveInfo ri = new ResolveInfo(); 6176 ri.providerInfo = pi; 6177 list.add(ri); 6178 } 6179 return list; 6180 } 6181 6182 // reader 6183 synchronized (mPackages) { 6184 String pkgName = intent.getPackage(); 6185 if (pkgName == null) { 6186 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6187 } 6188 final PackageParser.Package pkg = mPackages.get(pkgName); 6189 if (pkg != null) { 6190 return mProviders.queryIntentForPackage( 6191 intent, resolvedType, flags, pkg.providers, userId); 6192 } 6193 return Collections.emptyList(); 6194 } 6195 } 6196 6197 @Override 6198 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6199 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6200 flags = updateFlagsForPackage(flags, userId, null); 6201 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6202 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6203 true /* requireFullPermission */, false /* checkShell */, 6204 "get installed packages"); 6205 6206 // writer 6207 synchronized (mPackages) { 6208 ArrayList<PackageInfo> list; 6209 if (listUninstalled) { 6210 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6211 for (PackageSetting ps : mSettings.mPackages.values()) { 6212 final PackageInfo pi; 6213 if (ps.pkg != null) { 6214 pi = generatePackageInfo(ps, flags, userId); 6215 } else { 6216 pi = generatePackageInfo(ps, flags, userId); 6217 } 6218 if (pi != null) { 6219 list.add(pi); 6220 } 6221 } 6222 } else { 6223 list = new ArrayList<PackageInfo>(mPackages.size()); 6224 for (PackageParser.Package p : mPackages.values()) { 6225 final PackageInfo pi = 6226 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6227 if (pi != null) { 6228 list.add(pi); 6229 } 6230 } 6231 } 6232 6233 return new ParceledListSlice<PackageInfo>(list); 6234 } 6235 } 6236 6237 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6238 String[] permissions, boolean[] tmp, int flags, int userId) { 6239 int numMatch = 0; 6240 final PermissionsState permissionsState = ps.getPermissionsState(); 6241 for (int i=0; i<permissions.length; i++) { 6242 final String permission = permissions[i]; 6243 if (permissionsState.hasPermission(permission, userId)) { 6244 tmp[i] = true; 6245 numMatch++; 6246 } else { 6247 tmp[i] = false; 6248 } 6249 } 6250 if (numMatch == 0) { 6251 return; 6252 } 6253 final PackageInfo pi; 6254 if (ps.pkg != null) { 6255 pi = generatePackageInfo(ps, flags, userId); 6256 } else { 6257 pi = generatePackageInfo(ps, flags, userId); 6258 } 6259 // The above might return null in cases of uninstalled apps or install-state 6260 // skew across users/profiles. 6261 if (pi != null) { 6262 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6263 if (numMatch == permissions.length) { 6264 pi.requestedPermissions = permissions; 6265 } else { 6266 pi.requestedPermissions = new String[numMatch]; 6267 numMatch = 0; 6268 for (int i=0; i<permissions.length; i++) { 6269 if (tmp[i]) { 6270 pi.requestedPermissions[numMatch] = permissions[i]; 6271 numMatch++; 6272 } 6273 } 6274 } 6275 } 6276 list.add(pi); 6277 } 6278 } 6279 6280 @Override 6281 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6282 String[] permissions, int flags, int userId) { 6283 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6284 flags = updateFlagsForPackage(flags, userId, permissions); 6285 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6286 6287 // writer 6288 synchronized (mPackages) { 6289 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6290 boolean[] tmpBools = new boolean[permissions.length]; 6291 if (listUninstalled) { 6292 for (PackageSetting ps : mSettings.mPackages.values()) { 6293 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6294 } 6295 } else { 6296 for (PackageParser.Package pkg : mPackages.values()) { 6297 PackageSetting ps = (PackageSetting)pkg.mExtras; 6298 if (ps != null) { 6299 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6300 userId); 6301 } 6302 } 6303 } 6304 6305 return new ParceledListSlice<PackageInfo>(list); 6306 } 6307 } 6308 6309 @Override 6310 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6311 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6312 flags = updateFlagsForApplication(flags, userId, null); 6313 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6314 6315 // writer 6316 synchronized (mPackages) { 6317 ArrayList<ApplicationInfo> list; 6318 if (listUninstalled) { 6319 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6320 for (PackageSetting ps : mSettings.mPackages.values()) { 6321 ApplicationInfo ai; 6322 if (ps.pkg != null) { 6323 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6324 ps.readUserState(userId), userId); 6325 } else { 6326 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6327 } 6328 if (ai != null) { 6329 list.add(ai); 6330 } 6331 } 6332 } else { 6333 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6334 for (PackageParser.Package p : mPackages.values()) { 6335 if (p.mExtras != null) { 6336 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6337 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6338 if (ai != null) { 6339 list.add(ai); 6340 } 6341 } 6342 } 6343 } 6344 6345 return new ParceledListSlice<ApplicationInfo>(list); 6346 } 6347 } 6348 6349 @Override 6350 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6351 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6352 return null; 6353 } 6354 6355 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6356 "getEphemeralApplications"); 6357 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6358 true /* requireFullPermission */, false /* checkShell */, 6359 "getEphemeralApplications"); 6360 synchronized (mPackages) { 6361 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6362 .getEphemeralApplicationsLPw(userId); 6363 if (ephemeralApps != null) { 6364 return new ParceledListSlice<>(ephemeralApps); 6365 } 6366 } 6367 return null; 6368 } 6369 6370 @Override 6371 public boolean isEphemeralApplication(String packageName, int userId) { 6372 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6373 true /* requireFullPermission */, false /* checkShell */, 6374 "isEphemeral"); 6375 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6376 return false; 6377 } 6378 6379 if (!isCallerSameApp(packageName)) { 6380 return false; 6381 } 6382 synchronized (mPackages) { 6383 PackageParser.Package pkg = mPackages.get(packageName); 6384 if (pkg != null) { 6385 return pkg.applicationInfo.isEphemeralApp(); 6386 } 6387 } 6388 return false; 6389 } 6390 6391 @Override 6392 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6393 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6394 return null; 6395 } 6396 6397 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6398 true /* requireFullPermission */, false /* checkShell */, 6399 "getCookie"); 6400 if (!isCallerSameApp(packageName)) { 6401 return null; 6402 } 6403 synchronized (mPackages) { 6404 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6405 packageName, userId); 6406 } 6407 } 6408 6409 @Override 6410 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6411 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6412 return true; 6413 } 6414 6415 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6416 true /* requireFullPermission */, true /* checkShell */, 6417 "setCookie"); 6418 if (!isCallerSameApp(packageName)) { 6419 return false; 6420 } 6421 synchronized (mPackages) { 6422 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6423 packageName, cookie, userId); 6424 } 6425 } 6426 6427 @Override 6428 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6429 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6430 return null; 6431 } 6432 6433 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6434 "getEphemeralApplicationIcon"); 6435 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6436 true /* requireFullPermission */, false /* checkShell */, 6437 "getEphemeralApplicationIcon"); 6438 synchronized (mPackages) { 6439 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6440 packageName, userId); 6441 } 6442 } 6443 6444 private boolean isCallerSameApp(String packageName) { 6445 PackageParser.Package pkg = mPackages.get(packageName); 6446 return pkg != null 6447 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6448 } 6449 6450 @Override 6451 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6452 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6453 } 6454 6455 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6456 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6457 6458 // reader 6459 synchronized (mPackages) { 6460 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6461 final int userId = UserHandle.getCallingUserId(); 6462 while (i.hasNext()) { 6463 final PackageParser.Package p = i.next(); 6464 if (p.applicationInfo == null) continue; 6465 6466 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6467 && !p.applicationInfo.isDirectBootAware(); 6468 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6469 && p.applicationInfo.isDirectBootAware(); 6470 6471 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6472 && (!mSafeMode || isSystemApp(p)) 6473 && (matchesUnaware || matchesAware)) { 6474 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6475 if (ps != null) { 6476 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6477 ps.readUserState(userId), userId); 6478 if (ai != null) { 6479 finalList.add(ai); 6480 } 6481 } 6482 } 6483 } 6484 } 6485 6486 return finalList; 6487 } 6488 6489 @Override 6490 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6491 if (!sUserManager.exists(userId)) return null; 6492 flags = updateFlagsForComponent(flags, userId, name); 6493 // reader 6494 synchronized (mPackages) { 6495 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6496 PackageSetting ps = provider != null 6497 ? mSettings.mPackages.get(provider.owner.packageName) 6498 : null; 6499 return ps != null 6500 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6501 ? PackageParser.generateProviderInfo(provider, flags, 6502 ps.readUserState(userId), userId) 6503 : null; 6504 } 6505 } 6506 6507 /** 6508 * @deprecated 6509 */ 6510 @Deprecated 6511 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6512 // reader 6513 synchronized (mPackages) { 6514 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6515 .entrySet().iterator(); 6516 final int userId = UserHandle.getCallingUserId(); 6517 while (i.hasNext()) { 6518 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6519 PackageParser.Provider p = entry.getValue(); 6520 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6521 6522 if (ps != null && p.syncable 6523 && (!mSafeMode || (p.info.applicationInfo.flags 6524 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6525 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6526 ps.readUserState(userId), userId); 6527 if (info != null) { 6528 outNames.add(entry.getKey()); 6529 outInfo.add(info); 6530 } 6531 } 6532 } 6533 } 6534 } 6535 6536 @Override 6537 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6538 int uid, int flags) { 6539 final int userId = processName != null ? UserHandle.getUserId(uid) 6540 : UserHandle.getCallingUserId(); 6541 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6542 flags = updateFlagsForComponent(flags, userId, processName); 6543 6544 ArrayList<ProviderInfo> finalList = null; 6545 // reader 6546 synchronized (mPackages) { 6547 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6548 while (i.hasNext()) { 6549 final PackageParser.Provider p = i.next(); 6550 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6551 if (ps != null && p.info.authority != null 6552 && (processName == null 6553 || (p.info.processName.equals(processName) 6554 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6555 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6556 if (finalList == null) { 6557 finalList = new ArrayList<ProviderInfo>(3); 6558 } 6559 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6560 ps.readUserState(userId), userId); 6561 if (info != null) { 6562 finalList.add(info); 6563 } 6564 } 6565 } 6566 } 6567 6568 if (finalList != null) { 6569 Collections.sort(finalList, mProviderInitOrderSorter); 6570 return new ParceledListSlice<ProviderInfo>(finalList); 6571 } 6572 6573 return ParceledListSlice.emptyList(); 6574 } 6575 6576 @Override 6577 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6578 // reader 6579 synchronized (mPackages) { 6580 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6581 return PackageParser.generateInstrumentationInfo(i, flags); 6582 } 6583 } 6584 6585 @Override 6586 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6587 String targetPackage, int flags) { 6588 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6589 } 6590 6591 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6592 int flags) { 6593 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6594 6595 // reader 6596 synchronized (mPackages) { 6597 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6598 while (i.hasNext()) { 6599 final PackageParser.Instrumentation p = i.next(); 6600 if (targetPackage == null 6601 || targetPackage.equals(p.info.targetPackage)) { 6602 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6603 flags); 6604 if (ii != null) { 6605 finalList.add(ii); 6606 } 6607 } 6608 } 6609 } 6610 6611 return finalList; 6612 } 6613 6614 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6615 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6616 if (overlays == null) { 6617 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6618 return; 6619 } 6620 for (PackageParser.Package opkg : overlays.values()) { 6621 // Not much to do if idmap fails: we already logged the error 6622 // and we certainly don't want to abort installation of pkg simply 6623 // because an overlay didn't fit properly. For these reasons, 6624 // ignore the return value of createIdmapForPackagePairLI. 6625 createIdmapForPackagePairLI(pkg, opkg); 6626 } 6627 } 6628 6629 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6630 PackageParser.Package opkg) { 6631 if (!opkg.mTrustedOverlay) { 6632 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6633 opkg.baseCodePath + ": overlay not trusted"); 6634 return false; 6635 } 6636 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6637 if (overlaySet == null) { 6638 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6639 opkg.baseCodePath + " but target package has no known overlays"); 6640 return false; 6641 } 6642 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6643 // TODO: generate idmap for split APKs 6644 try { 6645 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6646 } catch (InstallerException e) { 6647 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6648 + opkg.baseCodePath); 6649 return false; 6650 } 6651 PackageParser.Package[] overlayArray = 6652 overlaySet.values().toArray(new PackageParser.Package[0]); 6653 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6654 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6655 return p1.mOverlayPriority - p2.mOverlayPriority; 6656 } 6657 }; 6658 Arrays.sort(overlayArray, cmp); 6659 6660 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6661 int i = 0; 6662 for (PackageParser.Package p : overlayArray) { 6663 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6664 } 6665 return true; 6666 } 6667 6668 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6669 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 6670 try { 6671 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6672 } finally { 6673 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6674 } 6675 } 6676 6677 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6678 final File[] files = dir.listFiles(); 6679 if (ArrayUtils.isEmpty(files)) { 6680 Log.d(TAG, "No files in app dir " + dir); 6681 return; 6682 } 6683 6684 if (DEBUG_PACKAGE_SCANNING) { 6685 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6686 + " flags=0x" + Integer.toHexString(parseFlags)); 6687 } 6688 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 6689 mSeparateProcesses, mOnlyCore, mMetrics); 6690 6691 // Submit files for parsing in parallel 6692 int fileCount = 0; 6693 for (File file : files) { 6694 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6695 && !PackageInstallerService.isStageName(file.getName()); 6696 if (!isPackage) { 6697 // Ignore entries which are not packages 6698 continue; 6699 } 6700 parallelPackageParser.submit(file, parseFlags); 6701 fileCount++; 6702 } 6703 6704 // Process results one by one 6705 for (; fileCount > 0; fileCount--) { 6706 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 6707 Throwable throwable = parseResult.throwable; 6708 int errorCode = PackageManager.INSTALL_SUCCEEDED; 6709 6710 if (throwable == null) { 6711 try { 6712 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 6713 currentTime, null); 6714 } catch (PackageManagerException e) { 6715 errorCode = e.error; 6716 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 6717 } 6718 } else if (throwable instanceof PackageParser.PackageParserException) { 6719 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 6720 throwable; 6721 errorCode = e.error; 6722 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 6723 } else { 6724 throw new IllegalStateException("Unexpected exception occurred while parsing " 6725 + parseResult.scanFile, throwable); 6726 } 6727 6728 // Delete invalid userdata apps 6729 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6730 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 6731 logCriticalInfo(Log.WARN, 6732 "Deleting invalid package at " + parseResult.scanFile); 6733 removeCodePathLI(parseResult.scanFile); 6734 } 6735 } 6736 parallelPackageParser.close(); 6737 } 6738 6739 private static File getSettingsProblemFile() { 6740 File dataDir = Environment.getDataDirectory(); 6741 File systemDir = new File(dataDir, "system"); 6742 File fname = new File(systemDir, "uiderrors.txt"); 6743 return fname; 6744 } 6745 6746 static void reportSettingsProblem(int priority, String msg) { 6747 logCriticalInfo(priority, msg); 6748 } 6749 6750 static void logCriticalInfo(int priority, String msg) { 6751 Slog.println(priority, TAG, msg); 6752 EventLogTags.writePmCriticalInfo(msg); 6753 try { 6754 File fname = getSettingsProblemFile(); 6755 FileOutputStream out = new FileOutputStream(fname, true); 6756 PrintWriter pw = new FastPrintWriter(out); 6757 SimpleDateFormat formatter = new SimpleDateFormat(); 6758 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6759 pw.println(dateString + ": " + msg); 6760 pw.close(); 6761 FileUtils.setPermissions( 6762 fname.toString(), 6763 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6764 -1, -1); 6765 } catch (java.io.IOException e) { 6766 } 6767 } 6768 6769 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6770 if (srcFile.isDirectory()) { 6771 final File baseFile = new File(pkg.baseCodePath); 6772 long maxModifiedTime = baseFile.lastModified(); 6773 if (pkg.splitCodePaths != null) { 6774 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6775 final File splitFile = new File(pkg.splitCodePaths[i]); 6776 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6777 } 6778 } 6779 return maxModifiedTime; 6780 } 6781 return srcFile.lastModified(); 6782 } 6783 6784 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6785 final int policyFlags) throws PackageManagerException { 6786 // When upgrading from pre-N MR1, verify the package time stamp using the package 6787 // directory and not the APK file. 6788 final long lastModifiedTime = mIsPreNMR1Upgrade 6789 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 6790 if (ps != null 6791 && ps.codePath.equals(srcFile) 6792 && ps.timeStamp == lastModifiedTime 6793 && !isCompatSignatureUpdateNeeded(pkg) 6794 && !isRecoverSignatureUpdateNeeded(pkg)) { 6795 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6796 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6797 ArraySet<PublicKey> signingKs; 6798 synchronized (mPackages) { 6799 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6800 } 6801 if (ps.signatures.mSignatures != null 6802 && ps.signatures.mSignatures.length != 0 6803 && signingKs != null) { 6804 // Optimization: reuse the existing cached certificates 6805 // if the package appears to be unchanged. 6806 pkg.mSignatures = ps.signatures.mSignatures; 6807 pkg.mSigningKeys = signingKs; 6808 return; 6809 } 6810 6811 Slog.w(TAG, "PackageSetting for " + ps.name 6812 + " is missing signatures. Collecting certs again to recover them."); 6813 } else { 6814 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 6815 } 6816 6817 try { 6818 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 6819 PackageParser.collectCertificates(pkg, policyFlags); 6820 } catch (PackageParserException e) { 6821 throw PackageManagerException.from(e); 6822 } finally { 6823 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6824 } 6825 } 6826 6827 /** 6828 * Traces a package scan. 6829 * @see #scanPackageLI(File, int, int, long, UserHandle) 6830 */ 6831 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6832 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6833 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 6834 try { 6835 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6836 } finally { 6837 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6838 } 6839 } 6840 6841 /** 6842 * Scans a package and returns the newly parsed package. 6843 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6844 */ 6845 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6846 long currentTime, UserHandle user) throws PackageManagerException { 6847 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6848 PackageParser pp = new PackageParser(); 6849 pp.setSeparateProcesses(mSeparateProcesses); 6850 pp.setOnlyCoreApps(mOnlyCore); 6851 pp.setDisplayMetrics(mMetrics); 6852 6853 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6854 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6855 } 6856 6857 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6858 final PackageParser.Package pkg; 6859 try { 6860 pkg = pp.parsePackage(scanFile, parseFlags); 6861 } catch (PackageParserException e) { 6862 throw PackageManagerException.from(e); 6863 } finally { 6864 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6865 } 6866 6867 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6868 } 6869 6870 /** 6871 * Scans a package and returns the newly parsed package. 6872 * @throws PackageManagerException on a parse error. 6873 */ 6874 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6875 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6876 throws PackageManagerException { 6877 // If the package has children and this is the first dive in the function 6878 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6879 // packages (parent and children) would be successfully scanned before the 6880 // actual scan since scanning mutates internal state and we want to atomically 6881 // install the package and its children. 6882 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6883 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6884 scanFlags |= SCAN_CHECK_ONLY; 6885 } 6886 } else { 6887 scanFlags &= ~SCAN_CHECK_ONLY; 6888 } 6889 6890 // Scan the parent 6891 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6892 scanFlags, currentTime, user); 6893 6894 // Scan the children 6895 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6896 for (int i = 0; i < childCount; i++) { 6897 PackageParser.Package childPackage = pkg.childPackages.get(i); 6898 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6899 currentTime, user); 6900 } 6901 6902 6903 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6904 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6905 } 6906 6907 return scannedPkg; 6908 } 6909 6910 /** 6911 * Scans a package and returns the newly parsed package. 6912 * @throws PackageManagerException on a parse error. 6913 */ 6914 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6915 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6916 throws PackageManagerException { 6917 PackageSetting ps = null; 6918 PackageSetting updatedPkg; 6919 // reader 6920 synchronized (mPackages) { 6921 // Look to see if we already know about this package. 6922 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 6923 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6924 // This package has been renamed to its original name. Let's 6925 // use that. 6926 ps = mSettings.getPackageLPr(oldName); 6927 } 6928 // If there was no original package, see one for the real package name. 6929 if (ps == null) { 6930 ps = mSettings.getPackageLPr(pkg.packageName); 6931 } 6932 // Check to see if this package could be hiding/updating a system 6933 // package. Must look for it either under the original or real 6934 // package name depending on our state. 6935 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6936 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6937 6938 // If this is a package we don't know about on the system partition, we 6939 // may need to remove disabled child packages on the system partition 6940 // or may need to not add child packages if the parent apk is updated 6941 // on the data partition and no longer defines this child package. 6942 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6943 // If this is a parent package for an updated system app and this system 6944 // app got an OTA update which no longer defines some of the child packages 6945 // we have to prune them from the disabled system packages. 6946 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6947 if (disabledPs != null) { 6948 final int scannedChildCount = (pkg.childPackages != null) 6949 ? pkg.childPackages.size() : 0; 6950 final int disabledChildCount = disabledPs.childPackageNames != null 6951 ? disabledPs.childPackageNames.size() : 0; 6952 for (int i = 0; i < disabledChildCount; i++) { 6953 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6954 boolean disabledPackageAvailable = false; 6955 for (int j = 0; j < scannedChildCount; j++) { 6956 PackageParser.Package childPkg = pkg.childPackages.get(j); 6957 if (childPkg.packageName.equals(disabledChildPackageName)) { 6958 disabledPackageAvailable = true; 6959 break; 6960 } 6961 } 6962 if (!disabledPackageAvailable) { 6963 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6964 } 6965 } 6966 } 6967 } 6968 } 6969 6970 boolean updatedPkgBetter = false; 6971 // First check if this is a system package that may involve an update 6972 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6973 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6974 // it needs to drop FLAG_PRIVILEGED. 6975 if (locationIsPrivileged(scanFile)) { 6976 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6977 } else { 6978 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6979 } 6980 6981 if (ps != null && !ps.codePath.equals(scanFile)) { 6982 // The path has changed from what was last scanned... check the 6983 // version of the new path against what we have stored to determine 6984 // what to do. 6985 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6986 if (pkg.mVersionCode <= ps.versionCode) { 6987 // The system package has been updated and the code path does not match 6988 // Ignore entry. Skip it. 6989 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6990 + " ignored: updated version " + ps.versionCode 6991 + " better than this " + pkg.mVersionCode); 6992 if (!updatedPkg.codePath.equals(scanFile)) { 6993 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6994 + ps.name + " changing from " + updatedPkg.codePathString 6995 + " to " + scanFile); 6996 updatedPkg.codePath = scanFile; 6997 updatedPkg.codePathString = scanFile.toString(); 6998 updatedPkg.resourcePath = scanFile; 6999 updatedPkg.resourcePathString = scanFile.toString(); 7000 } 7001 updatedPkg.pkg = pkg; 7002 updatedPkg.versionCode = pkg.mVersionCode; 7003 7004 // Update the disabled system child packages to point to the package too. 7005 final int childCount = updatedPkg.childPackageNames != null 7006 ? updatedPkg.childPackageNames.size() : 0; 7007 for (int i = 0; i < childCount; i++) { 7008 String childPackageName = updatedPkg.childPackageNames.get(i); 7009 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7010 childPackageName); 7011 if (updatedChildPkg != null) { 7012 updatedChildPkg.pkg = pkg; 7013 updatedChildPkg.versionCode = pkg.mVersionCode; 7014 } 7015 } 7016 7017 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7018 + scanFile + " ignored: updated version " + ps.versionCode 7019 + " better than this " + pkg.mVersionCode); 7020 } else { 7021 // The current app on the system partition is better than 7022 // what we have updated to on the data partition; switch 7023 // back to the system partition version. 7024 // At this point, its safely assumed that package installation for 7025 // apps in system partition will go through. If not there won't be a working 7026 // version of the app 7027 // writer 7028 synchronized (mPackages) { 7029 // Just remove the loaded entries from package lists. 7030 mPackages.remove(ps.name); 7031 } 7032 7033 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7034 + " reverting from " + ps.codePathString 7035 + ": new version " + pkg.mVersionCode 7036 + " better than installed " + ps.versionCode); 7037 7038 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7039 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7040 synchronized (mInstallLock) { 7041 args.cleanUpResourcesLI(); 7042 } 7043 synchronized (mPackages) { 7044 mSettings.enableSystemPackageLPw(ps.name); 7045 } 7046 updatedPkgBetter = true; 7047 } 7048 } 7049 } 7050 7051 if (updatedPkg != null) { 7052 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7053 // initially 7054 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7055 7056 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7057 // flag set initially 7058 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7059 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7060 } 7061 } 7062 7063 // Verify certificates against what was last scanned 7064 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7065 7066 /* 7067 * A new system app appeared, but we already had a non-system one of the 7068 * same name installed earlier. 7069 */ 7070 boolean shouldHideSystemApp = false; 7071 if (updatedPkg == null && ps != null 7072 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7073 /* 7074 * Check to make sure the signatures match first. If they don't, 7075 * wipe the installed application and its data. 7076 */ 7077 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7078 != PackageManager.SIGNATURE_MATCH) { 7079 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7080 + " signatures don't match existing userdata copy; removing"); 7081 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7082 "scanPackageInternalLI")) { 7083 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7084 } 7085 ps = null; 7086 } else { 7087 /* 7088 * If the newly-added system app is an older version than the 7089 * already installed version, hide it. It will be scanned later 7090 * and re-added like an update. 7091 */ 7092 if (pkg.mVersionCode <= ps.versionCode) { 7093 shouldHideSystemApp = true; 7094 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7095 + " but new version " + pkg.mVersionCode + " better than installed " 7096 + ps.versionCode + "; hiding system"); 7097 } else { 7098 /* 7099 * The newly found system app is a newer version that the 7100 * one previously installed. Simply remove the 7101 * already-installed application and replace it with our own 7102 * while keeping the application data. 7103 */ 7104 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7105 + " reverting from " + ps.codePathString + ": new version " 7106 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7107 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7108 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7109 synchronized (mInstallLock) { 7110 args.cleanUpResourcesLI(); 7111 } 7112 } 7113 } 7114 } 7115 7116 // The apk is forward locked (not public) if its code and resources 7117 // are kept in different files. (except for app in either system or 7118 // vendor path). 7119 // TODO grab this value from PackageSettings 7120 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7121 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7122 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7123 } 7124 } 7125 7126 // TODO: extend to support forward-locked splits 7127 String resourcePath = null; 7128 String baseResourcePath = null; 7129 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7130 if (ps != null && ps.resourcePathString != null) { 7131 resourcePath = ps.resourcePathString; 7132 baseResourcePath = ps.resourcePathString; 7133 } else { 7134 // Should not happen at all. Just log an error. 7135 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7136 } 7137 } else { 7138 resourcePath = pkg.codePath; 7139 baseResourcePath = pkg.baseCodePath; 7140 } 7141 7142 // Set application objects path explicitly. 7143 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7144 pkg.setApplicationInfoCodePath(pkg.codePath); 7145 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7146 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7147 pkg.setApplicationInfoResourcePath(resourcePath); 7148 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7149 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7150 7151 // Note that we invoke the following method only if we are about to unpack an application 7152 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7153 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7154 7155 /* 7156 * If the system app should be overridden by a previously installed 7157 * data, hide the system app now and let the /data/app scan pick it up 7158 * again. 7159 */ 7160 if (shouldHideSystemApp) { 7161 synchronized (mPackages) { 7162 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7163 } 7164 } 7165 7166 return scannedPkg; 7167 } 7168 7169 private static String fixProcessName(String defProcessName, 7170 String processName) { 7171 if (processName == null) { 7172 return defProcessName; 7173 } 7174 return processName; 7175 } 7176 7177 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7178 throws PackageManagerException { 7179 if (pkgSetting.signatures.mSignatures != null) { 7180 // Already existing package. Make sure signatures match 7181 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7182 == PackageManager.SIGNATURE_MATCH; 7183 if (!match) { 7184 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7185 == PackageManager.SIGNATURE_MATCH; 7186 } 7187 if (!match) { 7188 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7189 == PackageManager.SIGNATURE_MATCH; 7190 } 7191 if (!match) { 7192 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7193 + pkg.packageName + " signatures do not match the " 7194 + "previously installed version; ignoring!"); 7195 } 7196 } 7197 7198 // Check for shared user signatures 7199 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7200 // Already existing package. Make sure signatures match 7201 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7202 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7203 if (!match) { 7204 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7205 == PackageManager.SIGNATURE_MATCH; 7206 } 7207 if (!match) { 7208 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7209 == PackageManager.SIGNATURE_MATCH; 7210 } 7211 if (!match) { 7212 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7213 "Package " + pkg.packageName 7214 + " has no signatures that match those in shared user " 7215 + pkgSetting.sharedUser.name + "; ignoring!"); 7216 } 7217 } 7218 } 7219 7220 /** 7221 * Enforces that only the system UID or root's UID can call a method exposed 7222 * via Binder. 7223 * 7224 * @param message used as message if SecurityException is thrown 7225 * @throws SecurityException if the caller is not system or root 7226 */ 7227 private static final void enforceSystemOrRoot(String message) { 7228 final int uid = Binder.getCallingUid(); 7229 if (uid != Process.SYSTEM_UID && uid != 0) { 7230 throw new SecurityException(message); 7231 } 7232 } 7233 7234 @Override 7235 public void performFstrimIfNeeded() { 7236 enforceSystemOrRoot("Only the system can request fstrim"); 7237 7238 // Before everything else, see whether we need to fstrim. 7239 try { 7240 IStorageManager sm = PackageHelper.getStorageManager(); 7241 if (sm != null) { 7242 boolean doTrim = false; 7243 final long interval = android.provider.Settings.Global.getLong( 7244 mContext.getContentResolver(), 7245 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7246 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7247 if (interval > 0) { 7248 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 7249 if (timeSinceLast > interval) { 7250 doTrim = true; 7251 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7252 + "; running immediately"); 7253 } 7254 } 7255 if (doTrim) { 7256 final boolean dexOptDialogShown; 7257 synchronized (mPackages) { 7258 dexOptDialogShown = mDexOptDialogShown; 7259 } 7260 if (!isFirstBoot() && dexOptDialogShown) { 7261 try { 7262 ActivityManager.getService().showBootMessage( 7263 mContext.getResources().getString( 7264 R.string.android_upgrading_fstrim), true); 7265 } catch (RemoteException e) { 7266 } 7267 } 7268 sm.runMaintenance(); 7269 } 7270 } else { 7271 Slog.e(TAG, "storageManager service unavailable!"); 7272 } 7273 } catch (RemoteException e) { 7274 // Can't happen; StorageManagerService is local 7275 } 7276 } 7277 7278 @Override 7279 public void updatePackagesIfNeeded() { 7280 enforceSystemOrRoot("Only the system can request package update"); 7281 7282 // We need to re-extract after an OTA. 7283 boolean causeUpgrade = isUpgrade(); 7284 7285 // First boot or factory reset. 7286 // Note: we also handle devices that are upgrading to N right now as if it is their 7287 // first boot, as they do not have profile data. 7288 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7289 7290 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7291 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7292 7293 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7294 return; 7295 } 7296 7297 List<PackageParser.Package> pkgs; 7298 synchronized (mPackages) { 7299 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7300 } 7301 7302 final long startTime = System.nanoTime(); 7303 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7304 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7305 7306 final int elapsedTimeSeconds = 7307 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7308 7309 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7310 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7311 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7312 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7313 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7314 } 7315 7316 /** 7317 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7318 * containing statistics about the invocation. The array consists of three elements, 7319 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7320 * and {@code numberOfPackagesFailed}. 7321 */ 7322 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7323 String compilerFilter) { 7324 7325 int numberOfPackagesVisited = 0; 7326 int numberOfPackagesOptimized = 0; 7327 int numberOfPackagesSkipped = 0; 7328 int numberOfPackagesFailed = 0; 7329 final int numberOfPackagesToDexopt = pkgs.size(); 7330 7331 for (PackageParser.Package pkg : pkgs) { 7332 numberOfPackagesVisited++; 7333 7334 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7335 if (DEBUG_DEXOPT) { 7336 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7337 } 7338 numberOfPackagesSkipped++; 7339 continue; 7340 } 7341 7342 if (DEBUG_DEXOPT) { 7343 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7344 numberOfPackagesToDexopt + ": " + pkg.packageName); 7345 } 7346 7347 if (showDialog) { 7348 try { 7349 ActivityManager.getService().showBootMessage( 7350 mContext.getResources().getString(R.string.android_upgrading_apk, 7351 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7352 } catch (RemoteException e) { 7353 } 7354 synchronized (mPackages) { 7355 mDexOptDialogShown = true; 7356 } 7357 } 7358 7359 // If the OTA updates a system app which was previously preopted to a non-preopted state 7360 // the app might end up being verified at runtime. That's because by default the apps 7361 // are verify-profile but for preopted apps there's no profile. 7362 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7363 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7364 // filter (by default interpret-only). 7365 // Note that at this stage unused apps are already filtered. 7366 if (isSystemApp(pkg) && 7367 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7368 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7369 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7370 } 7371 7372 // If the OTA updates a system app which was previously preopted to a non-preopted state 7373 // the app might end up being verified at runtime. That's because by default the apps 7374 // are verify-profile but for preopted apps there's no profile. 7375 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7376 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7377 // filter (by default interpret-only). 7378 // Note that at this stage unused apps are already filtered. 7379 if (isSystemApp(pkg) && 7380 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7381 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7382 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7383 } 7384 7385 // checkProfiles is false to avoid merging profiles during boot which 7386 // might interfere with background compilation (b/28612421). 7387 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7388 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7389 // trade-off worth doing to save boot time work. 7390 int dexOptStatus = performDexOptTraced(pkg.packageName, 7391 false /* checkProfiles */, 7392 compilerFilter, 7393 false /* force */); 7394 switch (dexOptStatus) { 7395 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7396 numberOfPackagesOptimized++; 7397 break; 7398 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7399 numberOfPackagesSkipped++; 7400 break; 7401 case PackageDexOptimizer.DEX_OPT_FAILED: 7402 numberOfPackagesFailed++; 7403 break; 7404 default: 7405 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7406 break; 7407 } 7408 } 7409 7410 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7411 numberOfPackagesFailed }; 7412 } 7413 7414 @Override 7415 public void notifyPackageUse(String packageName, int reason) { 7416 synchronized (mPackages) { 7417 PackageParser.Package p = mPackages.get(packageName); 7418 if (p == null) { 7419 return; 7420 } 7421 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7422 } 7423 } 7424 7425 // TODO: this is not used nor needed. Delete it. 7426 @Override 7427 public boolean performDexOptIfNeeded(String packageName) { 7428 int dexOptStatus = performDexOptTraced(packageName, 7429 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7430 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7431 } 7432 7433 @Override 7434 public boolean performDexOpt(String packageName, 7435 boolean checkProfiles, int compileReason, boolean force) { 7436 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7437 getCompilerFilterForReason(compileReason), force); 7438 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7439 } 7440 7441 @Override 7442 public boolean performDexOptMode(String packageName, 7443 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7444 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7445 targetCompilerFilter, force); 7446 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7447 } 7448 7449 private int performDexOptTraced(String packageName, 7450 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7451 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7452 try { 7453 return performDexOptInternal(packageName, checkProfiles, 7454 targetCompilerFilter, force); 7455 } finally { 7456 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7457 } 7458 } 7459 7460 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7461 // if the package can now be considered up to date for the given filter. 7462 private int performDexOptInternal(String packageName, 7463 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7464 PackageParser.Package p; 7465 synchronized (mPackages) { 7466 p = mPackages.get(packageName); 7467 if (p == null) { 7468 // Package could not be found. Report failure. 7469 return PackageDexOptimizer.DEX_OPT_FAILED; 7470 } 7471 mPackageUsage.maybeWriteAsync(mPackages); 7472 mCompilerStats.maybeWriteAsync(); 7473 } 7474 long callingId = Binder.clearCallingIdentity(); 7475 try { 7476 synchronized (mInstallLock) { 7477 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7478 targetCompilerFilter, force); 7479 } 7480 } finally { 7481 Binder.restoreCallingIdentity(callingId); 7482 } 7483 } 7484 7485 public ArraySet<String> getOptimizablePackages() { 7486 ArraySet<String> pkgs = new ArraySet<String>(); 7487 synchronized (mPackages) { 7488 for (PackageParser.Package p : mPackages.values()) { 7489 if (PackageDexOptimizer.canOptimizePackage(p)) { 7490 pkgs.add(p.packageName); 7491 } 7492 } 7493 } 7494 return pkgs; 7495 } 7496 7497 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7498 boolean checkProfiles, String targetCompilerFilter, 7499 boolean force) { 7500 // Select the dex optimizer based on the force parameter. 7501 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7502 // allocate an object here. 7503 PackageDexOptimizer pdo = force 7504 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7505 : mPackageDexOptimizer; 7506 7507 // Optimize all dependencies first. Note: we ignore the return value and march on 7508 // on errors. 7509 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7510 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7511 if (!deps.isEmpty()) { 7512 for (PackageParser.Package depPackage : deps) { 7513 // TODO: Analyze and investigate if we (should) profile libraries. 7514 // Currently this will do a full compilation of the library by default. 7515 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7516 false /* checkProfiles */, 7517 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7518 getOrCreateCompilerPackageStats(depPackage)); 7519 } 7520 } 7521 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7522 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7523 } 7524 7525 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7526 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7527 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7528 Set<String> collectedNames = new HashSet<>(); 7529 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7530 7531 retValue.remove(p); 7532 7533 return retValue; 7534 } else { 7535 return Collections.emptyList(); 7536 } 7537 } 7538 7539 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7540 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7541 if (!collectedNames.contains(p.packageName)) { 7542 collectedNames.add(p.packageName); 7543 collected.add(p); 7544 7545 if (p.usesLibraries != null) { 7546 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7547 } 7548 if (p.usesOptionalLibraries != null) { 7549 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7550 collectedNames); 7551 } 7552 } 7553 } 7554 7555 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7556 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7557 for (String libName : libs) { 7558 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7559 if (libPkg != null) { 7560 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7561 } 7562 } 7563 } 7564 7565 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7566 synchronized (mPackages) { 7567 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7568 if (lib != null && lib.apk != null) { 7569 return mPackages.get(lib.apk); 7570 } 7571 } 7572 return null; 7573 } 7574 7575 public void shutdown() { 7576 mPackageUsage.writeNow(mPackages); 7577 mCompilerStats.writeNow(); 7578 } 7579 7580 @Override 7581 public void dumpProfiles(String packageName) { 7582 PackageParser.Package pkg; 7583 synchronized (mPackages) { 7584 pkg = mPackages.get(packageName); 7585 if (pkg == null) { 7586 throw new IllegalArgumentException("Unknown package: " + packageName); 7587 } 7588 } 7589 /* Only the shell, root, or the app user should be able to dump profiles. */ 7590 int callingUid = Binder.getCallingUid(); 7591 if (callingUid != Process.SHELL_UID && 7592 callingUid != Process.ROOT_UID && 7593 callingUid != pkg.applicationInfo.uid) { 7594 throw new SecurityException("dumpProfiles"); 7595 } 7596 7597 synchronized (mInstallLock) { 7598 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7599 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7600 try { 7601 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7602 String gid = Integer.toString(sharedGid); 7603 String codePaths = TextUtils.join(";", allCodePaths); 7604 mInstaller.dumpProfiles(gid, packageName, codePaths); 7605 } catch (InstallerException e) { 7606 Slog.w(TAG, "Failed to dump profiles", e); 7607 } 7608 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7609 } 7610 } 7611 7612 @Override 7613 public void forceDexOpt(String packageName) { 7614 enforceSystemOrRoot("forceDexOpt"); 7615 7616 PackageParser.Package pkg; 7617 synchronized (mPackages) { 7618 pkg = mPackages.get(packageName); 7619 if (pkg == null) { 7620 throw new IllegalArgumentException("Unknown package: " + packageName); 7621 } 7622 } 7623 7624 synchronized (mInstallLock) { 7625 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7626 7627 // Whoever is calling forceDexOpt wants a fully compiled package. 7628 // Don't use profiles since that may cause compilation to be skipped. 7629 final int res = performDexOptInternalWithDependenciesLI(pkg, 7630 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7631 true /* force */); 7632 7633 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7634 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7635 throw new IllegalStateException("Failed to dexopt: " + res); 7636 } 7637 } 7638 } 7639 7640 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7641 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7642 Slog.w(TAG, "Unable to update from " + oldPkg.name 7643 + " to " + newPkg.packageName 7644 + ": old package not in system partition"); 7645 return false; 7646 } else if (mPackages.get(oldPkg.name) != null) { 7647 Slog.w(TAG, "Unable to update from " + oldPkg.name 7648 + " to " + newPkg.packageName 7649 + ": old package still exists"); 7650 return false; 7651 } 7652 return true; 7653 } 7654 7655 void removeCodePathLI(File codePath) { 7656 if (codePath.isDirectory()) { 7657 try { 7658 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7659 } catch (InstallerException e) { 7660 Slog.w(TAG, "Failed to remove code path", e); 7661 } 7662 } else { 7663 codePath.delete(); 7664 } 7665 } 7666 7667 private int[] resolveUserIds(int userId) { 7668 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7669 } 7670 7671 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7672 if (pkg == null) { 7673 Slog.wtf(TAG, "Package was null!", new Throwable()); 7674 return; 7675 } 7676 clearAppDataLeafLIF(pkg, userId, flags); 7677 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7678 for (int i = 0; i < childCount; i++) { 7679 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7680 } 7681 } 7682 7683 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7684 final PackageSetting ps; 7685 synchronized (mPackages) { 7686 ps = mSettings.mPackages.get(pkg.packageName); 7687 } 7688 for (int realUserId : resolveUserIds(userId)) { 7689 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7690 try { 7691 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7692 ceDataInode); 7693 } catch (InstallerException e) { 7694 Slog.w(TAG, String.valueOf(e)); 7695 } 7696 } 7697 } 7698 7699 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7700 if (pkg == null) { 7701 Slog.wtf(TAG, "Package was null!", new Throwable()); 7702 return; 7703 } 7704 destroyAppDataLeafLIF(pkg, userId, flags); 7705 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7706 for (int i = 0; i < childCount; i++) { 7707 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7708 } 7709 } 7710 7711 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7712 final PackageSetting ps; 7713 synchronized (mPackages) { 7714 ps = mSettings.mPackages.get(pkg.packageName); 7715 } 7716 for (int realUserId : resolveUserIds(userId)) { 7717 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7718 try { 7719 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7720 ceDataInode); 7721 } catch (InstallerException e) { 7722 Slog.w(TAG, String.valueOf(e)); 7723 } 7724 } 7725 } 7726 7727 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7728 if (pkg == null) { 7729 Slog.wtf(TAG, "Package was null!", new Throwable()); 7730 return; 7731 } 7732 destroyAppProfilesLeafLIF(pkg); 7733 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7734 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7735 for (int i = 0; i < childCount; i++) { 7736 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7737 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7738 true /* removeBaseMarker */); 7739 } 7740 } 7741 7742 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7743 boolean removeBaseMarker) { 7744 if (pkg.isForwardLocked()) { 7745 return; 7746 } 7747 7748 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7749 try { 7750 path = PackageManagerServiceUtils.realpath(new File(path)); 7751 } catch (IOException e) { 7752 // TODO: Should we return early here ? 7753 Slog.w(TAG, "Failed to get canonical path", e); 7754 continue; 7755 } 7756 7757 final String useMarker = path.replace('/', '@'); 7758 for (int realUserId : resolveUserIds(userId)) { 7759 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7760 if (removeBaseMarker) { 7761 File foreignUseMark = new File(profileDir, useMarker); 7762 if (foreignUseMark.exists()) { 7763 if (!foreignUseMark.delete()) { 7764 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7765 + pkg.packageName); 7766 } 7767 } 7768 } 7769 7770 File[] markers = profileDir.listFiles(); 7771 if (markers != null) { 7772 final String searchString = "@" + pkg.packageName + "@"; 7773 // We also delete all markers that contain the package name we're 7774 // uninstalling. These are associated with secondary dex-files belonging 7775 // to the package. Reconstructing the path of these dex files is messy 7776 // in general. 7777 for (File marker : markers) { 7778 if (marker.getName().indexOf(searchString) > 0) { 7779 if (!marker.delete()) { 7780 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7781 + pkg.packageName); 7782 } 7783 } 7784 } 7785 } 7786 } 7787 } 7788 } 7789 7790 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7791 try { 7792 mInstaller.destroyAppProfiles(pkg.packageName); 7793 } catch (InstallerException e) { 7794 Slog.w(TAG, String.valueOf(e)); 7795 } 7796 } 7797 7798 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7799 if (pkg == null) { 7800 Slog.wtf(TAG, "Package was null!", new Throwable()); 7801 return; 7802 } 7803 clearAppProfilesLeafLIF(pkg); 7804 // We don't remove the base foreign use marker when clearing profiles because 7805 // we will rename it when the app is updated. Unlike the actual profile contents, 7806 // the foreign use marker is good across installs. 7807 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7808 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7809 for (int i = 0; i < childCount; i++) { 7810 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7811 } 7812 } 7813 7814 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7815 try { 7816 mInstaller.clearAppProfiles(pkg.packageName); 7817 } catch (InstallerException e) { 7818 Slog.w(TAG, String.valueOf(e)); 7819 } 7820 } 7821 7822 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7823 long lastUpdateTime) { 7824 // Set parent install/update time 7825 PackageSetting ps = (PackageSetting) pkg.mExtras; 7826 if (ps != null) { 7827 ps.firstInstallTime = firstInstallTime; 7828 ps.lastUpdateTime = lastUpdateTime; 7829 } 7830 // Set children install/update time 7831 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7832 for (int i = 0; i < childCount; i++) { 7833 PackageParser.Package childPkg = pkg.childPackages.get(i); 7834 ps = (PackageSetting) childPkg.mExtras; 7835 if (ps != null) { 7836 ps.firstInstallTime = firstInstallTime; 7837 ps.lastUpdateTime = lastUpdateTime; 7838 } 7839 } 7840 } 7841 7842 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7843 PackageParser.Package changingLib) { 7844 if (file.path != null) { 7845 usesLibraryFiles.add(file.path); 7846 return; 7847 } 7848 PackageParser.Package p = mPackages.get(file.apk); 7849 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7850 // If we are doing this while in the middle of updating a library apk, 7851 // then we need to make sure to use that new apk for determining the 7852 // dependencies here. (We haven't yet finished committing the new apk 7853 // to the package manager state.) 7854 if (p == null || p.packageName.equals(changingLib.packageName)) { 7855 p = changingLib; 7856 } 7857 } 7858 if (p != null) { 7859 usesLibraryFiles.addAll(p.getAllCodePaths()); 7860 } 7861 } 7862 7863 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 7864 PackageParser.Package changingLib) throws PackageManagerException { 7865 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7866 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7867 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7868 for (int i=0; i<N; i++) { 7869 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7870 if (file == null) { 7871 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7872 "Package " + pkg.packageName + " requires unavailable shared library " 7873 + pkg.usesLibraries.get(i) + "; failing!"); 7874 } 7875 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 7876 } 7877 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7878 for (int i=0; i<N; i++) { 7879 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7880 if (file == null) { 7881 Slog.w(TAG, "Package " + pkg.packageName 7882 + " desires unavailable shared library " 7883 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7884 } else { 7885 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 7886 } 7887 } 7888 N = usesLibraryFiles.size(); 7889 if (N > 0) { 7890 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7891 } else { 7892 pkg.usesLibraryFiles = null; 7893 } 7894 } 7895 } 7896 7897 private static boolean hasString(List<String> list, List<String> which) { 7898 if (list == null) { 7899 return false; 7900 } 7901 for (int i=list.size()-1; i>=0; i--) { 7902 for (int j=which.size()-1; j>=0; j--) { 7903 if (which.get(j).equals(list.get(i))) { 7904 return true; 7905 } 7906 } 7907 } 7908 return false; 7909 } 7910 7911 private void updateAllSharedLibrariesLPw() { 7912 for (PackageParser.Package pkg : mPackages.values()) { 7913 try { 7914 updateSharedLibrariesLPr(pkg, null); 7915 } catch (PackageManagerException e) { 7916 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7917 } 7918 } 7919 } 7920 7921 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7922 PackageParser.Package changingPkg) { 7923 ArrayList<PackageParser.Package> res = null; 7924 for (PackageParser.Package pkg : mPackages.values()) { 7925 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7926 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7927 if (res == null) { 7928 res = new ArrayList<PackageParser.Package>(); 7929 } 7930 res.add(pkg); 7931 try { 7932 updateSharedLibrariesLPr(pkg, changingPkg); 7933 } catch (PackageManagerException e) { 7934 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7935 } 7936 } 7937 } 7938 return res; 7939 } 7940 7941 /** 7942 * Derive the value of the {@code cpuAbiOverride} based on the provided 7943 * value and an optional stored value from the package settings. 7944 */ 7945 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7946 String cpuAbiOverride = null; 7947 7948 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7949 cpuAbiOverride = null; 7950 } else if (abiOverride != null) { 7951 cpuAbiOverride = abiOverride; 7952 } else if (settings != null) { 7953 cpuAbiOverride = settings.cpuAbiOverrideString; 7954 } 7955 7956 return cpuAbiOverride; 7957 } 7958 7959 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7960 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7961 throws PackageManagerException { 7962 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7963 // If the package has children and this is the first dive in the function 7964 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7965 // whether all packages (parent and children) would be successfully scanned 7966 // before the actual scan since scanning mutates internal state and we want 7967 // to atomically install the package and its children. 7968 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7969 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7970 scanFlags |= SCAN_CHECK_ONLY; 7971 } 7972 } else { 7973 scanFlags &= ~SCAN_CHECK_ONLY; 7974 } 7975 7976 final PackageParser.Package scannedPkg; 7977 try { 7978 // Scan the parent 7979 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7980 // Scan the children 7981 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7982 for (int i = 0; i < childCount; i++) { 7983 PackageParser.Package childPkg = pkg.childPackages.get(i); 7984 scanPackageLI(childPkg, policyFlags, 7985 scanFlags, currentTime, user); 7986 } 7987 } finally { 7988 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7989 } 7990 7991 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7992 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7993 } 7994 7995 return scannedPkg; 7996 } 7997 7998 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7999 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8000 boolean success = false; 8001 try { 8002 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8003 currentTime, user); 8004 success = true; 8005 return res; 8006 } finally { 8007 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8008 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8009 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8010 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8011 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8012 } 8013 } 8014 } 8015 8016 /** 8017 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8018 */ 8019 private static boolean apkHasCode(String fileName) { 8020 StrictJarFile jarFile = null; 8021 try { 8022 jarFile = new StrictJarFile(fileName, 8023 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8024 return jarFile.findEntry("classes.dex") != null; 8025 } catch (IOException ignore) { 8026 } finally { 8027 try { 8028 if (jarFile != null) { 8029 jarFile.close(); 8030 } 8031 } catch (IOException ignore) {} 8032 } 8033 return false; 8034 } 8035 8036 /** 8037 * Enforces code policy for the package. This ensures that if an APK has 8038 * declared hasCode="true" in its manifest that the APK actually contains 8039 * code. 8040 * 8041 * @throws PackageManagerException If bytecode could not be found when it should exist 8042 */ 8043 private static void assertCodePolicy(PackageParser.Package pkg) 8044 throws PackageManagerException { 8045 final boolean shouldHaveCode = 8046 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8047 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8048 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8049 "Package " + pkg.baseCodePath + " code is missing"); 8050 } 8051 8052 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8053 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8054 final boolean splitShouldHaveCode = 8055 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8056 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8057 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8058 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8059 } 8060 } 8061 } 8062 } 8063 8064 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8065 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8066 throws PackageManagerException { 8067 if (DEBUG_PACKAGE_SCANNING) { 8068 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8069 Log.d(TAG, "Scanning package " + pkg.packageName); 8070 } 8071 8072 applyPolicy(pkg, policyFlags); 8073 8074 assertPackageIsValid(pkg, policyFlags, scanFlags); 8075 8076 // Initialize package source and resource directories 8077 final File scanFile = new File(pkg.codePath); 8078 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8079 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8080 8081 SharedUserSetting suid = null; 8082 PackageSetting pkgSetting = null; 8083 8084 // Getting the package setting may have a side-effect, so if we 8085 // are only checking if scan would succeed, stash a copy of the 8086 // old setting to restore at the end. 8087 PackageSetting nonMutatedPs = null; 8088 8089 // We keep references to the derived CPU Abis from settings in oder to reuse 8090 // them in the case where we're not upgrading or booting for the first time. 8091 String primaryCpuAbiFromSettings = null; 8092 String secondaryCpuAbiFromSettings = null; 8093 8094 // writer 8095 synchronized (mPackages) { 8096 if (pkg.mSharedUserId != null) { 8097 // SIDE EFFECTS; may potentially allocate a new shared user 8098 suid = mSettings.getSharedUserLPw( 8099 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 8100 if (DEBUG_PACKAGE_SCANNING) { 8101 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8102 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8103 + "): packages=" + suid.packages); 8104 } 8105 } 8106 8107 // Check if we are renaming from an original package name. 8108 PackageSetting origPackage = null; 8109 String realName = null; 8110 if (pkg.mOriginalPackages != null) { 8111 // This package may need to be renamed to a previously 8112 // installed name. Let's check on that... 8113 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8114 if (pkg.mOriginalPackages.contains(renamed)) { 8115 // This package had originally been installed as the 8116 // original name, and we have already taken care of 8117 // transitioning to the new one. Just update the new 8118 // one to continue using the old name. 8119 realName = pkg.mRealPackage; 8120 if (!pkg.packageName.equals(renamed)) { 8121 // Callers into this function may have already taken 8122 // care of renaming the package; only do it here if 8123 // it is not already done. 8124 pkg.setPackageName(renamed); 8125 } 8126 } else { 8127 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8128 if ((origPackage = mSettings.getPackageLPr( 8129 pkg.mOriginalPackages.get(i))) != null) { 8130 // We do have the package already installed under its 8131 // original name... should we use it? 8132 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8133 // New package is not compatible with original. 8134 origPackage = null; 8135 continue; 8136 } else if (origPackage.sharedUser != null) { 8137 // Make sure uid is compatible between packages. 8138 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8139 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8140 + " to " + pkg.packageName + ": old uid " 8141 + origPackage.sharedUser.name 8142 + " differs from " + pkg.mSharedUserId); 8143 origPackage = null; 8144 continue; 8145 } 8146 // TODO: Add case when shared user id is added [b/28144775] 8147 } else { 8148 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8149 + pkg.packageName + " to old name " + origPackage.name); 8150 } 8151 break; 8152 } 8153 } 8154 } 8155 } 8156 8157 if (mTransferedPackages.contains(pkg.packageName)) { 8158 Slog.w(TAG, "Package " + pkg.packageName 8159 + " was transferred to another, but its .apk remains"); 8160 } 8161 8162 // See comments in nonMutatedPs declaration 8163 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8164 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8165 if (foundPs != null) { 8166 nonMutatedPs = new PackageSetting(foundPs); 8167 } 8168 } 8169 8170 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 8171 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8172 if (foundPs != null) { 8173 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 8174 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 8175 } 8176 } 8177 8178 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8179 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 8180 PackageManagerService.reportSettingsProblem(Log.WARN, 8181 "Package " + pkg.packageName + " shared user changed from " 8182 + (pkgSetting.sharedUser != null 8183 ? pkgSetting.sharedUser.name : "<nothing>") 8184 + " to " 8185 + (suid != null ? suid.name : "<nothing>") 8186 + "; replacing with new"); 8187 pkgSetting = null; 8188 } 8189 final PackageSetting oldPkgSetting = 8190 pkgSetting == null ? null : new PackageSetting(pkgSetting); 8191 final PackageSetting disabledPkgSetting = 8192 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8193 if (pkgSetting == null) { 8194 final String parentPackageName = (pkg.parentPackage != null) 8195 ? pkg.parentPackage.packageName : null; 8196 // REMOVE SharedUserSetting from method; update in a separate call 8197 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 8198 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 8199 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 8200 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 8201 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 8202 true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(), 8203 UserManagerService.getInstance()); 8204 // SIDE EFFECTS; updates system state; move elsewhere 8205 if (origPackage != null) { 8206 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 8207 } 8208 mSettings.addUserToSettingLPw(pkgSetting); 8209 } else { 8210 // REMOVE SharedUserSetting from method; update in a separate call. 8211 // 8212 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 8213 // secondaryCpuAbi are not known at this point so we always update them 8214 // to null here, only to reset them at a later point. 8215 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 8216 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 8217 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 8218 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 8219 UserManagerService.getInstance()); 8220 } 8221 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 8222 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 8223 8224 // SIDE EFFECTS; modifies system state; move elsewhere 8225 if (pkgSetting.origPackage != null) { 8226 // If we are first transitioning from an original package, 8227 // fix up the new package's name now. We need to do this after 8228 // looking up the package under its new name, so getPackageLP 8229 // can take care of fiddling things correctly. 8230 pkg.setPackageName(origPackage.name); 8231 8232 // File a report about this. 8233 String msg = "New package " + pkgSetting.realName 8234 + " renamed to replace old package " + pkgSetting.name; 8235 reportSettingsProblem(Log.WARN, msg); 8236 8237 // Make a note of it. 8238 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8239 mTransferedPackages.add(origPackage.name); 8240 } 8241 8242 // No longer need to retain this. 8243 pkgSetting.origPackage = null; 8244 } 8245 8246 // SIDE EFFECTS; modifies system state; move elsewhere 8247 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8248 // Make a note of it. 8249 mTransferedPackages.add(pkg.packageName); 8250 } 8251 8252 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8253 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8254 } 8255 8256 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8257 // Check all shared libraries and map to their actual file path. 8258 // We only do this here for apps not on a system dir, because those 8259 // are the only ones that can fail an install due to this. We 8260 // will take care of the system apps by updating all of their 8261 // library paths after the scan is done. 8262 updateSharedLibrariesLPr(pkg, null); 8263 } 8264 8265 if (mFoundPolicyFile) { 8266 SELinuxMMAC.assignSeinfoValue(pkg); 8267 } 8268 8269 pkg.applicationInfo.uid = pkgSetting.appId; 8270 pkg.mExtras = pkgSetting; 8271 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8272 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8273 // We just determined the app is signed correctly, so bring 8274 // over the latest parsed certs. 8275 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8276 } else { 8277 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8278 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8279 "Package " + pkg.packageName + " upgrade keys do not match the " 8280 + "previously installed version"); 8281 } else { 8282 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8283 String msg = "System package " + pkg.packageName 8284 + " signature changed; retaining data."; 8285 reportSettingsProblem(Log.WARN, msg); 8286 } 8287 } 8288 } else { 8289 try { 8290 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 8291 verifySignaturesLP(pkgSetting, pkg); 8292 // We just determined the app is signed correctly, so bring 8293 // over the latest parsed certs. 8294 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8295 } catch (PackageManagerException e) { 8296 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8297 throw e; 8298 } 8299 // The signature has changed, but this package is in the system 8300 // image... let's recover! 8301 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8302 // However... if this package is part of a shared user, but it 8303 // doesn't match the signature of the shared user, let's fail. 8304 // What this means is that you can't change the signatures 8305 // associated with an overall shared user, which doesn't seem all 8306 // that unreasonable. 8307 if (pkgSetting.sharedUser != null) { 8308 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8309 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8310 throw new PackageManagerException( 8311 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8312 "Signature mismatch for shared user: " 8313 + pkgSetting.sharedUser); 8314 } 8315 } 8316 // File a report about this. 8317 String msg = "System package " + pkg.packageName 8318 + " signature changed; retaining data."; 8319 reportSettingsProblem(Log.WARN, msg); 8320 } 8321 } 8322 8323 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8324 // This package wants to adopt ownership of permissions from 8325 // another package. 8326 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8327 final String origName = pkg.mAdoptPermissions.get(i); 8328 final PackageSetting orig = mSettings.getPackageLPr(origName); 8329 if (orig != null) { 8330 if (verifyPackageUpdateLPr(orig, pkg)) { 8331 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8332 + pkg.packageName); 8333 // SIDE EFFECTS; updates permissions system state; move elsewhere 8334 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8335 } 8336 } 8337 } 8338 } 8339 } 8340 8341 pkg.applicationInfo.processName = fixProcessName( 8342 pkg.applicationInfo.packageName, 8343 pkg.applicationInfo.processName); 8344 8345 if (pkg != mPlatformPackage) { 8346 // Get all of our default paths setup 8347 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8348 } 8349 8350 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8351 8352 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8353 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 8354 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 8355 derivePackageAbi( 8356 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 8357 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8358 8359 // Some system apps still use directory structure for native libraries 8360 // in which case we might end up not detecting abi solely based on apk 8361 // structure. Try to detect abi based on directory structure. 8362 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8363 pkg.applicationInfo.primaryCpuAbi == null) { 8364 setBundledAppAbisAndRoots(pkg, pkgSetting); 8365 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8366 } 8367 } else { 8368 // This is not a first boot or an upgrade, don't bother deriving the 8369 // ABI during the scan. Instead, trust the value that was stored in the 8370 // package setting. 8371 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 8372 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 8373 8374 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8375 8376 if (DEBUG_ABI_SELECTION) { 8377 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 8378 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 8379 pkg.applicationInfo.secondaryCpuAbi); 8380 } 8381 } 8382 } else { 8383 if ((scanFlags & SCAN_MOVE) != 0) { 8384 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8385 // but we already have this packages package info in the PackageSetting. We just 8386 // use that and derive the native library path based on the new codepath. 8387 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8388 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8389 } 8390 8391 // Set native library paths again. For moves, the path will be updated based on the 8392 // ABIs we've determined above. For non-moves, the path will be updated based on the 8393 // ABIs we determined during compilation, but the path will depend on the final 8394 // package path (after the rename away from the stage path). 8395 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8396 } 8397 8398 // This is a special case for the "system" package, where the ABI is 8399 // dictated by the zygote configuration (and init.rc). We should keep track 8400 // of this ABI so that we can deal with "normal" applications that run under 8401 // the same UID correctly. 8402 if (mPlatformPackage == pkg) { 8403 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8404 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8405 } 8406 8407 // If there's a mismatch between the abi-override in the package setting 8408 // and the abiOverride specified for the install. Warn about this because we 8409 // would've already compiled the app without taking the package setting into 8410 // account. 8411 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8412 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8413 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8414 " for package " + pkg.packageName); 8415 } 8416 } 8417 8418 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8419 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8420 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8421 8422 // Copy the derived override back to the parsed package, so that we can 8423 // update the package settings accordingly. 8424 pkg.cpuAbiOverride = cpuAbiOverride; 8425 8426 if (DEBUG_ABI_SELECTION) { 8427 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8428 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8429 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8430 } 8431 8432 // Push the derived path down into PackageSettings so we know what to 8433 // clean up at uninstall time. 8434 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8435 8436 if (DEBUG_ABI_SELECTION) { 8437 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8438 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8439 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8440 } 8441 8442 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 8443 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8444 // We don't do this here during boot because we can do it all 8445 // at once after scanning all existing packages. 8446 // 8447 // We also do this *before* we perform dexopt on this package, so that 8448 // we can avoid redundant dexopts, and also to make sure we've got the 8449 // code and package path correct. 8450 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 8451 } 8452 8453 if (mFactoryTest && pkg.requestedPermissions.contains( 8454 android.Manifest.permission.FACTORY_TEST)) { 8455 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8456 } 8457 8458 if (isSystemApp(pkg)) { 8459 pkgSetting.isOrphaned = true; 8460 } 8461 8462 // Take care of first install / last update times. 8463 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8464 if (currentTime != 0) { 8465 if (pkgSetting.firstInstallTime == 0) { 8466 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8467 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 8468 pkgSetting.lastUpdateTime = currentTime; 8469 } 8470 } else if (pkgSetting.firstInstallTime == 0) { 8471 // We need *something*. Take time time stamp of the file. 8472 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8473 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8474 if (scanFileTime != pkgSetting.timeStamp) { 8475 // A package on the system image has changed; consider this 8476 // to be an update. 8477 pkgSetting.lastUpdateTime = scanFileTime; 8478 } 8479 } 8480 pkgSetting.setTimeStamp(scanFileTime); 8481 8482 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8483 if (nonMutatedPs != null) { 8484 synchronized (mPackages) { 8485 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8486 } 8487 } 8488 } else { 8489 // Modify state for the given package setting 8490 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 8491 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 8492 } 8493 return pkg; 8494 } 8495 8496 /** 8497 * Applies policy to the parsed package based upon the given policy flags. 8498 * Ensures the package is in a good state. 8499 * <p> 8500 * Implementation detail: This method must NOT have any side effect. It would 8501 * ideally be static, but, it requires locks to read system state. 8502 */ 8503 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 8504 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8505 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8506 if (pkg.applicationInfo.isDirectBootAware()) { 8507 // we're direct boot aware; set for all components 8508 for (PackageParser.Service s : pkg.services) { 8509 s.info.encryptionAware = s.info.directBootAware = true; 8510 } 8511 for (PackageParser.Provider p : pkg.providers) { 8512 p.info.encryptionAware = p.info.directBootAware = true; 8513 } 8514 for (PackageParser.Activity a : pkg.activities) { 8515 a.info.encryptionAware = a.info.directBootAware = true; 8516 } 8517 for (PackageParser.Activity r : pkg.receivers) { 8518 r.info.encryptionAware = r.info.directBootAware = true; 8519 } 8520 } 8521 } else { 8522 // Only allow system apps to be flagged as core apps. 8523 pkg.coreApp = false; 8524 // clear flags not applicable to regular apps 8525 pkg.applicationInfo.privateFlags &= 8526 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8527 pkg.applicationInfo.privateFlags &= 8528 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8529 } 8530 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8531 8532 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8533 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8534 } 8535 8536 if (!isSystemApp(pkg)) { 8537 // Only system apps can use these features. 8538 pkg.mOriginalPackages = null; 8539 pkg.mRealPackage = null; 8540 pkg.mAdoptPermissions = null; 8541 } 8542 } 8543 8544 /** 8545 * Asserts the parsed package is valid according to teh given policy. If the 8546 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 8547 * <p> 8548 * Implementation detail: This method must NOT have any side effects. It would 8549 * ideally be static, but, it requires locks to read system state. 8550 * 8551 * @throws PackageManagerException If the package fails any of the validation checks 8552 */ 8553 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 8554 throws PackageManagerException { 8555 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8556 assertCodePolicy(pkg); 8557 } 8558 8559 if (pkg.applicationInfo.getCodePath() == null || 8560 pkg.applicationInfo.getResourcePath() == null) { 8561 // Bail out. The resource and code paths haven't been set. 8562 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8563 "Code and resource paths haven't been set correctly"); 8564 } 8565 8566 // Make sure we're not adding any bogus keyset info 8567 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8568 ksms.assertScannedPackageValid(pkg); 8569 8570 synchronized (mPackages) { 8571 // The special "android" package can only be defined once 8572 if (pkg.packageName.equals("android")) { 8573 if (mAndroidApplication != null) { 8574 Slog.w(TAG, "*************************************************"); 8575 Slog.w(TAG, "Core android package being redefined. Skipping."); 8576 Slog.w(TAG, " codePath=" + pkg.codePath); 8577 Slog.w(TAG, "*************************************************"); 8578 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8579 "Core android package being redefined. Skipping."); 8580 } 8581 } 8582 8583 // A package name must be unique; don't allow duplicates 8584 if (mPackages.containsKey(pkg.packageName) 8585 || mSharedLibraries.containsKey(pkg.packageName)) { 8586 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8587 "Application package " + pkg.packageName 8588 + " already installed. Skipping duplicate."); 8589 } 8590 8591 // Only privileged apps and updated privileged apps can add child packages. 8592 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8593 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8594 throw new PackageManagerException("Only privileged apps can add child " 8595 + "packages. Ignoring package " + pkg.packageName); 8596 } 8597 final int childCount = pkg.childPackages.size(); 8598 for (int i = 0; i < childCount; i++) { 8599 PackageParser.Package childPkg = pkg.childPackages.get(i); 8600 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8601 childPkg.packageName)) { 8602 throw new PackageManagerException("Can't override child of " 8603 + "another disabled app. Ignoring package " + pkg.packageName); 8604 } 8605 } 8606 } 8607 8608 // If we're only installing presumed-existing packages, require that the 8609 // scanned APK is both already known and at the path previously established 8610 // for it. Previously unknown packages we pick up normally, but if we have an 8611 // a priori expectation about this package's install presence, enforce it. 8612 // With a singular exception for new system packages. When an OTA contains 8613 // a new system package, we allow the codepath to change from a system location 8614 // to the user-installed location. If we don't allow this change, any newer, 8615 // user-installed version of the application will be ignored. 8616 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8617 if (mExpectingBetter.containsKey(pkg.packageName)) { 8618 logCriticalInfo(Log.WARN, 8619 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8620 } else { 8621 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 8622 if (known != null) { 8623 if (DEBUG_PACKAGE_SCANNING) { 8624 Log.d(TAG, "Examining " + pkg.codePath 8625 + " and requiring known paths " + known.codePathString 8626 + " & " + known.resourcePathString); 8627 } 8628 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8629 || !pkg.applicationInfo.getResourcePath().equals( 8630 known.resourcePathString)) { 8631 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8632 "Application package " + pkg.packageName 8633 + " found at " + pkg.applicationInfo.getCodePath() 8634 + " but expected at " + known.codePathString 8635 + "; ignoring."); 8636 } 8637 } 8638 } 8639 } 8640 8641 // Verify that this new package doesn't have any content providers 8642 // that conflict with existing packages. Only do this if the 8643 // package isn't already installed, since we don't want to break 8644 // things that are installed. 8645 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8646 final int N = pkg.providers.size(); 8647 int i; 8648 for (i=0; i<N; i++) { 8649 PackageParser.Provider p = pkg.providers.get(i); 8650 if (p.info.authority != null) { 8651 String names[] = p.info.authority.split(";"); 8652 for (int j = 0; j < names.length; j++) { 8653 if (mProvidersByAuthority.containsKey(names[j])) { 8654 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8655 final String otherPackageName = 8656 ((other != null && other.getComponentName() != null) ? 8657 other.getComponentName().getPackageName() : "?"); 8658 throw new PackageManagerException( 8659 INSTALL_FAILED_CONFLICTING_PROVIDER, 8660 "Can't install because provider name " + names[j] 8661 + " (in package " + pkg.applicationInfo.packageName 8662 + ") is already used by " + otherPackageName); 8663 } 8664 } 8665 } 8666 } 8667 } 8668 } 8669 } 8670 8671 /** 8672 * Adds a scanned package to the system. When this method is finished, the package will 8673 * be available for query, resolution, etc... 8674 */ 8675 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 8676 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 8677 final String pkgName = pkg.packageName; 8678 if (mCustomResolverComponentName != null && 8679 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8680 setUpCustomResolverActivity(pkg); 8681 } 8682 8683 if (pkg.packageName.equals("android")) { 8684 synchronized (mPackages) { 8685 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8686 // Set up information for our fall-back user intent resolution activity. 8687 mPlatformPackage = pkg; 8688 pkg.mVersionCode = mSdkVersion; 8689 mAndroidApplication = pkg.applicationInfo; 8690 8691 if (!mResolverReplaced) { 8692 mResolveActivity.applicationInfo = mAndroidApplication; 8693 mResolveActivity.name = ResolverActivity.class.getName(); 8694 mResolveActivity.packageName = mAndroidApplication.packageName; 8695 mResolveActivity.processName = "system:ui"; 8696 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8697 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8698 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8699 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8700 mResolveActivity.exported = true; 8701 mResolveActivity.enabled = true; 8702 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8703 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8704 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8705 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8706 | ActivityInfo.CONFIG_ORIENTATION 8707 | ActivityInfo.CONFIG_KEYBOARD 8708 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8709 mResolveInfo.activityInfo = mResolveActivity; 8710 mResolveInfo.priority = 0; 8711 mResolveInfo.preferredOrder = 0; 8712 mResolveInfo.match = 0; 8713 mResolveComponentName = new ComponentName( 8714 mAndroidApplication.packageName, mResolveActivity.name); 8715 } 8716 } 8717 } 8718 } 8719 8720 ArrayList<PackageParser.Package> clientLibPkgs = null; 8721 // writer 8722 synchronized (mPackages) { 8723 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8724 // Only system apps can add new shared libraries. 8725 if (pkg.libraryNames != null) { 8726 for (int i=0; i<pkg.libraryNames.size(); i++) { 8727 String name = pkg.libraryNames.get(i); 8728 boolean allowed = false; 8729 if (pkg.isUpdatedSystemApp()) { 8730 // New library entries can only be added through the 8731 // system image. This is important to get rid of a lot 8732 // of nasty edge cases: for example if we allowed a non- 8733 // system update of the app to add a library, then uninstalling 8734 // the update would make the library go away, and assumptions 8735 // we made such as through app install filtering would now 8736 // have allowed apps on the device which aren't compatible 8737 // with it. Better to just have the restriction here, be 8738 // conservative, and create many fewer cases that can negatively 8739 // impact the user experience. 8740 final PackageSetting sysPs = mSettings 8741 .getDisabledSystemPkgLPr(pkg.packageName); 8742 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8743 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8744 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8745 allowed = true; 8746 break; 8747 } 8748 } 8749 } 8750 } else { 8751 allowed = true; 8752 } 8753 if (allowed) { 8754 if (!mSharedLibraries.containsKey(name)) { 8755 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8756 } else if (!name.equals(pkg.packageName)) { 8757 Slog.w(TAG, "Package " + pkg.packageName + " library " 8758 + name + " already exists; skipping"); 8759 } 8760 } else { 8761 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8762 + name + " that is not declared on system image; skipping"); 8763 } 8764 } 8765 if ((scanFlags & SCAN_BOOTING) == 0) { 8766 // If we are not booting, we need to update any applications 8767 // that are clients of our shared library. If we are booting, 8768 // this will all be done once the scan is complete. 8769 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8770 } 8771 } 8772 } 8773 } 8774 8775 if ((scanFlags & SCAN_BOOTING) != 0) { 8776 // No apps can run during boot scan, so they don't need to be frozen 8777 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8778 // Caller asked to not kill app, so it's probably not frozen 8779 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8780 // Caller asked us to ignore frozen check for some reason; they 8781 // probably didn't know the package name 8782 } else { 8783 // We're doing major surgery on this package, so it better be frozen 8784 // right now to keep it from launching 8785 checkPackageFrozen(pkgName); 8786 } 8787 8788 // Also need to kill any apps that are dependent on the library. 8789 if (clientLibPkgs != null) { 8790 for (int i=0; i<clientLibPkgs.size(); i++) { 8791 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8792 killApplication(clientPkg.applicationInfo.packageName, 8793 clientPkg.applicationInfo.uid, "update lib"); 8794 } 8795 } 8796 8797 // writer 8798 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8799 8800 boolean createIdmapFailed = false; 8801 synchronized (mPackages) { 8802 // We don't expect installation to fail beyond this point 8803 8804 if (pkgSetting.pkg != null) { 8805 // Note that |user| might be null during the initial boot scan. If a codePath 8806 // for an app has changed during a boot scan, it's due to an app update that's 8807 // part of the system partition and marker changes must be applied to all users. 8808 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 8809 final int[] userIds = resolveUserIds(userId); 8810 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 8811 } 8812 8813 // Add the new setting to mSettings 8814 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8815 // Add the new setting to mPackages 8816 mPackages.put(pkg.applicationInfo.packageName, pkg); 8817 // Make sure we don't accidentally delete its data. 8818 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8819 while (iter.hasNext()) { 8820 PackageCleanItem item = iter.next(); 8821 if (pkgName.equals(item.packageName)) { 8822 iter.remove(); 8823 } 8824 } 8825 8826 // Add the package's KeySets to the global KeySetManagerService 8827 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8828 ksms.addScannedPackageLPw(pkg); 8829 8830 int N = pkg.providers.size(); 8831 StringBuilder r = null; 8832 int i; 8833 for (i=0; i<N; i++) { 8834 PackageParser.Provider p = pkg.providers.get(i); 8835 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8836 p.info.processName); 8837 mProviders.addProvider(p); 8838 p.syncable = p.info.isSyncable; 8839 if (p.info.authority != null) { 8840 String names[] = p.info.authority.split(";"); 8841 p.info.authority = null; 8842 for (int j = 0; j < names.length; j++) { 8843 if (j == 1 && p.syncable) { 8844 // We only want the first authority for a provider to possibly be 8845 // syncable, so if we already added this provider using a different 8846 // authority clear the syncable flag. We copy the provider before 8847 // changing it because the mProviders object contains a reference 8848 // to a provider that we don't want to change. 8849 // Only do this for the second authority since the resulting provider 8850 // object can be the same for all future authorities for this provider. 8851 p = new PackageParser.Provider(p); 8852 p.syncable = false; 8853 } 8854 if (!mProvidersByAuthority.containsKey(names[j])) { 8855 mProvidersByAuthority.put(names[j], p); 8856 if (p.info.authority == null) { 8857 p.info.authority = names[j]; 8858 } else { 8859 p.info.authority = p.info.authority + ";" + names[j]; 8860 } 8861 if (DEBUG_PACKAGE_SCANNING) { 8862 if (chatty) 8863 Log.d(TAG, "Registered content provider: " + names[j] 8864 + ", className = " + p.info.name + ", isSyncable = " 8865 + p.info.isSyncable); 8866 } 8867 } else { 8868 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8869 Slog.w(TAG, "Skipping provider name " + names[j] + 8870 " (in package " + pkg.applicationInfo.packageName + 8871 "): name already used by " 8872 + ((other != null && other.getComponentName() != null) 8873 ? other.getComponentName().getPackageName() : "?")); 8874 } 8875 } 8876 } 8877 if (chatty) { 8878 if (r == null) { 8879 r = new StringBuilder(256); 8880 } else { 8881 r.append(' '); 8882 } 8883 r.append(p.info.name); 8884 } 8885 } 8886 if (r != null) { 8887 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8888 } 8889 8890 N = pkg.services.size(); 8891 r = null; 8892 for (i=0; i<N; i++) { 8893 PackageParser.Service s = pkg.services.get(i); 8894 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8895 s.info.processName); 8896 mServices.addService(s); 8897 if (chatty) { 8898 if (r == null) { 8899 r = new StringBuilder(256); 8900 } else { 8901 r.append(' '); 8902 } 8903 r.append(s.info.name); 8904 } 8905 } 8906 if (r != null) { 8907 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8908 } 8909 8910 N = pkg.receivers.size(); 8911 r = null; 8912 for (i=0; i<N; i++) { 8913 PackageParser.Activity a = pkg.receivers.get(i); 8914 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8915 a.info.processName); 8916 mReceivers.addActivity(a, "receiver"); 8917 if (chatty) { 8918 if (r == null) { 8919 r = new StringBuilder(256); 8920 } else { 8921 r.append(' '); 8922 } 8923 r.append(a.info.name); 8924 } 8925 } 8926 if (r != null) { 8927 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8928 } 8929 8930 N = pkg.activities.size(); 8931 r = null; 8932 for (i=0; i<N; i++) { 8933 PackageParser.Activity a = pkg.activities.get(i); 8934 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8935 a.info.processName); 8936 mActivities.addActivity(a, "activity"); 8937 if (chatty) { 8938 if (r == null) { 8939 r = new StringBuilder(256); 8940 } else { 8941 r.append(' '); 8942 } 8943 r.append(a.info.name); 8944 } 8945 } 8946 if (r != null) { 8947 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8948 } 8949 8950 N = pkg.permissionGroups.size(); 8951 r = null; 8952 for (i=0; i<N; i++) { 8953 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8954 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8955 final String curPackageName = cur == null ? null : cur.info.packageName; 8956 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 8957 if (cur == null || isPackageUpdate) { 8958 mPermissionGroups.put(pg.info.name, pg); 8959 if (chatty) { 8960 if (r == null) { 8961 r = new StringBuilder(256); 8962 } else { 8963 r.append(' '); 8964 } 8965 if (isPackageUpdate) { 8966 r.append("UPD:"); 8967 } 8968 r.append(pg.info.name); 8969 } 8970 } else { 8971 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8972 + pg.info.packageName + " ignored: original from " 8973 + cur.info.packageName); 8974 if (chatty) { 8975 if (r == null) { 8976 r = new StringBuilder(256); 8977 } else { 8978 r.append(' '); 8979 } 8980 r.append("DUP:"); 8981 r.append(pg.info.name); 8982 } 8983 } 8984 } 8985 if (r != null) { 8986 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8987 } 8988 8989 N = pkg.permissions.size(); 8990 r = null; 8991 for (i=0; i<N; i++) { 8992 PackageParser.Permission p = pkg.permissions.get(i); 8993 8994 // Assume by default that we did not install this permission into the system. 8995 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8996 8997 // Now that permission groups have a special meaning, we ignore permission 8998 // groups for legacy apps to prevent unexpected behavior. In particular, 8999 // permissions for one app being granted to someone just becase they happen 9000 // to be in a group defined by another app (before this had no implications). 9001 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 9002 p.group = mPermissionGroups.get(p.info.group); 9003 // Warn for a permission in an unknown group. 9004 if (p.info.group != null && p.group == null) { 9005 Slog.w(TAG, "Permission " + p.info.name + " from package " 9006 + p.info.packageName + " in an unknown group " + p.info.group); 9007 } 9008 } 9009 9010 ArrayMap<String, BasePermission> permissionMap = 9011 p.tree ? mSettings.mPermissionTrees 9012 : mSettings.mPermissions; 9013 BasePermission bp = permissionMap.get(p.info.name); 9014 9015 // Allow system apps to redefine non-system permissions 9016 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 9017 final boolean currentOwnerIsSystem = (bp.perm != null 9018 && isSystemApp(bp.perm.owner)); 9019 if (isSystemApp(p.owner)) { 9020 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 9021 // It's a built-in permission and no owner, take ownership now 9022 bp.packageSetting = pkgSetting; 9023 bp.perm = p; 9024 bp.uid = pkg.applicationInfo.uid; 9025 bp.sourcePackage = p.info.packageName; 9026 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9027 } else if (!currentOwnerIsSystem) { 9028 String msg = "New decl " + p.owner + " of permission " 9029 + p.info.name + " is system; overriding " + bp.sourcePackage; 9030 reportSettingsProblem(Log.WARN, msg); 9031 bp = null; 9032 } 9033 } 9034 } 9035 9036 if (bp == null) { 9037 bp = new BasePermission(p.info.name, p.info.packageName, 9038 BasePermission.TYPE_NORMAL); 9039 permissionMap.put(p.info.name, bp); 9040 } 9041 9042 if (bp.perm == null) { 9043 if (bp.sourcePackage == null 9044 || bp.sourcePackage.equals(p.info.packageName)) { 9045 BasePermission tree = findPermissionTreeLP(p.info.name); 9046 if (tree == null 9047 || tree.sourcePackage.equals(p.info.packageName)) { 9048 bp.packageSetting = pkgSetting; 9049 bp.perm = p; 9050 bp.uid = pkg.applicationInfo.uid; 9051 bp.sourcePackage = p.info.packageName; 9052 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9053 if (chatty) { 9054 if (r == null) { 9055 r = new StringBuilder(256); 9056 } else { 9057 r.append(' '); 9058 } 9059 r.append(p.info.name); 9060 } 9061 } else { 9062 Slog.w(TAG, "Permission " + p.info.name + " from package " 9063 + p.info.packageName + " ignored: base tree " 9064 + tree.name + " is from package " 9065 + tree.sourcePackage); 9066 } 9067 } else { 9068 Slog.w(TAG, "Permission " + p.info.name + " from package " 9069 + p.info.packageName + " ignored: original from " 9070 + bp.sourcePackage); 9071 } 9072 } else if (chatty) { 9073 if (r == null) { 9074 r = new StringBuilder(256); 9075 } else { 9076 r.append(' '); 9077 } 9078 r.append("DUP:"); 9079 r.append(p.info.name); 9080 } 9081 if (bp.perm == p) { 9082 bp.protectionLevel = p.info.protectionLevel; 9083 } 9084 } 9085 9086 if (r != null) { 9087 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 9088 } 9089 9090 N = pkg.instrumentation.size(); 9091 r = null; 9092 for (i=0; i<N; i++) { 9093 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9094 a.info.packageName = pkg.applicationInfo.packageName; 9095 a.info.sourceDir = pkg.applicationInfo.sourceDir; 9096 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 9097 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 9098 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 9099 a.info.dataDir = pkg.applicationInfo.dataDir; 9100 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 9101 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 9102 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 9103 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 9104 mInstrumentation.put(a.getComponentName(), a); 9105 if (chatty) { 9106 if (r == null) { 9107 r = new StringBuilder(256); 9108 } else { 9109 r.append(' '); 9110 } 9111 r.append(a.info.name); 9112 } 9113 } 9114 if (r != null) { 9115 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9116 } 9117 9118 if (pkg.protectedBroadcasts != null) { 9119 N = pkg.protectedBroadcasts.size(); 9120 for (i=0; i<N; i++) { 9121 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9122 } 9123 } 9124 9125 // Create idmap files for pairs of (packages, overlay packages). 9126 // Note: "android", ie framework-res.apk, is handled by native layers. 9127 if (pkg.mOverlayTarget != null) { 9128 // This is an overlay package. 9129 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9130 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9131 mOverlays.put(pkg.mOverlayTarget, 9132 new ArrayMap<String, PackageParser.Package>()); 9133 } 9134 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9135 map.put(pkg.packageName, pkg); 9136 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9137 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9138 createIdmapFailed = true; 9139 } 9140 } 9141 } else if (mOverlays.containsKey(pkg.packageName) && 9142 !pkg.packageName.equals("android")) { 9143 // This is a regular package, with one or more known overlay packages. 9144 createIdmapsForPackageLI(pkg); 9145 } 9146 } 9147 9148 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9149 9150 if (createIdmapFailed) { 9151 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9152 "scanPackageLI failed to createIdmap"); 9153 } 9154 } 9155 9156 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9157 PackageParser.Package update, int[] userIds) { 9158 if (existing.applicationInfo == null || update.applicationInfo == null) { 9159 // This isn't due to an app installation. 9160 return; 9161 } 9162 9163 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9164 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9165 9166 // The codePath hasn't changed, so there's nothing for us to do. 9167 if (Objects.equals(oldCodePath, newCodePath)) { 9168 return; 9169 } 9170 9171 File canonicalNewCodePath; 9172 try { 9173 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9174 } catch (IOException e) { 9175 Slog.w(TAG, "Failed to get canonical path.", e); 9176 return; 9177 } 9178 9179 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9180 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9181 // that the last component of the path (i.e, the name) doesn't need canonicalization 9182 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9183 // but may change in the future. Hopefully this function won't exist at that point. 9184 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9185 oldCodePath.getName()); 9186 9187 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9188 // with "@". 9189 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9190 if (!oldMarkerPrefix.endsWith("@")) { 9191 oldMarkerPrefix += "@"; 9192 } 9193 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9194 if (!newMarkerPrefix.endsWith("@")) { 9195 newMarkerPrefix += "@"; 9196 } 9197 9198 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9199 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9200 for (String updatedPath : updatedPaths) { 9201 String updatedPathName = new File(updatedPath).getName(); 9202 markerSuffixes.add(updatedPathName.replace('/', '@')); 9203 } 9204 9205 for (int userId : userIds) { 9206 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9207 9208 for (String markerSuffix : markerSuffixes) { 9209 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9210 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9211 if (oldForeignUseMark.exists()) { 9212 try { 9213 Os.rename(oldForeignUseMark.getAbsolutePath(), 9214 newForeignUseMark.getAbsolutePath()); 9215 } catch (ErrnoException e) { 9216 Slog.w(TAG, "Failed to rename foreign use marker", e); 9217 oldForeignUseMark.delete(); 9218 } 9219 } 9220 } 9221 } 9222 } 9223 9224 /** 9225 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9226 * is derived purely on the basis of the contents of {@code scanFile} and 9227 * {@code cpuAbiOverride}. 9228 * 9229 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9230 */ 9231 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9232 String cpuAbiOverride, boolean extractLibs, 9233 File appLib32InstallDir) 9234 throws PackageManagerException { 9235 // Give ourselves some initial paths; we'll come back for another 9236 // pass once we've determined ABI below. 9237 setNativeLibraryPaths(pkg, appLib32InstallDir); 9238 9239 // We would never need to extract libs for forward-locked and external packages, 9240 // since the container service will do it for us. We shouldn't attempt to 9241 // extract libs from system app when it was not updated. 9242 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9243 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9244 extractLibs = false; 9245 } 9246 9247 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9248 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9249 9250 NativeLibraryHelper.Handle handle = null; 9251 try { 9252 handle = NativeLibraryHelper.Handle.create(pkg); 9253 // TODO(multiArch): This can be null for apps that didn't go through the 9254 // usual installation process. We can calculate it again, like we 9255 // do during install time. 9256 // 9257 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9258 // unnecessary. 9259 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9260 9261 // Null out the abis so that they can be recalculated. 9262 pkg.applicationInfo.primaryCpuAbi = null; 9263 pkg.applicationInfo.secondaryCpuAbi = null; 9264 if (isMultiArch(pkg.applicationInfo)) { 9265 // Warn if we've set an abiOverride for multi-lib packages.. 9266 // By definition, we need to copy both 32 and 64 bit libraries for 9267 // such packages. 9268 if (pkg.cpuAbiOverride != null 9269 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9270 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9271 } 9272 9273 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9274 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9275 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9276 if (extractLibs) { 9277 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9278 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9279 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9280 useIsaSpecificSubdirs); 9281 } else { 9282 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9283 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9284 } 9285 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9286 } 9287 9288 maybeThrowExceptionForMultiArchCopy( 9289 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9290 9291 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9292 if (extractLibs) { 9293 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9294 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9295 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9296 useIsaSpecificSubdirs); 9297 } else { 9298 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9299 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9300 } 9301 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9302 } 9303 9304 maybeThrowExceptionForMultiArchCopy( 9305 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9306 9307 if (abi64 >= 0) { 9308 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9309 } 9310 9311 if (abi32 >= 0) { 9312 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9313 if (abi64 >= 0) { 9314 if (pkg.use32bitAbi) { 9315 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9316 pkg.applicationInfo.primaryCpuAbi = abi; 9317 } else { 9318 pkg.applicationInfo.secondaryCpuAbi = abi; 9319 } 9320 } else { 9321 pkg.applicationInfo.primaryCpuAbi = abi; 9322 } 9323 } 9324 9325 } else { 9326 String[] abiList = (cpuAbiOverride != null) ? 9327 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9328 9329 // Enable gross and lame hacks for apps that are built with old 9330 // SDK tools. We must scan their APKs for renderscript bitcode and 9331 // not launch them if it's present. Don't bother checking on devices 9332 // that don't have 64 bit support. 9333 boolean needsRenderScriptOverride = false; 9334 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9335 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9336 abiList = Build.SUPPORTED_32_BIT_ABIS; 9337 needsRenderScriptOverride = true; 9338 } 9339 9340 final int copyRet; 9341 if (extractLibs) { 9342 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9343 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9344 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9345 } else { 9346 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9347 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9348 } 9349 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9350 9351 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9352 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9353 "Error unpackaging native libs for app, errorCode=" + copyRet); 9354 } 9355 9356 if (copyRet >= 0) { 9357 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9358 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9359 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9360 } else if (needsRenderScriptOverride) { 9361 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9362 } 9363 } 9364 } catch (IOException ioe) { 9365 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9366 } finally { 9367 IoUtils.closeQuietly(handle); 9368 } 9369 9370 // Now that we've calculated the ABIs and determined if it's an internal app, 9371 // we will go ahead and populate the nativeLibraryPath. 9372 setNativeLibraryPaths(pkg, appLib32InstallDir); 9373 } 9374 9375 /** 9376 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9377 * i.e, so that all packages can be run inside a single process if required. 9378 * 9379 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9380 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9381 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9382 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9383 * updating a package that belongs to a shared user. 9384 * 9385 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9386 * adds unnecessary complexity. 9387 */ 9388 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9389 PackageParser.Package scannedPackage) { 9390 String requiredInstructionSet = null; 9391 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9392 requiredInstructionSet = VMRuntime.getInstructionSet( 9393 scannedPackage.applicationInfo.primaryCpuAbi); 9394 } 9395 9396 PackageSetting requirer = null; 9397 for (PackageSetting ps : packagesForUser) { 9398 // If packagesForUser contains scannedPackage, we skip it. This will happen 9399 // when scannedPackage is an update of an existing package. Without this check, 9400 // we will never be able to change the ABI of any package belonging to a shared 9401 // user, even if it's compatible with other packages. 9402 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9403 if (ps.primaryCpuAbiString == null) { 9404 continue; 9405 } 9406 9407 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9408 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9409 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9410 // this but there's not much we can do. 9411 String errorMessage = "Instruction set mismatch, " 9412 + ((requirer == null) ? "[caller]" : requirer) 9413 + " requires " + requiredInstructionSet + " whereas " + ps 9414 + " requires " + instructionSet; 9415 Slog.w(TAG, errorMessage); 9416 } 9417 9418 if (requiredInstructionSet == null) { 9419 requiredInstructionSet = instructionSet; 9420 requirer = ps; 9421 } 9422 } 9423 } 9424 9425 if (requiredInstructionSet != null) { 9426 String adjustedAbi; 9427 if (requirer != null) { 9428 // requirer != null implies that either scannedPackage was null or that scannedPackage 9429 // did not require an ABI, in which case we have to adjust scannedPackage to match 9430 // the ABI of the set (which is the same as requirer's ABI) 9431 adjustedAbi = requirer.primaryCpuAbiString; 9432 if (scannedPackage != null) { 9433 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9434 } 9435 } else { 9436 // requirer == null implies that we're updating all ABIs in the set to 9437 // match scannedPackage. 9438 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9439 } 9440 9441 for (PackageSetting ps : packagesForUser) { 9442 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9443 if (ps.primaryCpuAbiString != null) { 9444 continue; 9445 } 9446 9447 ps.primaryCpuAbiString = adjustedAbi; 9448 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9449 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9450 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9451 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9452 + " (requirer=" 9453 + (requirer == null ? "null" : requirer.pkg.packageName) 9454 + ", scannedPackage=" 9455 + (scannedPackage != null ? scannedPackage.packageName : "null") 9456 + ")"); 9457 try { 9458 mInstaller.rmdex(ps.codePathString, 9459 getDexCodeInstructionSet(getPreferredInstructionSet())); 9460 } catch (InstallerException ignored) { 9461 } 9462 } 9463 } 9464 } 9465 } 9466 } 9467 9468 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9469 synchronized (mPackages) { 9470 mResolverReplaced = true; 9471 // Set up information for custom user intent resolution activity. 9472 mResolveActivity.applicationInfo = pkg.applicationInfo; 9473 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9474 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9475 mResolveActivity.processName = pkg.applicationInfo.packageName; 9476 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9477 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9478 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9479 mResolveActivity.theme = 0; 9480 mResolveActivity.exported = true; 9481 mResolveActivity.enabled = true; 9482 mResolveInfo.activityInfo = mResolveActivity; 9483 mResolveInfo.priority = 0; 9484 mResolveInfo.preferredOrder = 0; 9485 mResolveInfo.match = 0; 9486 mResolveComponentName = mCustomResolverComponentName; 9487 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9488 mResolveComponentName); 9489 } 9490 } 9491 9492 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9493 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9494 9495 // Set up information for ephemeral installer activity 9496 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9497 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9498 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9499 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9500 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9501 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9502 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9503 mEphemeralInstallerActivity.theme = 0; 9504 mEphemeralInstallerActivity.exported = true; 9505 mEphemeralInstallerActivity.enabled = true; 9506 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9507 mEphemeralInstallerInfo.priority = 0; 9508 mEphemeralInstallerInfo.preferredOrder = 1; 9509 mEphemeralInstallerInfo.isDefault = true; 9510 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9511 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9512 9513 if (DEBUG_EPHEMERAL) { 9514 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9515 } 9516 } 9517 9518 private static String calculateBundledApkRoot(final String codePathString) { 9519 final File codePath = new File(codePathString); 9520 final File codeRoot; 9521 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9522 codeRoot = Environment.getRootDirectory(); 9523 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9524 codeRoot = Environment.getOemDirectory(); 9525 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9526 codeRoot = Environment.getVendorDirectory(); 9527 } else { 9528 // Unrecognized code path; take its top real segment as the apk root: 9529 // e.g. /something/app/blah.apk => /something 9530 try { 9531 File f = codePath.getCanonicalFile(); 9532 File parent = f.getParentFile(); // non-null because codePath is a file 9533 File tmp; 9534 while ((tmp = parent.getParentFile()) != null) { 9535 f = parent; 9536 parent = tmp; 9537 } 9538 codeRoot = f; 9539 Slog.w(TAG, "Unrecognized code path " 9540 + codePath + " - using " + codeRoot); 9541 } catch (IOException e) { 9542 // Can't canonicalize the code path -- shenanigans? 9543 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9544 return Environment.getRootDirectory().getPath(); 9545 } 9546 } 9547 return codeRoot.getPath(); 9548 } 9549 9550 /** 9551 * Derive and set the location of native libraries for the given package, 9552 * which varies depending on where and how the package was installed. 9553 */ 9554 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 9555 final ApplicationInfo info = pkg.applicationInfo; 9556 final String codePath = pkg.codePath; 9557 final File codeFile = new File(codePath); 9558 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9559 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9560 9561 info.nativeLibraryRootDir = null; 9562 info.nativeLibraryRootRequiresIsa = false; 9563 info.nativeLibraryDir = null; 9564 info.secondaryNativeLibraryDir = null; 9565 9566 if (isApkFile(codeFile)) { 9567 // Monolithic install 9568 if (bundledApp) { 9569 // If "/system/lib64/apkname" exists, assume that is the per-package 9570 // native library directory to use; otherwise use "/system/lib/apkname". 9571 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9572 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9573 getPrimaryInstructionSet(info)); 9574 9575 // This is a bundled system app so choose the path based on the ABI. 9576 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9577 // is just the default path. 9578 final String apkName = deriveCodePathName(codePath); 9579 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9580 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9581 apkName).getAbsolutePath(); 9582 9583 if (info.secondaryCpuAbi != null) { 9584 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9585 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9586 secondaryLibDir, apkName).getAbsolutePath(); 9587 } 9588 } else if (asecApp) { 9589 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9590 .getAbsolutePath(); 9591 } else { 9592 final String apkName = deriveCodePathName(codePath); 9593 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 9594 .getAbsolutePath(); 9595 } 9596 9597 info.nativeLibraryRootRequiresIsa = false; 9598 info.nativeLibraryDir = info.nativeLibraryRootDir; 9599 } else { 9600 // Cluster install 9601 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9602 info.nativeLibraryRootRequiresIsa = true; 9603 9604 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9605 getPrimaryInstructionSet(info)).getAbsolutePath(); 9606 9607 if (info.secondaryCpuAbi != null) { 9608 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9609 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9610 } 9611 } 9612 } 9613 9614 /** 9615 * Calculate the abis and roots for a bundled app. These can uniquely 9616 * be determined from the contents of the system partition, i.e whether 9617 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9618 * of this information, and instead assume that the system was built 9619 * sensibly. 9620 */ 9621 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9622 PackageSetting pkgSetting) { 9623 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9624 9625 // If "/system/lib64/apkname" exists, assume that is the per-package 9626 // native library directory to use; otherwise use "/system/lib/apkname". 9627 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9628 setBundledAppAbi(pkg, apkRoot, apkName); 9629 // pkgSetting might be null during rescan following uninstall of updates 9630 // to a bundled app, so accommodate that possibility. The settings in 9631 // that case will be established later from the parsed package. 9632 // 9633 // If the settings aren't null, sync them up with what we've just derived. 9634 // note that apkRoot isn't stored in the package settings. 9635 if (pkgSetting != null) { 9636 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9637 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9638 } 9639 } 9640 9641 /** 9642 * Deduces the ABI of a bundled app and sets the relevant fields on the 9643 * parsed pkg object. 9644 * 9645 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9646 * under which system libraries are installed. 9647 * @param apkName the name of the installed package. 9648 */ 9649 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9650 final File codeFile = new File(pkg.codePath); 9651 9652 final boolean has64BitLibs; 9653 final boolean has32BitLibs; 9654 if (isApkFile(codeFile)) { 9655 // Monolithic install 9656 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9657 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9658 } else { 9659 // Cluster install 9660 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9661 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9662 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9663 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9664 has64BitLibs = (new File(rootDir, isa)).exists(); 9665 } else { 9666 has64BitLibs = false; 9667 } 9668 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9669 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9670 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9671 has32BitLibs = (new File(rootDir, isa)).exists(); 9672 } else { 9673 has32BitLibs = false; 9674 } 9675 } 9676 9677 if (has64BitLibs && !has32BitLibs) { 9678 // The package has 64 bit libs, but not 32 bit libs. Its primary 9679 // ABI should be 64 bit. We can safely assume here that the bundled 9680 // native libraries correspond to the most preferred ABI in the list. 9681 9682 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9683 pkg.applicationInfo.secondaryCpuAbi = null; 9684 } else if (has32BitLibs && !has64BitLibs) { 9685 // The package has 32 bit libs but not 64 bit libs. Its primary 9686 // ABI should be 32 bit. 9687 9688 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9689 pkg.applicationInfo.secondaryCpuAbi = null; 9690 } else if (has32BitLibs && has64BitLibs) { 9691 // The application has both 64 and 32 bit bundled libraries. We check 9692 // here that the app declares multiArch support, and warn if it doesn't. 9693 // 9694 // We will be lenient here and record both ABIs. The primary will be the 9695 // ABI that's higher on the list, i.e, a device that's configured to prefer 9696 // 64 bit apps will see a 64 bit primary ABI, 9697 9698 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9699 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9700 } 9701 9702 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9703 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9704 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9705 } else { 9706 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9707 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9708 } 9709 } else { 9710 pkg.applicationInfo.primaryCpuAbi = null; 9711 pkg.applicationInfo.secondaryCpuAbi = null; 9712 } 9713 } 9714 9715 private void killApplication(String pkgName, int appId, String reason) { 9716 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9717 } 9718 9719 private void killApplication(String pkgName, int appId, int userId, String reason) { 9720 // Request the ActivityManager to kill the process(only for existing packages) 9721 // so that we do not end up in a confused state while the user is still using the older 9722 // version of the application while the new one gets installed. 9723 final long token = Binder.clearCallingIdentity(); 9724 try { 9725 IActivityManager am = ActivityManager.getService(); 9726 if (am != null) { 9727 try { 9728 am.killApplication(pkgName, appId, userId, reason); 9729 } catch (RemoteException e) { 9730 } 9731 } 9732 } finally { 9733 Binder.restoreCallingIdentity(token); 9734 } 9735 } 9736 9737 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9738 // Remove the parent package setting 9739 PackageSetting ps = (PackageSetting) pkg.mExtras; 9740 if (ps != null) { 9741 removePackageLI(ps, chatty); 9742 } 9743 // Remove the child package setting 9744 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9745 for (int i = 0; i < childCount; i++) { 9746 PackageParser.Package childPkg = pkg.childPackages.get(i); 9747 ps = (PackageSetting) childPkg.mExtras; 9748 if (ps != null) { 9749 removePackageLI(ps, chatty); 9750 } 9751 } 9752 } 9753 9754 void removePackageLI(PackageSetting ps, boolean chatty) { 9755 if (DEBUG_INSTALL) { 9756 if (chatty) 9757 Log.d(TAG, "Removing package " + ps.name); 9758 } 9759 9760 // writer 9761 synchronized (mPackages) { 9762 mPackages.remove(ps.name); 9763 final PackageParser.Package pkg = ps.pkg; 9764 if (pkg != null) { 9765 cleanPackageDataStructuresLILPw(pkg, chatty); 9766 } 9767 } 9768 } 9769 9770 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9771 if (DEBUG_INSTALL) { 9772 if (chatty) 9773 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9774 } 9775 9776 // writer 9777 synchronized (mPackages) { 9778 // Remove the parent package 9779 mPackages.remove(pkg.applicationInfo.packageName); 9780 cleanPackageDataStructuresLILPw(pkg, chatty); 9781 9782 // Remove the child packages 9783 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9784 for (int i = 0; i < childCount; i++) { 9785 PackageParser.Package childPkg = pkg.childPackages.get(i); 9786 mPackages.remove(childPkg.applicationInfo.packageName); 9787 cleanPackageDataStructuresLILPw(childPkg, chatty); 9788 } 9789 } 9790 } 9791 9792 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9793 int N = pkg.providers.size(); 9794 StringBuilder r = null; 9795 int i; 9796 for (i=0; i<N; i++) { 9797 PackageParser.Provider p = pkg.providers.get(i); 9798 mProviders.removeProvider(p); 9799 if (p.info.authority == null) { 9800 9801 /* There was another ContentProvider with this authority when 9802 * this app was installed so this authority is null, 9803 * Ignore it as we don't have to unregister the provider. 9804 */ 9805 continue; 9806 } 9807 String names[] = p.info.authority.split(";"); 9808 for (int j = 0; j < names.length; j++) { 9809 if (mProvidersByAuthority.get(names[j]) == p) { 9810 mProvidersByAuthority.remove(names[j]); 9811 if (DEBUG_REMOVE) { 9812 if (chatty) 9813 Log.d(TAG, "Unregistered content provider: " + names[j] 9814 + ", className = " + p.info.name + ", isSyncable = " 9815 + p.info.isSyncable); 9816 } 9817 } 9818 } 9819 if (DEBUG_REMOVE && chatty) { 9820 if (r == null) { 9821 r = new StringBuilder(256); 9822 } else { 9823 r.append(' '); 9824 } 9825 r.append(p.info.name); 9826 } 9827 } 9828 if (r != null) { 9829 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9830 } 9831 9832 N = pkg.services.size(); 9833 r = null; 9834 for (i=0; i<N; i++) { 9835 PackageParser.Service s = pkg.services.get(i); 9836 mServices.removeService(s); 9837 if (chatty) { 9838 if (r == null) { 9839 r = new StringBuilder(256); 9840 } else { 9841 r.append(' '); 9842 } 9843 r.append(s.info.name); 9844 } 9845 } 9846 if (r != null) { 9847 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9848 } 9849 9850 N = pkg.receivers.size(); 9851 r = null; 9852 for (i=0; i<N; i++) { 9853 PackageParser.Activity a = pkg.receivers.get(i); 9854 mReceivers.removeActivity(a, "receiver"); 9855 if (DEBUG_REMOVE && chatty) { 9856 if (r == null) { 9857 r = new StringBuilder(256); 9858 } else { 9859 r.append(' '); 9860 } 9861 r.append(a.info.name); 9862 } 9863 } 9864 if (r != null) { 9865 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9866 } 9867 9868 N = pkg.activities.size(); 9869 r = null; 9870 for (i=0; i<N; i++) { 9871 PackageParser.Activity a = pkg.activities.get(i); 9872 mActivities.removeActivity(a, "activity"); 9873 if (DEBUG_REMOVE && chatty) { 9874 if (r == null) { 9875 r = new StringBuilder(256); 9876 } else { 9877 r.append(' '); 9878 } 9879 r.append(a.info.name); 9880 } 9881 } 9882 if (r != null) { 9883 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9884 } 9885 9886 N = pkg.permissions.size(); 9887 r = null; 9888 for (i=0; i<N; i++) { 9889 PackageParser.Permission p = pkg.permissions.get(i); 9890 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9891 if (bp == null) { 9892 bp = mSettings.mPermissionTrees.get(p.info.name); 9893 } 9894 if (bp != null && bp.perm == p) { 9895 bp.perm = null; 9896 if (DEBUG_REMOVE && chatty) { 9897 if (r == null) { 9898 r = new StringBuilder(256); 9899 } else { 9900 r.append(' '); 9901 } 9902 r.append(p.info.name); 9903 } 9904 } 9905 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9906 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9907 if (appOpPkgs != null) { 9908 appOpPkgs.remove(pkg.packageName); 9909 } 9910 } 9911 } 9912 if (r != null) { 9913 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9914 } 9915 9916 N = pkg.requestedPermissions.size(); 9917 r = null; 9918 for (i=0; i<N; i++) { 9919 String perm = pkg.requestedPermissions.get(i); 9920 BasePermission bp = mSettings.mPermissions.get(perm); 9921 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9922 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9923 if (appOpPkgs != null) { 9924 appOpPkgs.remove(pkg.packageName); 9925 if (appOpPkgs.isEmpty()) { 9926 mAppOpPermissionPackages.remove(perm); 9927 } 9928 } 9929 } 9930 } 9931 if (r != null) { 9932 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9933 } 9934 9935 N = pkg.instrumentation.size(); 9936 r = null; 9937 for (i=0; i<N; i++) { 9938 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9939 mInstrumentation.remove(a.getComponentName()); 9940 if (DEBUG_REMOVE && chatty) { 9941 if (r == null) { 9942 r = new StringBuilder(256); 9943 } else { 9944 r.append(' '); 9945 } 9946 r.append(a.info.name); 9947 } 9948 } 9949 if (r != null) { 9950 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9951 } 9952 9953 r = null; 9954 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9955 // Only system apps can hold shared libraries. 9956 if (pkg.libraryNames != null) { 9957 for (i=0; i<pkg.libraryNames.size(); i++) { 9958 String name = pkg.libraryNames.get(i); 9959 SharedLibraryEntry cur = mSharedLibraries.get(name); 9960 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9961 mSharedLibraries.remove(name); 9962 if (DEBUG_REMOVE && chatty) { 9963 if (r == null) { 9964 r = new StringBuilder(256); 9965 } else { 9966 r.append(' '); 9967 } 9968 r.append(name); 9969 } 9970 } 9971 } 9972 } 9973 } 9974 if (r != null) { 9975 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9976 } 9977 } 9978 9979 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9980 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9981 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9982 return true; 9983 } 9984 } 9985 return false; 9986 } 9987 9988 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9989 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9990 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9991 9992 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9993 // Update the parent permissions 9994 updatePermissionsLPw(pkg.packageName, pkg, flags); 9995 // Update the child permissions 9996 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9997 for (int i = 0; i < childCount; i++) { 9998 PackageParser.Package childPkg = pkg.childPackages.get(i); 9999 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 10000 } 10001 } 10002 10003 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 10004 int flags) { 10005 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 10006 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 10007 } 10008 10009 private void updatePermissionsLPw(String changingPkg, 10010 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 10011 // Make sure there are no dangling permission trees. 10012 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 10013 while (it.hasNext()) { 10014 final BasePermission bp = it.next(); 10015 if (bp.packageSetting == null) { 10016 // We may not yet have parsed the package, so just see if 10017 // we still know about its settings. 10018 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10019 } 10020 if (bp.packageSetting == null) { 10021 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 10022 + " from package " + bp.sourcePackage); 10023 it.remove(); 10024 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10025 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10026 Slog.i(TAG, "Removing old permission tree: " + bp.name 10027 + " from package " + bp.sourcePackage); 10028 flags |= UPDATE_PERMISSIONS_ALL; 10029 it.remove(); 10030 } 10031 } 10032 } 10033 10034 // Make sure all dynamic permissions have been assigned to a package, 10035 // and make sure there are no dangling permissions. 10036 it = mSettings.mPermissions.values().iterator(); 10037 while (it.hasNext()) { 10038 final BasePermission bp = it.next(); 10039 if (bp.type == BasePermission.TYPE_DYNAMIC) { 10040 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 10041 + bp.name + " pkg=" + bp.sourcePackage 10042 + " info=" + bp.pendingInfo); 10043 if (bp.packageSetting == null && bp.pendingInfo != null) { 10044 final BasePermission tree = findPermissionTreeLP(bp.name); 10045 if (tree != null && tree.perm != null) { 10046 bp.packageSetting = tree.packageSetting; 10047 bp.perm = new PackageParser.Permission(tree.perm.owner, 10048 new PermissionInfo(bp.pendingInfo)); 10049 bp.perm.info.packageName = tree.perm.info.packageName; 10050 bp.perm.info.name = bp.name; 10051 bp.uid = tree.uid; 10052 } 10053 } 10054 } 10055 if (bp.packageSetting == null) { 10056 // We may not yet have parsed the package, so just see if 10057 // we still know about its settings. 10058 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10059 } 10060 if (bp.packageSetting == null) { 10061 Slog.w(TAG, "Removing dangling permission: " + bp.name 10062 + " from package " + bp.sourcePackage); 10063 it.remove(); 10064 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10065 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10066 Slog.i(TAG, "Removing old permission: " + bp.name 10067 + " from package " + bp.sourcePackage); 10068 flags |= UPDATE_PERMISSIONS_ALL; 10069 it.remove(); 10070 } 10071 } 10072 } 10073 10074 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 10075 // Now update the permissions for all packages, in particular 10076 // replace the granted permissions of the system packages. 10077 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 10078 for (PackageParser.Package pkg : mPackages.values()) { 10079 if (pkg != pkgInfo) { 10080 // Only replace for packages on requested volume 10081 final String volumeUuid = getVolumeUuidForPackage(pkg); 10082 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 10083 && Objects.equals(replaceVolumeUuid, volumeUuid); 10084 grantPermissionsLPw(pkg, replace, changingPkg); 10085 } 10086 } 10087 } 10088 10089 if (pkgInfo != null) { 10090 // Only replace for packages on requested volume 10091 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 10092 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 10093 && Objects.equals(replaceVolumeUuid, volumeUuid); 10094 grantPermissionsLPw(pkgInfo, replace, changingPkg); 10095 } 10096 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10097 } 10098 10099 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 10100 String packageOfInterest) { 10101 // IMPORTANT: There are two types of permissions: install and runtime. 10102 // Install time permissions are granted when the app is installed to 10103 // all device users and users added in the future. Runtime permissions 10104 // are granted at runtime explicitly to specific users. Normal and signature 10105 // protected permissions are install time permissions. Dangerous permissions 10106 // are install permissions if the app's target SDK is Lollipop MR1 or older, 10107 // otherwise they are runtime permissions. This function does not manage 10108 // runtime permissions except for the case an app targeting Lollipop MR1 10109 // being upgraded to target a newer SDK, in which case dangerous permissions 10110 // are transformed from install time to runtime ones. 10111 10112 final PackageSetting ps = (PackageSetting) pkg.mExtras; 10113 if (ps == null) { 10114 return; 10115 } 10116 10117 PermissionsState permissionsState = ps.getPermissionsState(); 10118 PermissionsState origPermissions = permissionsState; 10119 10120 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10121 10122 boolean runtimePermissionsRevoked = false; 10123 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10124 10125 boolean changedInstallPermission = false; 10126 10127 if (replace) { 10128 ps.installPermissionsFixed = false; 10129 if (!ps.isSharedUser()) { 10130 origPermissions = new PermissionsState(permissionsState); 10131 permissionsState.reset(); 10132 } else { 10133 // We need to know only about runtime permission changes since the 10134 // calling code always writes the install permissions state but 10135 // the runtime ones are written only if changed. The only cases of 10136 // changed runtime permissions here are promotion of an install to 10137 // runtime and revocation of a runtime from a shared user. 10138 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10139 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10140 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10141 runtimePermissionsRevoked = true; 10142 } 10143 } 10144 } 10145 10146 permissionsState.setGlobalGids(mGlobalGids); 10147 10148 final int N = pkg.requestedPermissions.size(); 10149 for (int i=0; i<N; i++) { 10150 final String name = pkg.requestedPermissions.get(i); 10151 final BasePermission bp = mSettings.mPermissions.get(name); 10152 10153 if (DEBUG_INSTALL) { 10154 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10155 } 10156 10157 if (bp == null || bp.packageSetting == null) { 10158 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10159 Slog.w(TAG, "Unknown permission " + name 10160 + " in package " + pkg.packageName); 10161 } 10162 continue; 10163 } 10164 10165 10166 // Limit ephemeral apps to ephemeral allowed permissions. 10167 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 10168 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 10169 + pkg.packageName); 10170 continue; 10171 } 10172 10173 final String perm = bp.name; 10174 boolean allowedSig = false; 10175 int grant = GRANT_DENIED; 10176 10177 // Keep track of app op permissions. 10178 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10179 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10180 if (pkgs == null) { 10181 pkgs = new ArraySet<>(); 10182 mAppOpPermissionPackages.put(bp.name, pkgs); 10183 } 10184 pkgs.add(pkg.packageName); 10185 } 10186 10187 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10188 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10189 >= Build.VERSION_CODES.M; 10190 switch (level) { 10191 case PermissionInfo.PROTECTION_NORMAL: { 10192 // For all apps normal permissions are install time ones. 10193 grant = GRANT_INSTALL; 10194 } break; 10195 10196 case PermissionInfo.PROTECTION_DANGEROUS: { 10197 // If a permission review is required for legacy apps we represent 10198 // their permissions as always granted runtime ones since we need 10199 // to keep the review required permission flag per user while an 10200 // install permission's state is shared across all users. 10201 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 10202 // For legacy apps dangerous permissions are install time ones. 10203 grant = GRANT_INSTALL; 10204 } else if (origPermissions.hasInstallPermission(bp.name)) { 10205 // For legacy apps that became modern, install becomes runtime. 10206 grant = GRANT_UPGRADE; 10207 } else if (mPromoteSystemApps 10208 && isSystemApp(ps) 10209 && mExistingSystemPackages.contains(ps.name)) { 10210 // For legacy system apps, install becomes runtime. 10211 // We cannot check hasInstallPermission() for system apps since those 10212 // permissions were granted implicitly and not persisted pre-M. 10213 grant = GRANT_UPGRADE; 10214 } else { 10215 // For modern apps keep runtime permissions unchanged. 10216 grant = GRANT_RUNTIME; 10217 } 10218 } break; 10219 10220 case PermissionInfo.PROTECTION_SIGNATURE: { 10221 // For all apps signature permissions are install time ones. 10222 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10223 if (allowedSig) { 10224 grant = GRANT_INSTALL; 10225 } 10226 } break; 10227 } 10228 10229 if (DEBUG_INSTALL) { 10230 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10231 } 10232 10233 if (grant != GRANT_DENIED) { 10234 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10235 // If this is an existing, non-system package, then 10236 // we can't add any new permissions to it. 10237 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10238 // Except... if this is a permission that was added 10239 // to the platform (note: need to only do this when 10240 // updating the platform). 10241 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10242 grant = GRANT_DENIED; 10243 } 10244 } 10245 } 10246 10247 switch (grant) { 10248 case GRANT_INSTALL: { 10249 // Revoke this as runtime permission to handle the case of 10250 // a runtime permission being downgraded to an install one. 10251 // Also in permission review mode we keep dangerous permissions 10252 // for legacy apps 10253 for (int userId : UserManagerService.getInstance().getUserIds()) { 10254 if (origPermissions.getRuntimePermissionState( 10255 bp.name, userId) != null) { 10256 // Revoke the runtime permission and clear the flags. 10257 origPermissions.revokeRuntimePermission(bp, userId); 10258 origPermissions.updatePermissionFlags(bp, userId, 10259 PackageManager.MASK_PERMISSION_FLAGS, 0); 10260 // If we revoked a permission permission, we have to write. 10261 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10262 changedRuntimePermissionUserIds, userId); 10263 } 10264 } 10265 // Grant an install permission. 10266 if (permissionsState.grantInstallPermission(bp) != 10267 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10268 changedInstallPermission = true; 10269 } 10270 } break; 10271 10272 case GRANT_RUNTIME: { 10273 // Grant previously granted runtime permissions. 10274 for (int userId : UserManagerService.getInstance().getUserIds()) { 10275 PermissionState permissionState = origPermissions 10276 .getRuntimePermissionState(bp.name, userId); 10277 int flags = permissionState != null 10278 ? permissionState.getFlags() : 0; 10279 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10280 if (permissionsState.grantRuntimePermission(bp, userId) == 10281 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10282 // If we cannot put the permission as it was, we have to write. 10283 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10284 changedRuntimePermissionUserIds, userId); 10285 } 10286 // If the app supports runtime permissions no need for a review. 10287 if (mPermissionReviewRequired 10288 && appSupportsRuntimePermissions 10289 && (flags & PackageManager 10290 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10291 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10292 // Since we changed the flags, we have to write. 10293 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10294 changedRuntimePermissionUserIds, userId); 10295 } 10296 } else if (mPermissionReviewRequired 10297 && !appSupportsRuntimePermissions) { 10298 // For legacy apps that need a permission review, every new 10299 // runtime permission is granted but it is pending a review. 10300 // We also need to review only platform defined runtime 10301 // permissions as these are the only ones the platform knows 10302 // how to disable the API to simulate revocation as legacy 10303 // apps don't expect to run with revoked permissions. 10304 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10305 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10306 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10307 // We changed the flags, hence have to write. 10308 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10309 changedRuntimePermissionUserIds, userId); 10310 } 10311 } 10312 if (permissionsState.grantRuntimePermission(bp, userId) 10313 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10314 // We changed the permission, hence have to write. 10315 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10316 changedRuntimePermissionUserIds, userId); 10317 } 10318 } 10319 // Propagate the permission flags. 10320 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10321 } 10322 } break; 10323 10324 case GRANT_UPGRADE: { 10325 // Grant runtime permissions for a previously held install permission. 10326 PermissionState permissionState = origPermissions 10327 .getInstallPermissionState(bp.name); 10328 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10329 10330 if (origPermissions.revokeInstallPermission(bp) 10331 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10332 // We will be transferring the permission flags, so clear them. 10333 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10334 PackageManager.MASK_PERMISSION_FLAGS, 0); 10335 changedInstallPermission = true; 10336 } 10337 10338 // If the permission is not to be promoted to runtime we ignore it and 10339 // also its other flags as they are not applicable to install permissions. 10340 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10341 for (int userId : currentUserIds) { 10342 if (permissionsState.grantRuntimePermission(bp, userId) != 10343 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10344 // Transfer the permission flags. 10345 permissionsState.updatePermissionFlags(bp, userId, 10346 flags, flags); 10347 // If we granted the permission, we have to write. 10348 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10349 changedRuntimePermissionUserIds, userId); 10350 } 10351 } 10352 } 10353 } break; 10354 10355 default: { 10356 if (packageOfInterest == null 10357 || packageOfInterest.equals(pkg.packageName)) { 10358 Slog.w(TAG, "Not granting permission " + perm 10359 + " to package " + pkg.packageName 10360 + " because it was previously installed without"); 10361 } 10362 } break; 10363 } 10364 } else { 10365 if (permissionsState.revokeInstallPermission(bp) != 10366 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10367 // Also drop the permission flags. 10368 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10369 PackageManager.MASK_PERMISSION_FLAGS, 0); 10370 changedInstallPermission = true; 10371 Slog.i(TAG, "Un-granting permission " + perm 10372 + " from package " + pkg.packageName 10373 + " (protectionLevel=" + bp.protectionLevel 10374 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10375 + ")"); 10376 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10377 // Don't print warning for app op permissions, since it is fine for them 10378 // not to be granted, there is a UI for the user to decide. 10379 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10380 Slog.w(TAG, "Not granting permission " + perm 10381 + " to package " + pkg.packageName 10382 + " (protectionLevel=" + bp.protectionLevel 10383 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10384 + ")"); 10385 } 10386 } 10387 } 10388 } 10389 10390 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10391 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10392 // This is the first that we have heard about this package, so the 10393 // permissions we have now selected are fixed until explicitly 10394 // changed. 10395 ps.installPermissionsFixed = true; 10396 } 10397 10398 // Persist the runtime permissions state for users with changes. If permissions 10399 // were revoked because no app in the shared user declares them we have to 10400 // write synchronously to avoid losing runtime permissions state. 10401 for (int userId : changedRuntimePermissionUserIds) { 10402 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10403 } 10404 } 10405 10406 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10407 boolean allowed = false; 10408 final int NP = PackageParser.NEW_PERMISSIONS.length; 10409 for (int ip=0; ip<NP; ip++) { 10410 final PackageParser.NewPermissionInfo npi 10411 = PackageParser.NEW_PERMISSIONS[ip]; 10412 if (npi.name.equals(perm) 10413 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10414 allowed = true; 10415 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10416 + pkg.packageName); 10417 break; 10418 } 10419 } 10420 return allowed; 10421 } 10422 10423 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10424 BasePermission bp, PermissionsState origPermissions) { 10425 boolean privilegedPermission = (bp.protectionLevel 10426 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 10427 boolean controlPrivappPermissions = RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS; 10428 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 10429 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 10430 if (controlPrivappPermissions && privilegedPermission && pkg.isPrivilegedApp() 10431 && !platformPackage && platformPermission) { 10432 ArraySet<String> wlPermissions = SystemConfig.getInstance() 10433 .getPrivAppPermissions(pkg.packageName); 10434 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 10435 if (!whitelisted) { 10436 // Log for now. TODO Enforce permissions 10437 Slog.w(TAG, "Privileged permission " + perm + " for package " 10438 + pkg.packageName + " - not in privapp-permissions whitelist"); 10439 } 10440 } 10441 boolean allowed = (compareSignatures( 10442 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10443 == PackageManager.SIGNATURE_MATCH) 10444 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10445 == PackageManager.SIGNATURE_MATCH); 10446 if (!allowed && privilegedPermission) { 10447 if (isSystemApp(pkg)) { 10448 // For updated system applications, a system permission 10449 // is granted only if it had been defined by the original application. 10450 if (pkg.isUpdatedSystemApp()) { 10451 final PackageSetting sysPs = mSettings 10452 .getDisabledSystemPkgLPr(pkg.packageName); 10453 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10454 // If the original was granted this permission, we take 10455 // that grant decision as read and propagate it to the 10456 // update. 10457 if (sysPs.isPrivileged()) { 10458 allowed = true; 10459 } 10460 } else { 10461 // The system apk may have been updated with an older 10462 // version of the one on the data partition, but which 10463 // granted a new system permission that it didn't have 10464 // before. In this case we do want to allow the app to 10465 // now get the new permission if the ancestral apk is 10466 // privileged to get it. 10467 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10468 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10469 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10470 allowed = true; 10471 break; 10472 } 10473 } 10474 } 10475 // Also if a privileged parent package on the system image or any of 10476 // its children requested a privileged permission, the updated child 10477 // packages can also get the permission. 10478 if (pkg.parentPackage != null) { 10479 final PackageSetting disabledSysParentPs = mSettings 10480 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10481 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10482 && disabledSysParentPs.isPrivileged()) { 10483 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10484 allowed = true; 10485 } else if (disabledSysParentPs.pkg.childPackages != null) { 10486 final int count = disabledSysParentPs.pkg.childPackages.size(); 10487 for (int i = 0; i < count; i++) { 10488 PackageParser.Package disabledSysChildPkg = 10489 disabledSysParentPs.pkg.childPackages.get(i); 10490 if (isPackageRequestingPermission(disabledSysChildPkg, 10491 perm)) { 10492 allowed = true; 10493 break; 10494 } 10495 } 10496 } 10497 } 10498 } 10499 } 10500 } else { 10501 allowed = isPrivilegedApp(pkg); 10502 } 10503 } 10504 } 10505 if (!allowed) { 10506 if (!allowed && (bp.protectionLevel 10507 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10508 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10509 // If this was a previously normal/dangerous permission that got moved 10510 // to a system permission as part of the runtime permission redesign, then 10511 // we still want to blindly grant it to old apps. 10512 allowed = true; 10513 } 10514 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10515 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10516 // If this permission is to be granted to the system installer and 10517 // this app is an installer, then it gets the permission. 10518 allowed = true; 10519 } 10520 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10521 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10522 // If this permission is to be granted to the system verifier and 10523 // this app is a verifier, then it gets the permission. 10524 allowed = true; 10525 } 10526 if (!allowed && (bp.protectionLevel 10527 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10528 && isSystemApp(pkg)) { 10529 // Any pre-installed system app is allowed to get this permission. 10530 allowed = true; 10531 } 10532 if (!allowed && (bp.protectionLevel 10533 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10534 // For development permissions, a development permission 10535 // is granted only if it was already granted. 10536 allowed = origPermissions.hasInstallPermission(perm); 10537 } 10538 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10539 && pkg.packageName.equals(mSetupWizardPackage)) { 10540 // If this permission is to be granted to the system setup wizard and 10541 // this app is a setup wizard, then it gets the permission. 10542 allowed = true; 10543 } 10544 } 10545 return allowed; 10546 } 10547 10548 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10549 final int permCount = pkg.requestedPermissions.size(); 10550 for (int j = 0; j < permCount; j++) { 10551 String requestedPermission = pkg.requestedPermissions.get(j); 10552 if (permission.equals(requestedPermission)) { 10553 return true; 10554 } 10555 } 10556 return false; 10557 } 10558 10559 final class ActivityIntentResolver 10560 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10561 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10562 boolean defaultOnly, int userId) { 10563 if (!sUserManager.exists(userId)) return null; 10564 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10565 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10566 } 10567 10568 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10569 int userId) { 10570 if (!sUserManager.exists(userId)) return null; 10571 mFlags = flags; 10572 return super.queryIntent(intent, resolvedType, 10573 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10574 } 10575 10576 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10577 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10578 if (!sUserManager.exists(userId)) return null; 10579 if (packageActivities == null) { 10580 return null; 10581 } 10582 mFlags = flags; 10583 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10584 final int N = packageActivities.size(); 10585 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10586 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10587 10588 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10589 for (int i = 0; i < N; ++i) { 10590 intentFilters = packageActivities.get(i).intents; 10591 if (intentFilters != null && intentFilters.size() > 0) { 10592 PackageParser.ActivityIntentInfo[] array = 10593 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10594 intentFilters.toArray(array); 10595 listCut.add(array); 10596 } 10597 } 10598 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10599 } 10600 10601 /** 10602 * Finds a privileged activity that matches the specified activity names. 10603 */ 10604 private PackageParser.Activity findMatchingActivity( 10605 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10606 for (PackageParser.Activity sysActivity : activityList) { 10607 if (sysActivity.info.name.equals(activityInfo.name)) { 10608 return sysActivity; 10609 } 10610 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10611 return sysActivity; 10612 } 10613 if (sysActivity.info.targetActivity != null) { 10614 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10615 return sysActivity; 10616 } 10617 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10618 return sysActivity; 10619 } 10620 } 10621 } 10622 return null; 10623 } 10624 10625 public class IterGenerator<E> { 10626 public Iterator<E> generate(ActivityIntentInfo info) { 10627 return null; 10628 } 10629 } 10630 10631 public class ActionIterGenerator extends IterGenerator<String> { 10632 @Override 10633 public Iterator<String> generate(ActivityIntentInfo info) { 10634 return info.actionsIterator(); 10635 } 10636 } 10637 10638 public class CategoriesIterGenerator extends IterGenerator<String> { 10639 @Override 10640 public Iterator<String> generate(ActivityIntentInfo info) { 10641 return info.categoriesIterator(); 10642 } 10643 } 10644 10645 public class SchemesIterGenerator extends IterGenerator<String> { 10646 @Override 10647 public Iterator<String> generate(ActivityIntentInfo info) { 10648 return info.schemesIterator(); 10649 } 10650 } 10651 10652 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10653 @Override 10654 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10655 return info.authoritiesIterator(); 10656 } 10657 } 10658 10659 /** 10660 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10661 * MODIFIED. Do not pass in a list that should not be changed. 10662 */ 10663 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10664 IterGenerator<T> generator, Iterator<T> searchIterator) { 10665 // loop through the set of actions; every one must be found in the intent filter 10666 while (searchIterator.hasNext()) { 10667 // we must have at least one filter in the list to consider a match 10668 if (intentList.size() == 0) { 10669 break; 10670 } 10671 10672 final T searchAction = searchIterator.next(); 10673 10674 // loop through the set of intent filters 10675 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10676 while (intentIter.hasNext()) { 10677 final ActivityIntentInfo intentInfo = intentIter.next(); 10678 boolean selectionFound = false; 10679 10680 // loop through the intent filter's selection criteria; at least one 10681 // of them must match the searched criteria 10682 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10683 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10684 final T intentSelection = intentSelectionIter.next(); 10685 if (intentSelection != null && intentSelection.equals(searchAction)) { 10686 selectionFound = true; 10687 break; 10688 } 10689 } 10690 10691 // the selection criteria wasn't found in this filter's set; this filter 10692 // is not a potential match 10693 if (!selectionFound) { 10694 intentIter.remove(); 10695 } 10696 } 10697 } 10698 } 10699 10700 private boolean isProtectedAction(ActivityIntentInfo filter) { 10701 final Iterator<String> actionsIter = filter.actionsIterator(); 10702 while (actionsIter != null && actionsIter.hasNext()) { 10703 final String filterAction = actionsIter.next(); 10704 if (PROTECTED_ACTIONS.contains(filterAction)) { 10705 return true; 10706 } 10707 } 10708 return false; 10709 } 10710 10711 /** 10712 * Adjusts the priority of the given intent filter according to policy. 10713 * <p> 10714 * <ul> 10715 * <li>The priority for non privileged applications is capped to '0'</li> 10716 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10717 * <li>The priority for unbundled updates to privileged applications is capped to the 10718 * priority defined on the system partition</li> 10719 * </ul> 10720 * <p> 10721 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10722 * allowed to obtain any priority on any action. 10723 */ 10724 private void adjustPriority( 10725 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10726 // nothing to do; priority is fine as-is 10727 if (intent.getPriority() <= 0) { 10728 return; 10729 } 10730 10731 final ActivityInfo activityInfo = intent.activity.info; 10732 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10733 10734 final boolean privilegedApp = 10735 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10736 if (!privilegedApp) { 10737 // non-privileged applications can never define a priority >0 10738 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10739 + " package: " + applicationInfo.packageName 10740 + " activity: " + intent.activity.className 10741 + " origPrio: " + intent.getPriority()); 10742 intent.setPriority(0); 10743 return; 10744 } 10745 10746 if (systemActivities == null) { 10747 // the system package is not disabled; we're parsing the system partition 10748 if (isProtectedAction(intent)) { 10749 if (mDeferProtectedFilters) { 10750 // We can't deal with these just yet. No component should ever obtain a 10751 // >0 priority for a protected actions, with ONE exception -- the setup 10752 // wizard. The setup wizard, however, cannot be known until we're able to 10753 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10754 // until all intent filters have been processed. Chicken, meet egg. 10755 // Let the filter temporarily have a high priority and rectify the 10756 // priorities after all system packages have been scanned. 10757 mProtectedFilters.add(intent); 10758 if (DEBUG_FILTERS) { 10759 Slog.i(TAG, "Protected action; save for later;" 10760 + " package: " + applicationInfo.packageName 10761 + " activity: " + intent.activity.className 10762 + " origPrio: " + intent.getPriority()); 10763 } 10764 return; 10765 } else { 10766 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10767 Slog.i(TAG, "No setup wizard;" 10768 + " All protected intents capped to priority 0"); 10769 } 10770 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10771 if (DEBUG_FILTERS) { 10772 Slog.i(TAG, "Found setup wizard;" 10773 + " allow priority " + intent.getPriority() + ";" 10774 + " package: " + intent.activity.info.packageName 10775 + " activity: " + intent.activity.className 10776 + " priority: " + intent.getPriority()); 10777 } 10778 // setup wizard gets whatever it wants 10779 return; 10780 } 10781 Slog.w(TAG, "Protected action; cap priority to 0;" 10782 + " package: " + intent.activity.info.packageName 10783 + " activity: " + intent.activity.className 10784 + " origPrio: " + intent.getPriority()); 10785 intent.setPriority(0); 10786 return; 10787 } 10788 } 10789 // privileged apps on the system image get whatever priority they request 10790 return; 10791 } 10792 10793 // privileged app unbundled update ... try to find the same activity 10794 final PackageParser.Activity foundActivity = 10795 findMatchingActivity(systemActivities, activityInfo); 10796 if (foundActivity == null) { 10797 // this is a new activity; it cannot obtain >0 priority 10798 if (DEBUG_FILTERS) { 10799 Slog.i(TAG, "New activity; cap priority to 0;" 10800 + " package: " + applicationInfo.packageName 10801 + " activity: " + intent.activity.className 10802 + " origPrio: " + intent.getPriority()); 10803 } 10804 intent.setPriority(0); 10805 return; 10806 } 10807 10808 // found activity, now check for filter equivalence 10809 10810 // a shallow copy is enough; we modify the list, not its contents 10811 final List<ActivityIntentInfo> intentListCopy = 10812 new ArrayList<>(foundActivity.intents); 10813 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10814 10815 // find matching action subsets 10816 final Iterator<String> actionsIterator = intent.actionsIterator(); 10817 if (actionsIterator != null) { 10818 getIntentListSubset( 10819 intentListCopy, new ActionIterGenerator(), actionsIterator); 10820 if (intentListCopy.size() == 0) { 10821 // no more intents to match; we're not equivalent 10822 if (DEBUG_FILTERS) { 10823 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10824 + " package: " + applicationInfo.packageName 10825 + " activity: " + intent.activity.className 10826 + " origPrio: " + intent.getPriority()); 10827 } 10828 intent.setPriority(0); 10829 return; 10830 } 10831 } 10832 10833 // find matching category subsets 10834 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10835 if (categoriesIterator != null) { 10836 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10837 categoriesIterator); 10838 if (intentListCopy.size() == 0) { 10839 // no more intents to match; we're not equivalent 10840 if (DEBUG_FILTERS) { 10841 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10842 + " package: " + applicationInfo.packageName 10843 + " activity: " + intent.activity.className 10844 + " origPrio: " + intent.getPriority()); 10845 } 10846 intent.setPriority(0); 10847 return; 10848 } 10849 } 10850 10851 // find matching schemes subsets 10852 final Iterator<String> schemesIterator = intent.schemesIterator(); 10853 if (schemesIterator != null) { 10854 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10855 schemesIterator); 10856 if (intentListCopy.size() == 0) { 10857 // no more intents to match; we're not equivalent 10858 if (DEBUG_FILTERS) { 10859 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10860 + " package: " + applicationInfo.packageName 10861 + " activity: " + intent.activity.className 10862 + " origPrio: " + intent.getPriority()); 10863 } 10864 intent.setPriority(0); 10865 return; 10866 } 10867 } 10868 10869 // find matching authorities subsets 10870 final Iterator<IntentFilter.AuthorityEntry> 10871 authoritiesIterator = intent.authoritiesIterator(); 10872 if (authoritiesIterator != null) { 10873 getIntentListSubset(intentListCopy, 10874 new AuthoritiesIterGenerator(), 10875 authoritiesIterator); 10876 if (intentListCopy.size() == 0) { 10877 // no more intents to match; we're not equivalent 10878 if (DEBUG_FILTERS) { 10879 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10880 + " package: " + applicationInfo.packageName 10881 + " activity: " + intent.activity.className 10882 + " origPrio: " + intent.getPriority()); 10883 } 10884 intent.setPriority(0); 10885 return; 10886 } 10887 } 10888 10889 // we found matching filter(s); app gets the max priority of all intents 10890 int cappedPriority = 0; 10891 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10892 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10893 } 10894 if (intent.getPriority() > cappedPriority) { 10895 if (DEBUG_FILTERS) { 10896 Slog.i(TAG, "Found matching filter(s);" 10897 + " cap priority to " + cappedPriority + ";" 10898 + " package: " + applicationInfo.packageName 10899 + " activity: " + intent.activity.className 10900 + " origPrio: " + intent.getPriority()); 10901 } 10902 intent.setPriority(cappedPriority); 10903 return; 10904 } 10905 // all this for nothing; the requested priority was <= what was on the system 10906 } 10907 10908 public final void addActivity(PackageParser.Activity a, String type) { 10909 mActivities.put(a.getComponentName(), a); 10910 if (DEBUG_SHOW_INFO) 10911 Log.v( 10912 TAG, " " + type + " " + 10913 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10914 if (DEBUG_SHOW_INFO) 10915 Log.v(TAG, " Class=" + a.info.name); 10916 final int NI = a.intents.size(); 10917 for (int j=0; j<NI; j++) { 10918 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10919 if ("activity".equals(type)) { 10920 final PackageSetting ps = 10921 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10922 final List<PackageParser.Activity> systemActivities = 10923 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10924 adjustPriority(systemActivities, intent); 10925 } 10926 if (DEBUG_SHOW_INFO) { 10927 Log.v(TAG, " IntentFilter:"); 10928 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10929 } 10930 if (!intent.debugCheck()) { 10931 Log.w(TAG, "==> For Activity " + a.info.name); 10932 } 10933 addFilter(intent); 10934 } 10935 } 10936 10937 public final void removeActivity(PackageParser.Activity a, String type) { 10938 mActivities.remove(a.getComponentName()); 10939 if (DEBUG_SHOW_INFO) { 10940 Log.v(TAG, " " + type + " " 10941 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10942 : a.info.name) + ":"); 10943 Log.v(TAG, " Class=" + a.info.name); 10944 } 10945 final int NI = a.intents.size(); 10946 for (int j=0; j<NI; j++) { 10947 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10948 if (DEBUG_SHOW_INFO) { 10949 Log.v(TAG, " IntentFilter:"); 10950 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10951 } 10952 removeFilter(intent); 10953 } 10954 } 10955 10956 @Override 10957 protected boolean allowFilterResult( 10958 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10959 ActivityInfo filterAi = filter.activity.info; 10960 for (int i=dest.size()-1; i>=0; i--) { 10961 ActivityInfo destAi = dest.get(i).activityInfo; 10962 if (destAi.name == filterAi.name 10963 && destAi.packageName == filterAi.packageName) { 10964 return false; 10965 } 10966 } 10967 return true; 10968 } 10969 10970 @Override 10971 protected ActivityIntentInfo[] newArray(int size) { 10972 return new ActivityIntentInfo[size]; 10973 } 10974 10975 @Override 10976 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10977 if (!sUserManager.exists(userId)) return true; 10978 PackageParser.Package p = filter.activity.owner; 10979 if (p != null) { 10980 PackageSetting ps = (PackageSetting)p.mExtras; 10981 if (ps != null) { 10982 // System apps are never considered stopped for purposes of 10983 // filtering, because there may be no way for the user to 10984 // actually re-launch them. 10985 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10986 && ps.getStopped(userId); 10987 } 10988 } 10989 return false; 10990 } 10991 10992 @Override 10993 protected boolean isPackageForFilter(String packageName, 10994 PackageParser.ActivityIntentInfo info) { 10995 return packageName.equals(info.activity.owner.packageName); 10996 } 10997 10998 @Override 10999 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 11000 int match, int userId) { 11001 if (!sUserManager.exists(userId)) return null; 11002 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 11003 return null; 11004 } 11005 final PackageParser.Activity activity = info.activity; 11006 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 11007 if (ps == null) { 11008 return null; 11009 } 11010 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 11011 ps.readUserState(userId), userId); 11012 if (ai == null) { 11013 return null; 11014 } 11015 final ResolveInfo res = new ResolveInfo(); 11016 res.activityInfo = ai; 11017 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11018 res.filter = info; 11019 } 11020 if (info != null) { 11021 res.handleAllWebDataURI = info.handleAllWebDataURI(); 11022 } 11023 res.priority = info.getPriority(); 11024 res.preferredOrder = activity.owner.mPreferredOrder; 11025 //System.out.println("Result: " + res.activityInfo.className + 11026 // " = " + res.priority); 11027 res.match = match; 11028 res.isDefault = info.hasDefault; 11029 res.labelRes = info.labelRes; 11030 res.nonLocalizedLabel = info.nonLocalizedLabel; 11031 if (userNeedsBadging(userId)) { 11032 res.noResourceId = true; 11033 } else { 11034 res.icon = info.icon; 11035 } 11036 res.iconResourceId = info.icon; 11037 res.system = res.activityInfo.applicationInfo.isSystemApp(); 11038 return res; 11039 } 11040 11041 @Override 11042 protected void sortResults(List<ResolveInfo> results) { 11043 Collections.sort(results, mResolvePrioritySorter); 11044 } 11045 11046 @Override 11047 protected void dumpFilter(PrintWriter out, String prefix, 11048 PackageParser.ActivityIntentInfo filter) { 11049 out.print(prefix); out.print( 11050 Integer.toHexString(System.identityHashCode(filter.activity))); 11051 out.print(' '); 11052 filter.activity.printComponentShortName(out); 11053 out.print(" filter "); 11054 out.println(Integer.toHexString(System.identityHashCode(filter))); 11055 } 11056 11057 @Override 11058 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 11059 return filter.activity; 11060 } 11061 11062 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11063 PackageParser.Activity activity = (PackageParser.Activity)label; 11064 out.print(prefix); out.print( 11065 Integer.toHexString(System.identityHashCode(activity))); 11066 out.print(' '); 11067 activity.printComponentShortName(out); 11068 if (count > 1) { 11069 out.print(" ("); out.print(count); out.print(" filters)"); 11070 } 11071 out.println(); 11072 } 11073 11074 // Keys are String (activity class name), values are Activity. 11075 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 11076 = new ArrayMap<ComponentName, PackageParser.Activity>(); 11077 private int mFlags; 11078 } 11079 11080 private final class ServiceIntentResolver 11081 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 11082 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11083 boolean defaultOnly, int userId) { 11084 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11085 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11086 } 11087 11088 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11089 int userId) { 11090 if (!sUserManager.exists(userId)) return null; 11091 mFlags = flags; 11092 return super.queryIntent(intent, resolvedType, 11093 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11094 } 11095 11096 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11097 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 11098 if (!sUserManager.exists(userId)) return null; 11099 if (packageServices == null) { 11100 return null; 11101 } 11102 mFlags = flags; 11103 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 11104 final int N = packageServices.size(); 11105 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 11106 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 11107 11108 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 11109 for (int i = 0; i < N; ++i) { 11110 intentFilters = packageServices.get(i).intents; 11111 if (intentFilters != null && intentFilters.size() > 0) { 11112 PackageParser.ServiceIntentInfo[] array = 11113 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 11114 intentFilters.toArray(array); 11115 listCut.add(array); 11116 } 11117 } 11118 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11119 } 11120 11121 public final void addService(PackageParser.Service s) { 11122 mServices.put(s.getComponentName(), s); 11123 if (DEBUG_SHOW_INFO) { 11124 Log.v(TAG, " " 11125 + (s.info.nonLocalizedLabel != null 11126 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11127 Log.v(TAG, " Class=" + s.info.name); 11128 } 11129 final int NI = s.intents.size(); 11130 int j; 11131 for (j=0; j<NI; j++) { 11132 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11133 if (DEBUG_SHOW_INFO) { 11134 Log.v(TAG, " IntentFilter:"); 11135 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11136 } 11137 if (!intent.debugCheck()) { 11138 Log.w(TAG, "==> For Service " + s.info.name); 11139 } 11140 addFilter(intent); 11141 } 11142 } 11143 11144 public final void removeService(PackageParser.Service s) { 11145 mServices.remove(s.getComponentName()); 11146 if (DEBUG_SHOW_INFO) { 11147 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11148 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11149 Log.v(TAG, " Class=" + s.info.name); 11150 } 11151 final int NI = s.intents.size(); 11152 int j; 11153 for (j=0; j<NI; j++) { 11154 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11155 if (DEBUG_SHOW_INFO) { 11156 Log.v(TAG, " IntentFilter:"); 11157 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11158 } 11159 removeFilter(intent); 11160 } 11161 } 11162 11163 @Override 11164 protected boolean allowFilterResult( 11165 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11166 ServiceInfo filterSi = filter.service.info; 11167 for (int i=dest.size()-1; i>=0; i--) { 11168 ServiceInfo destAi = dest.get(i).serviceInfo; 11169 if (destAi.name == filterSi.name 11170 && destAi.packageName == filterSi.packageName) { 11171 return false; 11172 } 11173 } 11174 return true; 11175 } 11176 11177 @Override 11178 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11179 return new PackageParser.ServiceIntentInfo[size]; 11180 } 11181 11182 @Override 11183 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11184 if (!sUserManager.exists(userId)) return true; 11185 PackageParser.Package p = filter.service.owner; 11186 if (p != null) { 11187 PackageSetting ps = (PackageSetting)p.mExtras; 11188 if (ps != null) { 11189 // System apps are never considered stopped for purposes of 11190 // filtering, because there may be no way for the user to 11191 // actually re-launch them. 11192 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11193 && ps.getStopped(userId); 11194 } 11195 } 11196 return false; 11197 } 11198 11199 @Override 11200 protected boolean isPackageForFilter(String packageName, 11201 PackageParser.ServiceIntentInfo info) { 11202 return packageName.equals(info.service.owner.packageName); 11203 } 11204 11205 @Override 11206 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11207 int match, int userId) { 11208 if (!sUserManager.exists(userId)) return null; 11209 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11210 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11211 return null; 11212 } 11213 final PackageParser.Service service = info.service; 11214 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11215 if (ps == null) { 11216 return null; 11217 } 11218 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11219 ps.readUserState(userId), userId); 11220 if (si == null) { 11221 return null; 11222 } 11223 final ResolveInfo res = new ResolveInfo(); 11224 res.serviceInfo = si; 11225 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11226 res.filter = filter; 11227 } 11228 res.priority = info.getPriority(); 11229 res.preferredOrder = service.owner.mPreferredOrder; 11230 res.match = match; 11231 res.isDefault = info.hasDefault; 11232 res.labelRes = info.labelRes; 11233 res.nonLocalizedLabel = info.nonLocalizedLabel; 11234 res.icon = info.icon; 11235 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11236 return res; 11237 } 11238 11239 @Override 11240 protected void sortResults(List<ResolveInfo> results) { 11241 Collections.sort(results, mResolvePrioritySorter); 11242 } 11243 11244 @Override 11245 protected void dumpFilter(PrintWriter out, String prefix, 11246 PackageParser.ServiceIntentInfo filter) { 11247 out.print(prefix); out.print( 11248 Integer.toHexString(System.identityHashCode(filter.service))); 11249 out.print(' '); 11250 filter.service.printComponentShortName(out); 11251 out.print(" filter "); 11252 out.println(Integer.toHexString(System.identityHashCode(filter))); 11253 } 11254 11255 @Override 11256 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11257 return filter.service; 11258 } 11259 11260 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11261 PackageParser.Service service = (PackageParser.Service)label; 11262 out.print(prefix); out.print( 11263 Integer.toHexString(System.identityHashCode(service))); 11264 out.print(' '); 11265 service.printComponentShortName(out); 11266 if (count > 1) { 11267 out.print(" ("); out.print(count); out.print(" filters)"); 11268 } 11269 out.println(); 11270 } 11271 11272// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11273// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11274// final List<ResolveInfo> retList = Lists.newArrayList(); 11275// while (i.hasNext()) { 11276// final ResolveInfo resolveInfo = (ResolveInfo) i; 11277// if (isEnabledLP(resolveInfo.serviceInfo)) { 11278// retList.add(resolveInfo); 11279// } 11280// } 11281// return retList; 11282// } 11283 11284 // Keys are String (activity class name), values are Activity. 11285 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11286 = new ArrayMap<ComponentName, PackageParser.Service>(); 11287 private int mFlags; 11288 }; 11289 11290 private final class ProviderIntentResolver 11291 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11292 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11293 boolean defaultOnly, int userId) { 11294 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11295 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11296 } 11297 11298 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11299 int userId) { 11300 if (!sUserManager.exists(userId)) 11301 return null; 11302 mFlags = flags; 11303 return super.queryIntent(intent, resolvedType, 11304 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11305 } 11306 11307 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11308 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11309 if (!sUserManager.exists(userId)) 11310 return null; 11311 if (packageProviders == null) { 11312 return null; 11313 } 11314 mFlags = flags; 11315 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11316 final int N = packageProviders.size(); 11317 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11318 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11319 11320 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11321 for (int i = 0; i < N; ++i) { 11322 intentFilters = packageProviders.get(i).intents; 11323 if (intentFilters != null && intentFilters.size() > 0) { 11324 PackageParser.ProviderIntentInfo[] array = 11325 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11326 intentFilters.toArray(array); 11327 listCut.add(array); 11328 } 11329 } 11330 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11331 } 11332 11333 public final void addProvider(PackageParser.Provider p) { 11334 if (mProviders.containsKey(p.getComponentName())) { 11335 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11336 return; 11337 } 11338 11339 mProviders.put(p.getComponentName(), p); 11340 if (DEBUG_SHOW_INFO) { 11341 Log.v(TAG, " " 11342 + (p.info.nonLocalizedLabel != null 11343 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11344 Log.v(TAG, " Class=" + p.info.name); 11345 } 11346 final int NI = p.intents.size(); 11347 int j; 11348 for (j = 0; j < NI; j++) { 11349 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11350 if (DEBUG_SHOW_INFO) { 11351 Log.v(TAG, " IntentFilter:"); 11352 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11353 } 11354 if (!intent.debugCheck()) { 11355 Log.w(TAG, "==> For Provider " + p.info.name); 11356 } 11357 addFilter(intent); 11358 } 11359 } 11360 11361 public final void removeProvider(PackageParser.Provider p) { 11362 mProviders.remove(p.getComponentName()); 11363 if (DEBUG_SHOW_INFO) { 11364 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11365 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11366 Log.v(TAG, " Class=" + p.info.name); 11367 } 11368 final int NI = p.intents.size(); 11369 int j; 11370 for (j = 0; j < NI; j++) { 11371 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11372 if (DEBUG_SHOW_INFO) { 11373 Log.v(TAG, " IntentFilter:"); 11374 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11375 } 11376 removeFilter(intent); 11377 } 11378 } 11379 11380 @Override 11381 protected boolean allowFilterResult( 11382 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11383 ProviderInfo filterPi = filter.provider.info; 11384 for (int i = dest.size() - 1; i >= 0; i--) { 11385 ProviderInfo destPi = dest.get(i).providerInfo; 11386 if (destPi.name == filterPi.name 11387 && destPi.packageName == filterPi.packageName) { 11388 return false; 11389 } 11390 } 11391 return true; 11392 } 11393 11394 @Override 11395 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11396 return new PackageParser.ProviderIntentInfo[size]; 11397 } 11398 11399 @Override 11400 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11401 if (!sUserManager.exists(userId)) 11402 return true; 11403 PackageParser.Package p = filter.provider.owner; 11404 if (p != null) { 11405 PackageSetting ps = (PackageSetting) p.mExtras; 11406 if (ps != null) { 11407 // System apps are never considered stopped for purposes of 11408 // filtering, because there may be no way for the user to 11409 // actually re-launch them. 11410 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11411 && ps.getStopped(userId); 11412 } 11413 } 11414 return false; 11415 } 11416 11417 @Override 11418 protected boolean isPackageForFilter(String packageName, 11419 PackageParser.ProviderIntentInfo info) { 11420 return packageName.equals(info.provider.owner.packageName); 11421 } 11422 11423 @Override 11424 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11425 int match, int userId) { 11426 if (!sUserManager.exists(userId)) 11427 return null; 11428 final PackageParser.ProviderIntentInfo info = filter; 11429 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11430 return null; 11431 } 11432 final PackageParser.Provider provider = info.provider; 11433 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11434 if (ps == null) { 11435 return null; 11436 } 11437 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11438 ps.readUserState(userId), userId); 11439 if (pi == null) { 11440 return null; 11441 } 11442 final ResolveInfo res = new ResolveInfo(); 11443 res.providerInfo = pi; 11444 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11445 res.filter = filter; 11446 } 11447 res.priority = info.getPriority(); 11448 res.preferredOrder = provider.owner.mPreferredOrder; 11449 res.match = match; 11450 res.isDefault = info.hasDefault; 11451 res.labelRes = info.labelRes; 11452 res.nonLocalizedLabel = info.nonLocalizedLabel; 11453 res.icon = info.icon; 11454 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11455 return res; 11456 } 11457 11458 @Override 11459 protected void sortResults(List<ResolveInfo> results) { 11460 Collections.sort(results, mResolvePrioritySorter); 11461 } 11462 11463 @Override 11464 protected void dumpFilter(PrintWriter out, String prefix, 11465 PackageParser.ProviderIntentInfo filter) { 11466 out.print(prefix); 11467 out.print( 11468 Integer.toHexString(System.identityHashCode(filter.provider))); 11469 out.print(' '); 11470 filter.provider.printComponentShortName(out); 11471 out.print(" filter "); 11472 out.println(Integer.toHexString(System.identityHashCode(filter))); 11473 } 11474 11475 @Override 11476 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11477 return filter.provider; 11478 } 11479 11480 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11481 PackageParser.Provider provider = (PackageParser.Provider)label; 11482 out.print(prefix); out.print( 11483 Integer.toHexString(System.identityHashCode(provider))); 11484 out.print(' '); 11485 provider.printComponentShortName(out); 11486 if (count > 1) { 11487 out.print(" ("); out.print(count); out.print(" filters)"); 11488 } 11489 out.println(); 11490 } 11491 11492 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11493 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11494 private int mFlags; 11495 } 11496 11497 static final class EphemeralIntentResolver 11498 extends IntentResolver<EphemeralResponse, EphemeralResponse> { 11499 /** 11500 * The result that has the highest defined order. Ordering applies on a 11501 * per-package basis. Mapping is from package name to Pair of order and 11502 * EphemeralResolveInfo. 11503 * <p> 11504 * NOTE: This is implemented as a field variable for convenience and efficiency. 11505 * By having a field variable, we're able to track filter ordering as soon as 11506 * a non-zero order is defined. Otherwise, multiple loops across the result set 11507 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11508 * this needs to be contained entirely within {@link #filterResults()}. 11509 */ 11510 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11511 11512 @Override 11513 protected EphemeralResponse[] newArray(int size) { 11514 return new EphemeralResponse[size]; 11515 } 11516 11517 @Override 11518 protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) { 11519 return true; 11520 } 11521 11522 @Override 11523 protected EphemeralResponse newResult(EphemeralResponse responseObj, int match, 11524 int userId) { 11525 if (!sUserManager.exists(userId)) { 11526 return null; 11527 } 11528 final String packageName = responseObj.resolveInfo.getPackageName(); 11529 final Integer order = responseObj.getOrder(); 11530 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11531 mOrderResult.get(packageName); 11532 // ordering is enabled and this item's order isn't high enough 11533 if (lastOrderResult != null && lastOrderResult.first >= order) { 11534 return null; 11535 } 11536 final EphemeralResolveInfo res = responseObj.resolveInfo; 11537 if (order > 0) { 11538 // non-zero order, enable ordering 11539 mOrderResult.put(packageName, new Pair<>(order, res)); 11540 } 11541 return responseObj; 11542 } 11543 11544 @Override 11545 protected void filterResults(List<EphemeralResponse> results) { 11546 // only do work if ordering is enabled [most of the time it won't be] 11547 if (mOrderResult.size() == 0) { 11548 return; 11549 } 11550 int resultSize = results.size(); 11551 for (int i = 0; i < resultSize; i++) { 11552 final EphemeralResolveInfo info = results.get(i).resolveInfo; 11553 final String packageName = info.getPackageName(); 11554 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11555 if (savedInfo == null) { 11556 // package doesn't having ordering 11557 continue; 11558 } 11559 if (savedInfo.second == info) { 11560 // circled back to the highest ordered item; remove from order list 11561 mOrderResult.remove(savedInfo); 11562 if (mOrderResult.size() == 0) { 11563 // no more ordered items 11564 break; 11565 } 11566 continue; 11567 } 11568 // item has a worse order, remove it from the result list 11569 results.remove(i); 11570 resultSize--; 11571 i--; 11572 } 11573 } 11574 } 11575 11576 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11577 new Comparator<ResolveInfo>() { 11578 public int compare(ResolveInfo r1, ResolveInfo r2) { 11579 int v1 = r1.priority; 11580 int v2 = r2.priority; 11581 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11582 if (v1 != v2) { 11583 return (v1 > v2) ? -1 : 1; 11584 } 11585 v1 = r1.preferredOrder; 11586 v2 = r2.preferredOrder; 11587 if (v1 != v2) { 11588 return (v1 > v2) ? -1 : 1; 11589 } 11590 if (r1.isDefault != r2.isDefault) { 11591 return r1.isDefault ? -1 : 1; 11592 } 11593 v1 = r1.match; 11594 v2 = r2.match; 11595 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11596 if (v1 != v2) { 11597 return (v1 > v2) ? -1 : 1; 11598 } 11599 if (r1.system != r2.system) { 11600 return r1.system ? -1 : 1; 11601 } 11602 if (r1.activityInfo != null) { 11603 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11604 } 11605 if (r1.serviceInfo != null) { 11606 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11607 } 11608 if (r1.providerInfo != null) { 11609 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11610 } 11611 return 0; 11612 } 11613 }; 11614 11615 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11616 new Comparator<ProviderInfo>() { 11617 public int compare(ProviderInfo p1, ProviderInfo p2) { 11618 final int v1 = p1.initOrder; 11619 final int v2 = p2.initOrder; 11620 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11621 } 11622 }; 11623 11624 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11625 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11626 final int[] userIds) { 11627 mHandler.post(new Runnable() { 11628 @Override 11629 public void run() { 11630 try { 11631 final IActivityManager am = ActivityManager.getService(); 11632 if (am == null) return; 11633 final int[] resolvedUserIds; 11634 if (userIds == null) { 11635 resolvedUserIds = am.getRunningUserIds(); 11636 } else { 11637 resolvedUserIds = userIds; 11638 } 11639 for (int id : resolvedUserIds) { 11640 final Intent intent = new Intent(action, 11641 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11642 if (extras != null) { 11643 intent.putExtras(extras); 11644 } 11645 if (targetPkg != null) { 11646 intent.setPackage(targetPkg); 11647 } 11648 // Modify the UID when posting to other users 11649 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11650 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11651 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11652 intent.putExtra(Intent.EXTRA_UID, uid); 11653 } 11654 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11655 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11656 if (DEBUG_BROADCASTS) { 11657 RuntimeException here = new RuntimeException("here"); 11658 here.fillInStackTrace(); 11659 Slog.d(TAG, "Sending to user " + id + ": " 11660 + intent.toShortString(false, true, false, false) 11661 + " " + intent.getExtras(), here); 11662 } 11663 am.broadcastIntent(null, intent, null, finishedReceiver, 11664 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11665 null, finishedReceiver != null, false, id); 11666 } 11667 } catch (RemoteException ex) { 11668 } 11669 } 11670 }); 11671 } 11672 11673 /** 11674 * Check if the external storage media is available. This is true if there 11675 * is a mounted external storage medium or if the external storage is 11676 * emulated. 11677 */ 11678 private boolean isExternalMediaAvailable() { 11679 return mMediaMounted || Environment.isExternalStorageEmulated(); 11680 } 11681 11682 @Override 11683 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11684 // writer 11685 synchronized (mPackages) { 11686 if (!isExternalMediaAvailable()) { 11687 // If the external storage is no longer mounted at this point, 11688 // the caller may not have been able to delete all of this 11689 // packages files and can not delete any more. Bail. 11690 return null; 11691 } 11692 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11693 if (lastPackage != null) { 11694 pkgs.remove(lastPackage); 11695 } 11696 if (pkgs.size() > 0) { 11697 return pkgs.get(0); 11698 } 11699 } 11700 return null; 11701 } 11702 11703 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11704 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11705 userId, andCode ? 1 : 0, packageName); 11706 if (mSystemReady) { 11707 msg.sendToTarget(); 11708 } else { 11709 if (mPostSystemReadyMessages == null) { 11710 mPostSystemReadyMessages = new ArrayList<>(); 11711 } 11712 mPostSystemReadyMessages.add(msg); 11713 } 11714 } 11715 11716 void startCleaningPackages() { 11717 // reader 11718 if (!isExternalMediaAvailable()) { 11719 return; 11720 } 11721 synchronized (mPackages) { 11722 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11723 return; 11724 } 11725 } 11726 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11727 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11728 IActivityManager am = ActivityManager.getService(); 11729 if (am != null) { 11730 try { 11731 am.startService(null, intent, null, mContext.getOpPackageName(), 11732 UserHandle.USER_SYSTEM); 11733 } catch (RemoteException e) { 11734 } 11735 } 11736 } 11737 11738 @Override 11739 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11740 int installFlags, String installerPackageName, int userId) { 11741 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11742 11743 final int callingUid = Binder.getCallingUid(); 11744 enforceCrossUserPermission(callingUid, userId, 11745 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11746 11747 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11748 try { 11749 if (observer != null) { 11750 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11751 } 11752 } catch (RemoteException re) { 11753 } 11754 return; 11755 } 11756 11757 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11758 installFlags |= PackageManager.INSTALL_FROM_ADB; 11759 11760 } else { 11761 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11762 // about installerPackageName. 11763 11764 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11765 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11766 } 11767 11768 UserHandle user; 11769 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11770 user = UserHandle.ALL; 11771 } else { 11772 user = new UserHandle(userId); 11773 } 11774 11775 // Only system components can circumvent runtime permissions when installing. 11776 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11777 && mContext.checkCallingOrSelfPermission(Manifest.permission 11778 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11779 throw new SecurityException("You need the " 11780 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11781 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11782 } 11783 11784 final File originFile = new File(originPath); 11785 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11786 11787 final Message msg = mHandler.obtainMessage(INIT_COPY); 11788 final VerificationInfo verificationInfo = new VerificationInfo( 11789 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11790 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11791 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11792 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11793 null /*certificates*/); 11794 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11795 msg.obj = params; 11796 11797 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11798 System.identityHashCode(msg.obj)); 11799 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11800 System.identityHashCode(msg.obj)); 11801 11802 mHandler.sendMessage(msg); 11803 } 11804 11805 void installStage(String packageName, File stagedDir, String stagedCid, 11806 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11807 String installerPackageName, int installerUid, UserHandle user, 11808 Certificate[][] certificates) { 11809 if (DEBUG_EPHEMERAL) { 11810 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11811 Slog.d(TAG, "Ephemeral install of " + packageName); 11812 } 11813 } 11814 final VerificationInfo verificationInfo = new VerificationInfo( 11815 sessionParams.originatingUri, sessionParams.referrerUri, 11816 sessionParams.originatingUid, installerUid); 11817 11818 final OriginInfo origin; 11819 if (stagedDir != null) { 11820 origin = OriginInfo.fromStagedFile(stagedDir); 11821 } else { 11822 origin = OriginInfo.fromStagedContainer(stagedCid); 11823 } 11824 11825 final Message msg = mHandler.obtainMessage(INIT_COPY); 11826 final InstallParams params = new InstallParams(origin, null, observer, 11827 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11828 verificationInfo, user, sessionParams.abiOverride, 11829 sessionParams.grantedRuntimePermissions, certificates); 11830 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11831 msg.obj = params; 11832 11833 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11834 System.identityHashCode(msg.obj)); 11835 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11836 System.identityHashCode(msg.obj)); 11837 11838 mHandler.sendMessage(msg); 11839 } 11840 11841 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11842 int userId) { 11843 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11844 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 11845 } 11846 11847 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 11848 int appId, int... userIds) { 11849 if (ArrayUtils.isEmpty(userIds)) { 11850 return; 11851 } 11852 Bundle extras = new Bundle(1); 11853 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 11854 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 11855 11856 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11857 packageName, extras, 0, null, null, userIds); 11858 if (isSystem) { 11859 mHandler.post(() -> { 11860 for (int userId : userIds) { 11861 sendBootCompletedBroadcastToSystemApp(packageName, userId); 11862 } 11863 } 11864 ); 11865 } 11866 } 11867 11868 /** 11869 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 11870 * automatically without needing an explicit launch. 11871 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 11872 */ 11873 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 11874 // If user is not running, the app didn't miss any broadcast 11875 if (!mUserManagerInternal.isUserRunning(userId)) { 11876 return; 11877 } 11878 final IActivityManager am = ActivityManager.getService(); 11879 try { 11880 // Deliver LOCKED_BOOT_COMPLETED first 11881 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 11882 .setPackage(packageName); 11883 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 11884 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 11885 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11886 11887 // Deliver BOOT_COMPLETED only if user is unlocked 11888 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 11889 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 11890 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 11891 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11892 } 11893 } catch (RemoteException e) { 11894 throw e.rethrowFromSystemServer(); 11895 } 11896 } 11897 11898 @Override 11899 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11900 int userId) { 11901 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11902 PackageSetting pkgSetting; 11903 final int uid = Binder.getCallingUid(); 11904 enforceCrossUserPermission(uid, userId, 11905 true /* requireFullPermission */, true /* checkShell */, 11906 "setApplicationHiddenSetting for user " + userId); 11907 11908 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11909 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11910 return false; 11911 } 11912 11913 long callingId = Binder.clearCallingIdentity(); 11914 try { 11915 boolean sendAdded = false; 11916 boolean sendRemoved = false; 11917 // writer 11918 synchronized (mPackages) { 11919 pkgSetting = mSettings.mPackages.get(packageName); 11920 if (pkgSetting == null) { 11921 return false; 11922 } 11923 // Do not allow "android" is being disabled 11924 if ("android".equals(packageName)) { 11925 Slog.w(TAG, "Cannot hide package: android"); 11926 return false; 11927 } 11928 // Only allow protected packages to hide themselves. 11929 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11930 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11931 Slog.w(TAG, "Not hiding protected package: " + packageName); 11932 return false; 11933 } 11934 11935 if (pkgSetting.getHidden(userId) != hidden) { 11936 pkgSetting.setHidden(hidden, userId); 11937 mSettings.writePackageRestrictionsLPr(userId); 11938 if (hidden) { 11939 sendRemoved = true; 11940 } else { 11941 sendAdded = true; 11942 } 11943 } 11944 } 11945 if (sendAdded) { 11946 sendPackageAddedForUser(packageName, pkgSetting, userId); 11947 return true; 11948 } 11949 if (sendRemoved) { 11950 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11951 "hiding pkg"); 11952 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11953 return true; 11954 } 11955 } finally { 11956 Binder.restoreCallingIdentity(callingId); 11957 } 11958 return false; 11959 } 11960 11961 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11962 int userId) { 11963 final PackageRemovedInfo info = new PackageRemovedInfo(); 11964 info.removedPackage = packageName; 11965 info.removedUsers = new int[] {userId}; 11966 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11967 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11968 } 11969 11970 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11971 if (pkgList.length > 0) { 11972 Bundle extras = new Bundle(1); 11973 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11974 11975 sendPackageBroadcast( 11976 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11977 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11978 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11979 new int[] {userId}); 11980 } 11981 } 11982 11983 /** 11984 * Returns true if application is not found or there was an error. Otherwise it returns 11985 * the hidden state of the package for the given user. 11986 */ 11987 @Override 11988 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11989 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11990 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11991 true /* requireFullPermission */, false /* checkShell */, 11992 "getApplicationHidden for user " + userId); 11993 PackageSetting pkgSetting; 11994 long callingId = Binder.clearCallingIdentity(); 11995 try { 11996 // writer 11997 synchronized (mPackages) { 11998 pkgSetting = mSettings.mPackages.get(packageName); 11999 if (pkgSetting == null) { 12000 return true; 12001 } 12002 return pkgSetting.getHidden(userId); 12003 } 12004 } finally { 12005 Binder.restoreCallingIdentity(callingId); 12006 } 12007 } 12008 12009 /** 12010 * @hide 12011 */ 12012 @Override 12013 public int installExistingPackageAsUser(String packageName, int userId) { 12014 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 12015 null); 12016 PackageSetting pkgSetting; 12017 final int uid = Binder.getCallingUid(); 12018 enforceCrossUserPermission(uid, userId, 12019 true /* requireFullPermission */, true /* checkShell */, 12020 "installExistingPackage for user " + userId); 12021 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12022 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 12023 } 12024 12025 long callingId = Binder.clearCallingIdentity(); 12026 try { 12027 boolean installed = false; 12028 12029 // writer 12030 synchronized (mPackages) { 12031 pkgSetting = mSettings.mPackages.get(packageName); 12032 if (pkgSetting == null) { 12033 return PackageManager.INSTALL_FAILED_INVALID_URI; 12034 } 12035 if (!pkgSetting.getInstalled(userId)) { 12036 pkgSetting.setInstalled(true, userId); 12037 pkgSetting.setHidden(false, userId); 12038 mSettings.writePackageRestrictionsLPr(userId); 12039 installed = true; 12040 } 12041 } 12042 12043 if (installed) { 12044 if (pkgSetting.pkg != null) { 12045 synchronized (mInstallLock) { 12046 // We don't need to freeze for a brand new install 12047 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 12048 } 12049 } 12050 sendPackageAddedForUser(packageName, pkgSetting, userId); 12051 } 12052 } finally { 12053 Binder.restoreCallingIdentity(callingId); 12054 } 12055 12056 return PackageManager.INSTALL_SUCCEEDED; 12057 } 12058 12059 boolean isUserRestricted(int userId, String restrictionKey) { 12060 Bundle restrictions = sUserManager.getUserRestrictions(userId); 12061 if (restrictions.getBoolean(restrictionKey, false)) { 12062 Log.w(TAG, "User is restricted: " + restrictionKey); 12063 return true; 12064 } 12065 return false; 12066 } 12067 12068 @Override 12069 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 12070 int userId) { 12071 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12072 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12073 true /* requireFullPermission */, true /* checkShell */, 12074 "setPackagesSuspended for user " + userId); 12075 12076 if (ArrayUtils.isEmpty(packageNames)) { 12077 return packageNames; 12078 } 12079 12080 // List of package names for whom the suspended state has changed. 12081 List<String> changedPackages = new ArrayList<>(packageNames.length); 12082 // List of package names for whom the suspended state is not set as requested in this 12083 // method. 12084 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 12085 long callingId = Binder.clearCallingIdentity(); 12086 try { 12087 for (int i = 0; i < packageNames.length; i++) { 12088 String packageName = packageNames[i]; 12089 boolean changed = false; 12090 final int appId; 12091 synchronized (mPackages) { 12092 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12093 if (pkgSetting == null) { 12094 Slog.w(TAG, "Could not find package setting for package \"" + packageName 12095 + "\". Skipping suspending/un-suspending."); 12096 unactionedPackages.add(packageName); 12097 continue; 12098 } 12099 appId = pkgSetting.appId; 12100 if (pkgSetting.getSuspended(userId) != suspended) { 12101 if (!canSuspendPackageForUserLocked(packageName, userId)) { 12102 unactionedPackages.add(packageName); 12103 continue; 12104 } 12105 pkgSetting.setSuspended(suspended, userId); 12106 mSettings.writePackageRestrictionsLPr(userId); 12107 changed = true; 12108 changedPackages.add(packageName); 12109 } 12110 } 12111 12112 if (changed && suspended) { 12113 killApplication(packageName, UserHandle.getUid(userId, appId), 12114 "suspending package"); 12115 } 12116 } 12117 } finally { 12118 Binder.restoreCallingIdentity(callingId); 12119 } 12120 12121 if (!changedPackages.isEmpty()) { 12122 sendPackagesSuspendedForUser(changedPackages.toArray( 12123 new String[changedPackages.size()]), userId, suspended); 12124 } 12125 12126 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 12127 } 12128 12129 @Override 12130 public boolean isPackageSuspendedForUser(String packageName, int userId) { 12131 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12132 true /* requireFullPermission */, false /* checkShell */, 12133 "isPackageSuspendedForUser for user " + userId); 12134 synchronized (mPackages) { 12135 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12136 if (pkgSetting == null) { 12137 throw new IllegalArgumentException("Unknown target package: " + packageName); 12138 } 12139 return pkgSetting.getSuspended(userId); 12140 } 12141 } 12142 12143 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 12144 if (isPackageDeviceAdmin(packageName, userId)) { 12145 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12146 + "\": has an active device admin"); 12147 return false; 12148 } 12149 12150 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 12151 if (packageName.equals(activeLauncherPackageName)) { 12152 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12153 + "\": contains the active launcher"); 12154 return false; 12155 } 12156 12157 if (packageName.equals(mRequiredInstallerPackage)) { 12158 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12159 + "\": required for package installation"); 12160 return false; 12161 } 12162 12163 if (packageName.equals(mRequiredUninstallerPackage)) { 12164 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12165 + "\": required for package uninstallation"); 12166 return false; 12167 } 12168 12169 if (packageName.equals(mRequiredVerifierPackage)) { 12170 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12171 + "\": required for package verification"); 12172 return false; 12173 } 12174 12175 if (packageName.equals(getDefaultDialerPackageName(userId))) { 12176 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12177 + "\": is the default dialer"); 12178 return false; 12179 } 12180 12181 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12182 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12183 + "\": protected package"); 12184 return false; 12185 } 12186 12187 return true; 12188 } 12189 12190 private String getActiveLauncherPackageName(int userId) { 12191 Intent intent = new Intent(Intent.ACTION_MAIN); 12192 intent.addCategory(Intent.CATEGORY_HOME); 12193 ResolveInfo resolveInfo = resolveIntent( 12194 intent, 12195 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 12196 PackageManager.MATCH_DEFAULT_ONLY, 12197 userId); 12198 12199 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 12200 } 12201 12202 private String getDefaultDialerPackageName(int userId) { 12203 synchronized (mPackages) { 12204 return mSettings.getDefaultDialerPackageNameLPw(userId); 12205 } 12206 } 12207 12208 @Override 12209 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 12210 mContext.enforceCallingOrSelfPermission( 12211 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12212 "Only package verification agents can verify applications"); 12213 12214 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12215 final PackageVerificationResponse response = new PackageVerificationResponse( 12216 verificationCode, Binder.getCallingUid()); 12217 msg.arg1 = id; 12218 msg.obj = response; 12219 mHandler.sendMessage(msg); 12220 } 12221 12222 @Override 12223 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12224 long millisecondsToDelay) { 12225 mContext.enforceCallingOrSelfPermission( 12226 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12227 "Only package verification agents can extend verification timeouts"); 12228 12229 final PackageVerificationState state = mPendingVerification.get(id); 12230 final PackageVerificationResponse response = new PackageVerificationResponse( 12231 verificationCodeAtTimeout, Binder.getCallingUid()); 12232 12233 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12234 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12235 } 12236 if (millisecondsToDelay < 0) { 12237 millisecondsToDelay = 0; 12238 } 12239 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12240 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12241 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12242 } 12243 12244 if ((state != null) && !state.timeoutExtended()) { 12245 state.extendTimeout(); 12246 12247 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12248 msg.arg1 = id; 12249 msg.obj = response; 12250 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12251 } 12252 } 12253 12254 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12255 int verificationCode, UserHandle user) { 12256 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12257 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12258 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12259 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12260 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12261 12262 mContext.sendBroadcastAsUser(intent, user, 12263 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12264 } 12265 12266 private ComponentName matchComponentForVerifier(String packageName, 12267 List<ResolveInfo> receivers) { 12268 ActivityInfo targetReceiver = null; 12269 12270 final int NR = receivers.size(); 12271 for (int i = 0; i < NR; i++) { 12272 final ResolveInfo info = receivers.get(i); 12273 if (info.activityInfo == null) { 12274 continue; 12275 } 12276 12277 if (packageName.equals(info.activityInfo.packageName)) { 12278 targetReceiver = info.activityInfo; 12279 break; 12280 } 12281 } 12282 12283 if (targetReceiver == null) { 12284 return null; 12285 } 12286 12287 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12288 } 12289 12290 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12291 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12292 if (pkgInfo.verifiers.length == 0) { 12293 return null; 12294 } 12295 12296 final int N = pkgInfo.verifiers.length; 12297 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12298 for (int i = 0; i < N; i++) { 12299 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12300 12301 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12302 receivers); 12303 if (comp == null) { 12304 continue; 12305 } 12306 12307 final int verifierUid = getUidForVerifier(verifierInfo); 12308 if (verifierUid == -1) { 12309 continue; 12310 } 12311 12312 if (DEBUG_VERIFY) { 12313 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12314 + " with the correct signature"); 12315 } 12316 sufficientVerifiers.add(comp); 12317 verificationState.addSufficientVerifier(verifierUid); 12318 } 12319 12320 return sufficientVerifiers; 12321 } 12322 12323 private int getUidForVerifier(VerifierInfo verifierInfo) { 12324 synchronized (mPackages) { 12325 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12326 if (pkg == null) { 12327 return -1; 12328 } else if (pkg.mSignatures.length != 1) { 12329 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12330 + " has more than one signature; ignoring"); 12331 return -1; 12332 } 12333 12334 /* 12335 * If the public key of the package's signature does not match 12336 * our expected public key, then this is a different package and 12337 * we should skip. 12338 */ 12339 12340 final byte[] expectedPublicKey; 12341 try { 12342 final Signature verifierSig = pkg.mSignatures[0]; 12343 final PublicKey publicKey = verifierSig.getPublicKey(); 12344 expectedPublicKey = publicKey.getEncoded(); 12345 } catch (CertificateException e) { 12346 return -1; 12347 } 12348 12349 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12350 12351 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12352 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12353 + " does not have the expected public key; ignoring"); 12354 return -1; 12355 } 12356 12357 return pkg.applicationInfo.uid; 12358 } 12359 } 12360 12361 @Override 12362 public void finishPackageInstall(int token, boolean didLaunch) { 12363 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12364 12365 if (DEBUG_INSTALL) { 12366 Slog.v(TAG, "BM finishing package install for " + token); 12367 } 12368 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12369 12370 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12371 mHandler.sendMessage(msg); 12372 } 12373 12374 /** 12375 * Get the verification agent timeout. 12376 * 12377 * @return verification timeout in milliseconds 12378 */ 12379 private long getVerificationTimeout() { 12380 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12381 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12382 DEFAULT_VERIFICATION_TIMEOUT); 12383 } 12384 12385 /** 12386 * Get the default verification agent response code. 12387 * 12388 * @return default verification response code 12389 */ 12390 private int getDefaultVerificationResponse() { 12391 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12392 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12393 DEFAULT_VERIFICATION_RESPONSE); 12394 } 12395 12396 /** 12397 * Check whether or not package verification has been enabled. 12398 * 12399 * @return true if verification should be performed 12400 */ 12401 private boolean isVerificationEnabled(int userId, int installFlags) { 12402 if (!DEFAULT_VERIFY_ENABLE) { 12403 return false; 12404 } 12405 // Ephemeral apps don't get the full verification treatment 12406 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12407 if (DEBUG_EPHEMERAL) { 12408 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12409 } 12410 return false; 12411 } 12412 12413 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12414 12415 // Check if installing from ADB 12416 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12417 // Do not run verification in a test harness environment 12418 if (ActivityManager.isRunningInTestHarness()) { 12419 return false; 12420 } 12421 if (ensureVerifyAppsEnabled) { 12422 return true; 12423 } 12424 // Check if the developer does not want package verification for ADB installs 12425 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12426 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12427 return false; 12428 } 12429 } 12430 12431 if (ensureVerifyAppsEnabled) { 12432 return true; 12433 } 12434 12435 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12436 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12437 } 12438 12439 @Override 12440 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12441 throws RemoteException { 12442 mContext.enforceCallingOrSelfPermission( 12443 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12444 "Only intentfilter verification agents can verify applications"); 12445 12446 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12447 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12448 Binder.getCallingUid(), verificationCode, failedDomains); 12449 msg.arg1 = id; 12450 msg.obj = response; 12451 mHandler.sendMessage(msg); 12452 } 12453 12454 @Override 12455 public int getIntentVerificationStatus(String packageName, int userId) { 12456 synchronized (mPackages) { 12457 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12458 } 12459 } 12460 12461 @Override 12462 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12463 mContext.enforceCallingOrSelfPermission( 12464 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12465 12466 boolean result = false; 12467 synchronized (mPackages) { 12468 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12469 } 12470 if (result) { 12471 scheduleWritePackageRestrictionsLocked(userId); 12472 } 12473 return result; 12474 } 12475 12476 @Override 12477 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12478 String packageName) { 12479 synchronized (mPackages) { 12480 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12481 } 12482 } 12483 12484 @Override 12485 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12486 if (TextUtils.isEmpty(packageName)) { 12487 return ParceledListSlice.emptyList(); 12488 } 12489 synchronized (mPackages) { 12490 PackageParser.Package pkg = mPackages.get(packageName); 12491 if (pkg == null || pkg.activities == null) { 12492 return ParceledListSlice.emptyList(); 12493 } 12494 final int count = pkg.activities.size(); 12495 ArrayList<IntentFilter> result = new ArrayList<>(); 12496 for (int n=0; n<count; n++) { 12497 PackageParser.Activity activity = pkg.activities.get(n); 12498 if (activity.intents != null && activity.intents.size() > 0) { 12499 result.addAll(activity.intents); 12500 } 12501 } 12502 return new ParceledListSlice<>(result); 12503 } 12504 } 12505 12506 @Override 12507 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12508 mContext.enforceCallingOrSelfPermission( 12509 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12510 12511 synchronized (mPackages) { 12512 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12513 if (packageName != null) { 12514 result |= updateIntentVerificationStatus(packageName, 12515 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12516 userId); 12517 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12518 packageName, userId); 12519 } 12520 return result; 12521 } 12522 } 12523 12524 @Override 12525 public String getDefaultBrowserPackageName(int userId) { 12526 synchronized (mPackages) { 12527 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12528 } 12529 } 12530 12531 /** 12532 * Get the "allow unknown sources" setting. 12533 * 12534 * @return the current "allow unknown sources" setting 12535 */ 12536 private int getUnknownSourcesSettings() { 12537 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12538 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12539 -1); 12540 } 12541 12542 @Override 12543 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12544 final int uid = Binder.getCallingUid(); 12545 // writer 12546 synchronized (mPackages) { 12547 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12548 if (targetPackageSetting == null) { 12549 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12550 } 12551 12552 PackageSetting installerPackageSetting; 12553 if (installerPackageName != null) { 12554 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12555 if (installerPackageSetting == null) { 12556 throw new IllegalArgumentException("Unknown installer package: " 12557 + installerPackageName); 12558 } 12559 } else { 12560 installerPackageSetting = null; 12561 } 12562 12563 Signature[] callerSignature; 12564 Object obj = mSettings.getUserIdLPr(uid); 12565 if (obj != null) { 12566 if (obj instanceof SharedUserSetting) { 12567 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12568 } else if (obj instanceof PackageSetting) { 12569 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12570 } else { 12571 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12572 } 12573 } else { 12574 throw new SecurityException("Unknown calling UID: " + uid); 12575 } 12576 12577 // Verify: can't set installerPackageName to a package that is 12578 // not signed with the same cert as the caller. 12579 if (installerPackageSetting != null) { 12580 if (compareSignatures(callerSignature, 12581 installerPackageSetting.signatures.mSignatures) 12582 != PackageManager.SIGNATURE_MATCH) { 12583 throw new SecurityException( 12584 "Caller does not have same cert as new installer package " 12585 + installerPackageName); 12586 } 12587 } 12588 12589 // Verify: if target already has an installer package, it must 12590 // be signed with the same cert as the caller. 12591 if (targetPackageSetting.installerPackageName != null) { 12592 PackageSetting setting = mSettings.mPackages.get( 12593 targetPackageSetting.installerPackageName); 12594 // If the currently set package isn't valid, then it's always 12595 // okay to change it. 12596 if (setting != null) { 12597 if (compareSignatures(callerSignature, 12598 setting.signatures.mSignatures) 12599 != PackageManager.SIGNATURE_MATCH) { 12600 throw new SecurityException( 12601 "Caller does not have same cert as old installer package " 12602 + targetPackageSetting.installerPackageName); 12603 } 12604 } 12605 } 12606 12607 // Okay! 12608 targetPackageSetting.installerPackageName = installerPackageName; 12609 if (installerPackageName != null) { 12610 mSettings.mInstallerPackages.add(installerPackageName); 12611 } 12612 scheduleWriteSettingsLocked(); 12613 } 12614 } 12615 12616 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12617 // Queue up an async operation since the package installation may take a little while. 12618 mHandler.post(new Runnable() { 12619 public void run() { 12620 mHandler.removeCallbacks(this); 12621 // Result object to be returned 12622 PackageInstalledInfo res = new PackageInstalledInfo(); 12623 res.setReturnCode(currentStatus); 12624 res.uid = -1; 12625 res.pkg = null; 12626 res.removedInfo = null; 12627 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12628 args.doPreInstall(res.returnCode); 12629 synchronized (mInstallLock) { 12630 installPackageTracedLI(args, res); 12631 } 12632 args.doPostInstall(res.returnCode, res.uid); 12633 } 12634 12635 // A restore should be performed at this point if (a) the install 12636 // succeeded, (b) the operation is not an update, and (c) the new 12637 // package has not opted out of backup participation. 12638 final boolean update = res.removedInfo != null 12639 && res.removedInfo.removedPackage != null; 12640 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12641 boolean doRestore = !update 12642 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12643 12644 // Set up the post-install work request bookkeeping. This will be used 12645 // and cleaned up by the post-install event handling regardless of whether 12646 // there's a restore pass performed. Token values are >= 1. 12647 int token; 12648 if (mNextInstallToken < 0) mNextInstallToken = 1; 12649 token = mNextInstallToken++; 12650 12651 PostInstallData data = new PostInstallData(args, res); 12652 mRunningInstalls.put(token, data); 12653 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12654 12655 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12656 // Pass responsibility to the Backup Manager. It will perform a 12657 // restore if appropriate, then pass responsibility back to the 12658 // Package Manager to run the post-install observer callbacks 12659 // and broadcasts. 12660 IBackupManager bm = IBackupManager.Stub.asInterface( 12661 ServiceManager.getService(Context.BACKUP_SERVICE)); 12662 if (bm != null) { 12663 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12664 + " to BM for possible restore"); 12665 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12666 try { 12667 // TODO: http://b/22388012 12668 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12669 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12670 } else { 12671 doRestore = false; 12672 } 12673 } catch (RemoteException e) { 12674 // can't happen; the backup manager is local 12675 } catch (Exception e) { 12676 Slog.e(TAG, "Exception trying to enqueue restore", e); 12677 doRestore = false; 12678 } 12679 } else { 12680 Slog.e(TAG, "Backup Manager not found!"); 12681 doRestore = false; 12682 } 12683 } 12684 12685 if (!doRestore) { 12686 // No restore possible, or the Backup Manager was mysteriously not 12687 // available -- just fire the post-install work request directly. 12688 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12689 12690 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12691 12692 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12693 mHandler.sendMessage(msg); 12694 } 12695 } 12696 }); 12697 } 12698 12699 /** 12700 * Callback from PackageSettings whenever an app is first transitioned out of the 12701 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12702 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12703 * here whether the app is the target of an ongoing install, and only send the 12704 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12705 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12706 * handling. 12707 */ 12708 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12709 // Serialize this with the rest of the install-process message chain. In the 12710 // restore-at-install case, this Runnable will necessarily run before the 12711 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12712 // are coherent. In the non-restore case, the app has already completed install 12713 // and been launched through some other means, so it is not in a problematic 12714 // state for observers to see the FIRST_LAUNCH signal. 12715 mHandler.post(new Runnable() { 12716 @Override 12717 public void run() { 12718 for (int i = 0; i < mRunningInstalls.size(); i++) { 12719 final PostInstallData data = mRunningInstalls.valueAt(i); 12720 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12721 continue; 12722 } 12723 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12724 // right package; but is it for the right user? 12725 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12726 if (userId == data.res.newUsers[uIndex]) { 12727 if (DEBUG_BACKUP) { 12728 Slog.i(TAG, "Package " + pkgName 12729 + " being restored so deferring FIRST_LAUNCH"); 12730 } 12731 return; 12732 } 12733 } 12734 } 12735 } 12736 // didn't find it, so not being restored 12737 if (DEBUG_BACKUP) { 12738 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12739 } 12740 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12741 } 12742 }); 12743 } 12744 12745 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12746 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12747 installerPkg, null, userIds); 12748 } 12749 12750 private abstract class HandlerParams { 12751 private static final int MAX_RETRIES = 4; 12752 12753 /** 12754 * Number of times startCopy() has been attempted and had a non-fatal 12755 * error. 12756 */ 12757 private int mRetries = 0; 12758 12759 /** User handle for the user requesting the information or installation. */ 12760 private final UserHandle mUser; 12761 String traceMethod; 12762 int traceCookie; 12763 12764 HandlerParams(UserHandle user) { 12765 mUser = user; 12766 } 12767 12768 UserHandle getUser() { 12769 return mUser; 12770 } 12771 12772 HandlerParams setTraceMethod(String traceMethod) { 12773 this.traceMethod = traceMethod; 12774 return this; 12775 } 12776 12777 HandlerParams setTraceCookie(int traceCookie) { 12778 this.traceCookie = traceCookie; 12779 return this; 12780 } 12781 12782 final boolean startCopy() { 12783 boolean res; 12784 try { 12785 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12786 12787 if (++mRetries > MAX_RETRIES) { 12788 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12789 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12790 handleServiceError(); 12791 return false; 12792 } else { 12793 handleStartCopy(); 12794 res = true; 12795 } 12796 } catch (RemoteException e) { 12797 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12798 mHandler.sendEmptyMessage(MCS_RECONNECT); 12799 res = false; 12800 } 12801 handleReturnCode(); 12802 return res; 12803 } 12804 12805 final void serviceError() { 12806 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12807 handleServiceError(); 12808 handleReturnCode(); 12809 } 12810 12811 abstract void handleStartCopy() throws RemoteException; 12812 abstract void handleServiceError(); 12813 abstract void handleReturnCode(); 12814 } 12815 12816 class MeasureParams extends HandlerParams { 12817 private final PackageStats mStats; 12818 private boolean mSuccess; 12819 12820 private final IPackageStatsObserver mObserver; 12821 12822 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12823 super(new UserHandle(stats.userHandle)); 12824 mObserver = observer; 12825 mStats = stats; 12826 } 12827 12828 @Override 12829 public String toString() { 12830 return "MeasureParams{" 12831 + Integer.toHexString(System.identityHashCode(this)) 12832 + " " + mStats.packageName + "}"; 12833 } 12834 12835 @Override 12836 void handleStartCopy() throws RemoteException { 12837 synchronized (mInstallLock) { 12838 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12839 } 12840 12841 if (mSuccess) { 12842 boolean mounted = false; 12843 try { 12844 final String status = Environment.getExternalStorageState(); 12845 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12846 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12847 } catch (Exception e) { 12848 } 12849 12850 if (mounted) { 12851 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12852 12853 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12854 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12855 12856 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12857 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12858 12859 // Always subtract cache size, since it's a subdirectory 12860 mStats.externalDataSize -= mStats.externalCacheSize; 12861 12862 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12863 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12864 12865 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12866 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12867 } 12868 } 12869 } 12870 12871 @Override 12872 void handleReturnCode() { 12873 if (mObserver != null) { 12874 try { 12875 mObserver.onGetStatsCompleted(mStats, mSuccess); 12876 } catch (RemoteException e) { 12877 Slog.i(TAG, "Observer no longer exists."); 12878 } 12879 } 12880 } 12881 12882 @Override 12883 void handleServiceError() { 12884 Slog.e(TAG, "Could not measure application " + mStats.packageName 12885 + " external storage"); 12886 } 12887 } 12888 12889 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12890 throws RemoteException { 12891 long result = 0; 12892 for (File path : paths) { 12893 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12894 } 12895 return result; 12896 } 12897 12898 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12899 for (File path : paths) { 12900 try { 12901 mcs.clearDirectory(path.getAbsolutePath()); 12902 } catch (RemoteException e) { 12903 } 12904 } 12905 } 12906 12907 static class OriginInfo { 12908 /** 12909 * Location where install is coming from, before it has been 12910 * copied/renamed into place. This could be a single monolithic APK 12911 * file, or a cluster directory. This location may be untrusted. 12912 */ 12913 final File file; 12914 final String cid; 12915 12916 /** 12917 * Flag indicating that {@link #file} or {@link #cid} has already been 12918 * staged, meaning downstream users don't need to defensively copy the 12919 * contents. 12920 */ 12921 final boolean staged; 12922 12923 /** 12924 * Flag indicating that {@link #file} or {@link #cid} is an already 12925 * installed app that is being moved. 12926 */ 12927 final boolean existing; 12928 12929 final String resolvedPath; 12930 final File resolvedFile; 12931 12932 static OriginInfo fromNothing() { 12933 return new OriginInfo(null, null, false, false); 12934 } 12935 12936 static OriginInfo fromUntrustedFile(File file) { 12937 return new OriginInfo(file, null, false, false); 12938 } 12939 12940 static OriginInfo fromExistingFile(File file) { 12941 return new OriginInfo(file, null, false, true); 12942 } 12943 12944 static OriginInfo fromStagedFile(File file) { 12945 return new OriginInfo(file, null, true, false); 12946 } 12947 12948 static OriginInfo fromStagedContainer(String cid) { 12949 return new OriginInfo(null, cid, true, false); 12950 } 12951 12952 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12953 this.file = file; 12954 this.cid = cid; 12955 this.staged = staged; 12956 this.existing = existing; 12957 12958 if (cid != null) { 12959 resolvedPath = PackageHelper.getSdDir(cid); 12960 resolvedFile = new File(resolvedPath); 12961 } else if (file != null) { 12962 resolvedPath = file.getAbsolutePath(); 12963 resolvedFile = file; 12964 } else { 12965 resolvedPath = null; 12966 resolvedFile = null; 12967 } 12968 } 12969 } 12970 12971 static class MoveInfo { 12972 final int moveId; 12973 final String fromUuid; 12974 final String toUuid; 12975 final String packageName; 12976 final String dataAppName; 12977 final int appId; 12978 final String seinfo; 12979 final int targetSdkVersion; 12980 12981 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12982 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12983 this.moveId = moveId; 12984 this.fromUuid = fromUuid; 12985 this.toUuid = toUuid; 12986 this.packageName = packageName; 12987 this.dataAppName = dataAppName; 12988 this.appId = appId; 12989 this.seinfo = seinfo; 12990 this.targetSdkVersion = targetSdkVersion; 12991 } 12992 } 12993 12994 static class VerificationInfo { 12995 /** A constant used to indicate that a uid value is not present. */ 12996 public static final int NO_UID = -1; 12997 12998 /** URI referencing where the package was downloaded from. */ 12999 final Uri originatingUri; 13000 13001 /** HTTP referrer URI associated with the originatingURI. */ 13002 final Uri referrer; 13003 13004 /** UID of the application that the install request originated from. */ 13005 final int originatingUid; 13006 13007 /** UID of application requesting the install */ 13008 final int installerUid; 13009 13010 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 13011 this.originatingUri = originatingUri; 13012 this.referrer = referrer; 13013 this.originatingUid = originatingUid; 13014 this.installerUid = installerUid; 13015 } 13016 } 13017 13018 class InstallParams extends HandlerParams { 13019 final OriginInfo origin; 13020 final MoveInfo move; 13021 final IPackageInstallObserver2 observer; 13022 int installFlags; 13023 final String installerPackageName; 13024 final String volumeUuid; 13025 private InstallArgs mArgs; 13026 private int mRet; 13027 final String packageAbiOverride; 13028 final String[] grantedRuntimePermissions; 13029 final VerificationInfo verificationInfo; 13030 final Certificate[][] certificates; 13031 13032 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13033 int installFlags, String installerPackageName, String volumeUuid, 13034 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 13035 String[] grantedPermissions, Certificate[][] certificates) { 13036 super(user); 13037 this.origin = origin; 13038 this.move = move; 13039 this.observer = observer; 13040 this.installFlags = installFlags; 13041 this.installerPackageName = installerPackageName; 13042 this.volumeUuid = volumeUuid; 13043 this.verificationInfo = verificationInfo; 13044 this.packageAbiOverride = packageAbiOverride; 13045 this.grantedRuntimePermissions = grantedPermissions; 13046 this.certificates = certificates; 13047 } 13048 13049 @Override 13050 public String toString() { 13051 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 13052 + " file=" + origin.file + " cid=" + origin.cid + "}"; 13053 } 13054 13055 private int installLocationPolicy(PackageInfoLite pkgLite) { 13056 String packageName = pkgLite.packageName; 13057 int installLocation = pkgLite.installLocation; 13058 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13059 // reader 13060 synchronized (mPackages) { 13061 // Currently installed package which the new package is attempting to replace or 13062 // null if no such package is installed. 13063 PackageParser.Package installedPkg = mPackages.get(packageName); 13064 // Package which currently owns the data which the new package will own if installed. 13065 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 13066 // will be null whereas dataOwnerPkg will contain information about the package 13067 // which was uninstalled while keeping its data. 13068 PackageParser.Package dataOwnerPkg = installedPkg; 13069 if (dataOwnerPkg == null) { 13070 PackageSetting ps = mSettings.mPackages.get(packageName); 13071 if (ps != null) { 13072 dataOwnerPkg = ps.pkg; 13073 } 13074 } 13075 13076 if (dataOwnerPkg != null) { 13077 // If installed, the package will get access to data left on the device by its 13078 // predecessor. As a security measure, this is permited only if this is not a 13079 // version downgrade or if the predecessor package is marked as debuggable and 13080 // a downgrade is explicitly requested. 13081 // 13082 // On debuggable platform builds, downgrades are permitted even for 13083 // non-debuggable packages to make testing easier. Debuggable platform builds do 13084 // not offer security guarantees and thus it's OK to disable some security 13085 // mechanisms to make debugging/testing easier on those builds. However, even on 13086 // debuggable builds downgrades of packages are permitted only if requested via 13087 // installFlags. This is because we aim to keep the behavior of debuggable 13088 // platform builds as close as possible to the behavior of non-debuggable 13089 // platform builds. 13090 final boolean downgradeRequested = 13091 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 13092 final boolean packageDebuggable = 13093 (dataOwnerPkg.applicationInfo.flags 13094 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 13095 final boolean downgradePermitted = 13096 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 13097 if (!downgradePermitted) { 13098 try { 13099 checkDowngrade(dataOwnerPkg, pkgLite); 13100 } catch (PackageManagerException e) { 13101 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 13102 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 13103 } 13104 } 13105 } 13106 13107 if (installedPkg != null) { 13108 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13109 // Check for updated system application. 13110 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13111 if (onSd) { 13112 Slog.w(TAG, "Cannot install update to system app on sdcard"); 13113 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 13114 } 13115 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13116 } else { 13117 if (onSd) { 13118 // Install flag overrides everything. 13119 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13120 } 13121 // If current upgrade specifies particular preference 13122 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 13123 // Application explicitly specified internal. 13124 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13125 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 13126 // App explictly prefers external. Let policy decide 13127 } else { 13128 // Prefer previous location 13129 if (isExternal(installedPkg)) { 13130 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13131 } 13132 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13133 } 13134 } 13135 } else { 13136 // Invalid install. Return error code 13137 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 13138 } 13139 } 13140 } 13141 // All the special cases have been taken care of. 13142 // Return result based on recommended install location. 13143 if (onSd) { 13144 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13145 } 13146 return pkgLite.recommendedInstallLocation; 13147 } 13148 13149 /* 13150 * Invoke remote method to get package information and install 13151 * location values. Override install location based on default 13152 * policy if needed and then create install arguments based 13153 * on the install location. 13154 */ 13155 public void handleStartCopy() throws RemoteException { 13156 int ret = PackageManager.INSTALL_SUCCEEDED; 13157 13158 // If we're already staged, we've firmly committed to an install location 13159 if (origin.staged) { 13160 if (origin.file != null) { 13161 installFlags |= PackageManager.INSTALL_INTERNAL; 13162 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13163 } else if (origin.cid != null) { 13164 installFlags |= PackageManager.INSTALL_EXTERNAL; 13165 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13166 } else { 13167 throw new IllegalStateException("Invalid stage location"); 13168 } 13169 } 13170 13171 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13172 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 13173 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13174 PackageInfoLite pkgLite = null; 13175 13176 if (onInt && onSd) { 13177 // Check if both bits are set. 13178 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 13179 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13180 } else if (onSd && ephemeral) { 13181 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 13182 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13183 } else { 13184 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 13185 packageAbiOverride); 13186 13187 if (DEBUG_EPHEMERAL && ephemeral) { 13188 Slog.v(TAG, "pkgLite for install: " + pkgLite); 13189 } 13190 13191 /* 13192 * If we have too little free space, try to free cache 13193 * before giving up. 13194 */ 13195 if (!origin.staged && pkgLite.recommendedInstallLocation 13196 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13197 // TODO: focus freeing disk space on the target device 13198 final StorageManager storage = StorageManager.from(mContext); 13199 final long lowThreshold = storage.getStorageLowBytes( 13200 Environment.getDataDirectory()); 13201 13202 final long sizeBytes = mContainerService.calculateInstalledSize( 13203 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 13204 13205 try { 13206 mInstaller.freeCache(null, sizeBytes + lowThreshold); 13207 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 13208 installFlags, packageAbiOverride); 13209 } catch (InstallerException e) { 13210 Slog.w(TAG, "Failed to free cache", e); 13211 } 13212 13213 /* 13214 * The cache free must have deleted the file we 13215 * downloaded to install. 13216 * 13217 * TODO: fix the "freeCache" call to not delete 13218 * the file we care about. 13219 */ 13220 if (pkgLite.recommendedInstallLocation 13221 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13222 pkgLite.recommendedInstallLocation 13223 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 13224 } 13225 } 13226 } 13227 13228 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13229 int loc = pkgLite.recommendedInstallLocation; 13230 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13231 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13232 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13233 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13234 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13235 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13236 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13237 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13238 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13239 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13240 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13241 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13242 } else { 13243 // Override with defaults if needed. 13244 loc = installLocationPolicy(pkgLite); 13245 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13246 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13247 } else if (!onSd && !onInt) { 13248 // Override install location with flags 13249 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13250 // Set the flag to install on external media. 13251 installFlags |= PackageManager.INSTALL_EXTERNAL; 13252 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13253 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13254 if (DEBUG_EPHEMERAL) { 13255 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13256 } 13257 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13258 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13259 |PackageManager.INSTALL_INTERNAL); 13260 } else { 13261 // Make sure the flag for installing on external 13262 // media is unset 13263 installFlags |= PackageManager.INSTALL_INTERNAL; 13264 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13265 } 13266 } 13267 } 13268 } 13269 13270 final InstallArgs args = createInstallArgs(this); 13271 mArgs = args; 13272 13273 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13274 // TODO: http://b/22976637 13275 // Apps installed for "all" users use the device owner to verify the app 13276 UserHandle verifierUser = getUser(); 13277 if (verifierUser == UserHandle.ALL) { 13278 verifierUser = UserHandle.SYSTEM; 13279 } 13280 13281 /* 13282 * Determine if we have any installed package verifiers. If we 13283 * do, then we'll defer to them to verify the packages. 13284 */ 13285 final int requiredUid = mRequiredVerifierPackage == null ? -1 13286 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13287 verifierUser.getIdentifier()); 13288 if (!origin.existing && requiredUid != -1 13289 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13290 final Intent verification = new Intent( 13291 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13292 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13293 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13294 PACKAGE_MIME_TYPE); 13295 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13296 13297 // Query all live verifiers based on current user state 13298 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13299 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13300 13301 if (DEBUG_VERIFY) { 13302 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13303 + verification.toString() + " with " + pkgLite.verifiers.length 13304 + " optional verifiers"); 13305 } 13306 13307 final int verificationId = mPendingVerificationToken++; 13308 13309 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13310 13311 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13312 installerPackageName); 13313 13314 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13315 installFlags); 13316 13317 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13318 pkgLite.packageName); 13319 13320 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13321 pkgLite.versionCode); 13322 13323 if (verificationInfo != null) { 13324 if (verificationInfo.originatingUri != null) { 13325 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13326 verificationInfo.originatingUri); 13327 } 13328 if (verificationInfo.referrer != null) { 13329 verification.putExtra(Intent.EXTRA_REFERRER, 13330 verificationInfo.referrer); 13331 } 13332 if (verificationInfo.originatingUid >= 0) { 13333 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13334 verificationInfo.originatingUid); 13335 } 13336 if (verificationInfo.installerUid >= 0) { 13337 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13338 verificationInfo.installerUid); 13339 } 13340 } 13341 13342 final PackageVerificationState verificationState = new PackageVerificationState( 13343 requiredUid, args); 13344 13345 mPendingVerification.append(verificationId, verificationState); 13346 13347 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13348 receivers, verificationState); 13349 13350 /* 13351 * If any sufficient verifiers were listed in the package 13352 * manifest, attempt to ask them. 13353 */ 13354 if (sufficientVerifiers != null) { 13355 final int N = sufficientVerifiers.size(); 13356 if (N == 0) { 13357 Slog.i(TAG, "Additional verifiers required, but none installed."); 13358 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13359 } else { 13360 for (int i = 0; i < N; i++) { 13361 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13362 13363 final Intent sufficientIntent = new Intent(verification); 13364 sufficientIntent.setComponent(verifierComponent); 13365 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13366 } 13367 } 13368 } 13369 13370 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13371 mRequiredVerifierPackage, receivers); 13372 if (ret == PackageManager.INSTALL_SUCCEEDED 13373 && mRequiredVerifierPackage != null) { 13374 Trace.asyncTraceBegin( 13375 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13376 /* 13377 * Send the intent to the required verification agent, 13378 * but only start the verification timeout after the 13379 * target BroadcastReceivers have run. 13380 */ 13381 verification.setComponent(requiredVerifierComponent); 13382 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13383 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13384 new BroadcastReceiver() { 13385 @Override 13386 public void onReceive(Context context, Intent intent) { 13387 final Message msg = mHandler 13388 .obtainMessage(CHECK_PENDING_VERIFICATION); 13389 msg.arg1 = verificationId; 13390 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13391 } 13392 }, null, 0, null, null); 13393 13394 /* 13395 * We don't want the copy to proceed until verification 13396 * succeeds, so null out this field. 13397 */ 13398 mArgs = null; 13399 } 13400 } else { 13401 /* 13402 * No package verification is enabled, so immediately start 13403 * the remote call to initiate copy using temporary file. 13404 */ 13405 ret = args.copyApk(mContainerService, true); 13406 } 13407 } 13408 13409 mRet = ret; 13410 } 13411 13412 @Override 13413 void handleReturnCode() { 13414 // If mArgs is null, then MCS couldn't be reached. When it 13415 // reconnects, it will try again to install. At that point, this 13416 // will succeed. 13417 if (mArgs != null) { 13418 processPendingInstall(mArgs, mRet); 13419 } 13420 } 13421 13422 @Override 13423 void handleServiceError() { 13424 mArgs = createInstallArgs(this); 13425 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13426 } 13427 13428 public boolean isForwardLocked() { 13429 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13430 } 13431 } 13432 13433 /** 13434 * Used during creation of InstallArgs 13435 * 13436 * @param installFlags package installation flags 13437 * @return true if should be installed on external storage 13438 */ 13439 private static boolean installOnExternalAsec(int installFlags) { 13440 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13441 return false; 13442 } 13443 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13444 return true; 13445 } 13446 return false; 13447 } 13448 13449 /** 13450 * Used during creation of InstallArgs 13451 * 13452 * @param installFlags package installation flags 13453 * @return true if should be installed as forward locked 13454 */ 13455 private static boolean installForwardLocked(int installFlags) { 13456 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13457 } 13458 13459 private InstallArgs createInstallArgs(InstallParams params) { 13460 if (params.move != null) { 13461 return new MoveInstallArgs(params); 13462 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13463 return new AsecInstallArgs(params); 13464 } else { 13465 return new FileInstallArgs(params); 13466 } 13467 } 13468 13469 /** 13470 * Create args that describe an existing installed package. Typically used 13471 * when cleaning up old installs, or used as a move source. 13472 */ 13473 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13474 String resourcePath, String[] instructionSets) { 13475 final boolean isInAsec; 13476 if (installOnExternalAsec(installFlags)) { 13477 /* Apps on SD card are always in ASEC containers. */ 13478 isInAsec = true; 13479 } else if (installForwardLocked(installFlags) 13480 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13481 /* 13482 * Forward-locked apps are only in ASEC containers if they're the 13483 * new style 13484 */ 13485 isInAsec = true; 13486 } else { 13487 isInAsec = false; 13488 } 13489 13490 if (isInAsec) { 13491 return new AsecInstallArgs(codePath, instructionSets, 13492 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13493 } else { 13494 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13495 } 13496 } 13497 13498 static abstract class InstallArgs { 13499 /** @see InstallParams#origin */ 13500 final OriginInfo origin; 13501 /** @see InstallParams#move */ 13502 final MoveInfo move; 13503 13504 final IPackageInstallObserver2 observer; 13505 // Always refers to PackageManager flags only 13506 final int installFlags; 13507 final String installerPackageName; 13508 final String volumeUuid; 13509 final UserHandle user; 13510 final String abiOverride; 13511 final String[] installGrantPermissions; 13512 /** If non-null, drop an async trace when the install completes */ 13513 final String traceMethod; 13514 final int traceCookie; 13515 final Certificate[][] certificates; 13516 13517 // The list of instruction sets supported by this app. This is currently 13518 // only used during the rmdex() phase to clean up resources. We can get rid of this 13519 // if we move dex files under the common app path. 13520 /* nullable */ String[] instructionSets; 13521 13522 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13523 int installFlags, String installerPackageName, String volumeUuid, 13524 UserHandle user, String[] instructionSets, 13525 String abiOverride, String[] installGrantPermissions, 13526 String traceMethod, int traceCookie, Certificate[][] certificates) { 13527 this.origin = origin; 13528 this.move = move; 13529 this.installFlags = installFlags; 13530 this.observer = observer; 13531 this.installerPackageName = installerPackageName; 13532 this.volumeUuid = volumeUuid; 13533 this.user = user; 13534 this.instructionSets = instructionSets; 13535 this.abiOverride = abiOverride; 13536 this.installGrantPermissions = installGrantPermissions; 13537 this.traceMethod = traceMethod; 13538 this.traceCookie = traceCookie; 13539 this.certificates = certificates; 13540 } 13541 13542 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13543 abstract int doPreInstall(int status); 13544 13545 /** 13546 * Rename package into final resting place. All paths on the given 13547 * scanned package should be updated to reflect the rename. 13548 */ 13549 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13550 abstract int doPostInstall(int status, int uid); 13551 13552 /** @see PackageSettingBase#codePathString */ 13553 abstract String getCodePath(); 13554 /** @see PackageSettingBase#resourcePathString */ 13555 abstract String getResourcePath(); 13556 13557 // Need installer lock especially for dex file removal. 13558 abstract void cleanUpResourcesLI(); 13559 abstract boolean doPostDeleteLI(boolean delete); 13560 13561 /** 13562 * Called before the source arguments are copied. This is used mostly 13563 * for MoveParams when it needs to read the source file to put it in the 13564 * destination. 13565 */ 13566 int doPreCopy() { 13567 return PackageManager.INSTALL_SUCCEEDED; 13568 } 13569 13570 /** 13571 * Called after the source arguments are copied. This is used mostly for 13572 * MoveParams when it needs to read the source file to put it in the 13573 * destination. 13574 */ 13575 int doPostCopy(int uid) { 13576 return PackageManager.INSTALL_SUCCEEDED; 13577 } 13578 13579 protected boolean isFwdLocked() { 13580 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13581 } 13582 13583 protected boolean isExternalAsec() { 13584 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13585 } 13586 13587 protected boolean isEphemeral() { 13588 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13589 } 13590 13591 UserHandle getUser() { 13592 return user; 13593 } 13594 } 13595 13596 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13597 if (!allCodePaths.isEmpty()) { 13598 if (instructionSets == null) { 13599 throw new IllegalStateException("instructionSet == null"); 13600 } 13601 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13602 for (String codePath : allCodePaths) { 13603 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13604 try { 13605 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13606 } catch (InstallerException ignored) { 13607 } 13608 } 13609 } 13610 } 13611 } 13612 13613 /** 13614 * Logic to handle installation of non-ASEC applications, including copying 13615 * and renaming logic. 13616 */ 13617 class FileInstallArgs extends InstallArgs { 13618 private File codeFile; 13619 private File resourceFile; 13620 13621 // Example topology: 13622 // /data/app/com.example/base.apk 13623 // /data/app/com.example/split_foo.apk 13624 // /data/app/com.example/lib/arm/libfoo.so 13625 // /data/app/com.example/lib/arm64/libfoo.so 13626 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13627 13628 /** New install */ 13629 FileInstallArgs(InstallParams params) { 13630 super(params.origin, params.move, params.observer, params.installFlags, 13631 params.installerPackageName, params.volumeUuid, 13632 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13633 params.grantedRuntimePermissions, 13634 params.traceMethod, params.traceCookie, params.certificates); 13635 if (isFwdLocked()) { 13636 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13637 } 13638 } 13639 13640 /** Existing install */ 13641 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13642 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13643 null, null, null, 0, null /*certificates*/); 13644 this.codeFile = (codePath != null) ? new File(codePath) : null; 13645 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13646 } 13647 13648 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13649 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13650 try { 13651 return doCopyApk(imcs, temp); 13652 } finally { 13653 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13654 } 13655 } 13656 13657 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13658 if (origin.staged) { 13659 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13660 codeFile = origin.file; 13661 resourceFile = origin.file; 13662 return PackageManager.INSTALL_SUCCEEDED; 13663 } 13664 13665 try { 13666 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13667 final File tempDir = 13668 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13669 codeFile = tempDir; 13670 resourceFile = tempDir; 13671 } catch (IOException e) { 13672 Slog.w(TAG, "Failed to create copy file: " + e); 13673 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13674 } 13675 13676 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13677 @Override 13678 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13679 if (!FileUtils.isValidExtFilename(name)) { 13680 throw new IllegalArgumentException("Invalid filename: " + name); 13681 } 13682 try { 13683 final File file = new File(codeFile, name); 13684 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13685 O_RDWR | O_CREAT, 0644); 13686 Os.chmod(file.getAbsolutePath(), 0644); 13687 return new ParcelFileDescriptor(fd); 13688 } catch (ErrnoException e) { 13689 throw new RemoteException("Failed to open: " + e.getMessage()); 13690 } 13691 } 13692 }; 13693 13694 int ret = PackageManager.INSTALL_SUCCEEDED; 13695 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13696 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13697 Slog.e(TAG, "Failed to copy package"); 13698 return ret; 13699 } 13700 13701 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13702 NativeLibraryHelper.Handle handle = null; 13703 try { 13704 handle = NativeLibraryHelper.Handle.create(codeFile); 13705 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13706 abiOverride); 13707 } catch (IOException e) { 13708 Slog.e(TAG, "Copying native libraries failed", e); 13709 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13710 } finally { 13711 IoUtils.closeQuietly(handle); 13712 } 13713 13714 return ret; 13715 } 13716 13717 int doPreInstall(int status) { 13718 if (status != PackageManager.INSTALL_SUCCEEDED) { 13719 cleanUp(); 13720 } 13721 return status; 13722 } 13723 13724 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13725 if (status != PackageManager.INSTALL_SUCCEEDED) { 13726 cleanUp(); 13727 return false; 13728 } 13729 13730 final File targetDir = codeFile.getParentFile(); 13731 final File beforeCodeFile = codeFile; 13732 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13733 13734 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13735 try { 13736 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13737 } catch (ErrnoException e) { 13738 Slog.w(TAG, "Failed to rename", e); 13739 return false; 13740 } 13741 13742 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13743 Slog.w(TAG, "Failed to restorecon"); 13744 return false; 13745 } 13746 13747 // Reflect the rename internally 13748 codeFile = afterCodeFile; 13749 resourceFile = afterCodeFile; 13750 13751 // Reflect the rename in scanned details 13752 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13753 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13754 afterCodeFile, pkg.baseCodePath)); 13755 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13756 afterCodeFile, pkg.splitCodePaths)); 13757 13758 // Reflect the rename in app info 13759 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13760 pkg.setApplicationInfoCodePath(pkg.codePath); 13761 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13762 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13763 pkg.setApplicationInfoResourcePath(pkg.codePath); 13764 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13765 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13766 13767 return true; 13768 } 13769 13770 int doPostInstall(int status, int uid) { 13771 if (status != PackageManager.INSTALL_SUCCEEDED) { 13772 cleanUp(); 13773 } 13774 return status; 13775 } 13776 13777 @Override 13778 String getCodePath() { 13779 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13780 } 13781 13782 @Override 13783 String getResourcePath() { 13784 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13785 } 13786 13787 private boolean cleanUp() { 13788 if (codeFile == null || !codeFile.exists()) { 13789 return false; 13790 } 13791 13792 removeCodePathLI(codeFile); 13793 13794 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13795 resourceFile.delete(); 13796 } 13797 13798 return true; 13799 } 13800 13801 void cleanUpResourcesLI() { 13802 // Try enumerating all code paths before deleting 13803 List<String> allCodePaths = Collections.EMPTY_LIST; 13804 if (codeFile != null && codeFile.exists()) { 13805 try { 13806 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13807 allCodePaths = pkg.getAllCodePaths(); 13808 } catch (PackageParserException e) { 13809 // Ignored; we tried our best 13810 } 13811 } 13812 13813 cleanUp(); 13814 removeDexFiles(allCodePaths, instructionSets); 13815 } 13816 13817 boolean doPostDeleteLI(boolean delete) { 13818 // XXX err, shouldn't we respect the delete flag? 13819 cleanUpResourcesLI(); 13820 return true; 13821 } 13822 } 13823 13824 private boolean isAsecExternal(String cid) { 13825 final String asecPath = PackageHelper.getSdFilesystem(cid); 13826 return !asecPath.startsWith(mAsecInternalPath); 13827 } 13828 13829 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13830 PackageManagerException { 13831 if (copyRet < 0) { 13832 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13833 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13834 throw new PackageManagerException(copyRet, message); 13835 } 13836 } 13837 } 13838 13839 /** 13840 * Extract the StorageManagerService "container ID" from the full code path of an 13841 * .apk. 13842 */ 13843 static String cidFromCodePath(String fullCodePath) { 13844 int eidx = fullCodePath.lastIndexOf("/"); 13845 String subStr1 = fullCodePath.substring(0, eidx); 13846 int sidx = subStr1.lastIndexOf("/"); 13847 return subStr1.substring(sidx+1, eidx); 13848 } 13849 13850 /** 13851 * Logic to handle installation of ASEC applications, including copying and 13852 * renaming logic. 13853 */ 13854 class AsecInstallArgs extends InstallArgs { 13855 static final String RES_FILE_NAME = "pkg.apk"; 13856 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13857 13858 String cid; 13859 String packagePath; 13860 String resourcePath; 13861 13862 /** New install */ 13863 AsecInstallArgs(InstallParams params) { 13864 super(params.origin, params.move, params.observer, params.installFlags, 13865 params.installerPackageName, params.volumeUuid, 13866 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13867 params.grantedRuntimePermissions, 13868 params.traceMethod, params.traceCookie, params.certificates); 13869 } 13870 13871 /** Existing install */ 13872 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13873 boolean isExternal, boolean isForwardLocked) { 13874 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13875 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13876 instructionSets, null, null, null, 0, null /*certificates*/); 13877 // Hackily pretend we're still looking at a full code path 13878 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13879 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13880 } 13881 13882 // Extract cid from fullCodePath 13883 int eidx = fullCodePath.lastIndexOf("/"); 13884 String subStr1 = fullCodePath.substring(0, eidx); 13885 int sidx = subStr1.lastIndexOf("/"); 13886 cid = subStr1.substring(sidx+1, eidx); 13887 setMountPath(subStr1); 13888 } 13889 13890 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13891 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13892 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13893 instructionSets, null, null, null, 0, null /*certificates*/); 13894 this.cid = cid; 13895 setMountPath(PackageHelper.getSdDir(cid)); 13896 } 13897 13898 void createCopyFile() { 13899 cid = mInstallerService.allocateExternalStageCidLegacy(); 13900 } 13901 13902 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13903 if (origin.staged && origin.cid != null) { 13904 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13905 cid = origin.cid; 13906 setMountPath(PackageHelper.getSdDir(cid)); 13907 return PackageManager.INSTALL_SUCCEEDED; 13908 } 13909 13910 if (temp) { 13911 createCopyFile(); 13912 } else { 13913 /* 13914 * Pre-emptively destroy the container since it's destroyed if 13915 * copying fails due to it existing anyway. 13916 */ 13917 PackageHelper.destroySdDir(cid); 13918 } 13919 13920 final String newMountPath = imcs.copyPackageToContainer( 13921 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13922 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13923 13924 if (newMountPath != null) { 13925 setMountPath(newMountPath); 13926 return PackageManager.INSTALL_SUCCEEDED; 13927 } else { 13928 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13929 } 13930 } 13931 13932 @Override 13933 String getCodePath() { 13934 return packagePath; 13935 } 13936 13937 @Override 13938 String getResourcePath() { 13939 return resourcePath; 13940 } 13941 13942 int doPreInstall(int status) { 13943 if (status != PackageManager.INSTALL_SUCCEEDED) { 13944 // Destroy container 13945 PackageHelper.destroySdDir(cid); 13946 } else { 13947 boolean mounted = PackageHelper.isContainerMounted(cid); 13948 if (!mounted) { 13949 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13950 Process.SYSTEM_UID); 13951 if (newMountPath != null) { 13952 setMountPath(newMountPath); 13953 } else { 13954 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13955 } 13956 } 13957 } 13958 return status; 13959 } 13960 13961 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13962 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13963 String newMountPath = null; 13964 if (PackageHelper.isContainerMounted(cid)) { 13965 // Unmount the container 13966 if (!PackageHelper.unMountSdDir(cid)) { 13967 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13968 return false; 13969 } 13970 } 13971 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13972 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13973 " which might be stale. Will try to clean up."); 13974 // Clean up the stale container and proceed to recreate. 13975 if (!PackageHelper.destroySdDir(newCacheId)) { 13976 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13977 return false; 13978 } 13979 // Successfully cleaned up stale container. Try to rename again. 13980 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13981 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13982 + " inspite of cleaning it up."); 13983 return false; 13984 } 13985 } 13986 if (!PackageHelper.isContainerMounted(newCacheId)) { 13987 Slog.w(TAG, "Mounting container " + newCacheId); 13988 newMountPath = PackageHelper.mountSdDir(newCacheId, 13989 getEncryptKey(), Process.SYSTEM_UID); 13990 } else { 13991 newMountPath = PackageHelper.getSdDir(newCacheId); 13992 } 13993 if (newMountPath == null) { 13994 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13995 return false; 13996 } 13997 Log.i(TAG, "Succesfully renamed " + cid + 13998 " to " + newCacheId + 13999 " at new path: " + newMountPath); 14000 cid = newCacheId; 14001 14002 final File beforeCodeFile = new File(packagePath); 14003 setMountPath(newMountPath); 14004 final File afterCodeFile = new File(packagePath); 14005 14006 // Reflect the rename in scanned details 14007 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14008 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14009 afterCodeFile, pkg.baseCodePath)); 14010 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14011 afterCodeFile, pkg.splitCodePaths)); 14012 14013 // Reflect the rename in app info 14014 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14015 pkg.setApplicationInfoCodePath(pkg.codePath); 14016 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14017 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14018 pkg.setApplicationInfoResourcePath(pkg.codePath); 14019 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14020 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14021 14022 return true; 14023 } 14024 14025 private void setMountPath(String mountPath) { 14026 final File mountFile = new File(mountPath); 14027 14028 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 14029 if (monolithicFile.exists()) { 14030 packagePath = monolithicFile.getAbsolutePath(); 14031 if (isFwdLocked()) { 14032 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 14033 } else { 14034 resourcePath = packagePath; 14035 } 14036 } else { 14037 packagePath = mountFile.getAbsolutePath(); 14038 resourcePath = packagePath; 14039 } 14040 } 14041 14042 int doPostInstall(int status, int uid) { 14043 if (status != PackageManager.INSTALL_SUCCEEDED) { 14044 cleanUp(); 14045 } else { 14046 final int groupOwner; 14047 final String protectedFile; 14048 if (isFwdLocked()) { 14049 groupOwner = UserHandle.getSharedAppGid(uid); 14050 protectedFile = RES_FILE_NAME; 14051 } else { 14052 groupOwner = -1; 14053 protectedFile = null; 14054 } 14055 14056 if (uid < Process.FIRST_APPLICATION_UID 14057 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 14058 Slog.e(TAG, "Failed to finalize " + cid); 14059 PackageHelper.destroySdDir(cid); 14060 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14061 } 14062 14063 boolean mounted = PackageHelper.isContainerMounted(cid); 14064 if (!mounted) { 14065 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 14066 } 14067 } 14068 return status; 14069 } 14070 14071 private void cleanUp() { 14072 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 14073 14074 // Destroy secure container 14075 PackageHelper.destroySdDir(cid); 14076 } 14077 14078 private List<String> getAllCodePaths() { 14079 final File codeFile = new File(getCodePath()); 14080 if (codeFile != null && codeFile.exists()) { 14081 try { 14082 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14083 return pkg.getAllCodePaths(); 14084 } catch (PackageParserException e) { 14085 // Ignored; we tried our best 14086 } 14087 } 14088 return Collections.EMPTY_LIST; 14089 } 14090 14091 void cleanUpResourcesLI() { 14092 // Enumerate all code paths before deleting 14093 cleanUpResourcesLI(getAllCodePaths()); 14094 } 14095 14096 private void cleanUpResourcesLI(List<String> allCodePaths) { 14097 cleanUp(); 14098 removeDexFiles(allCodePaths, instructionSets); 14099 } 14100 14101 String getPackageName() { 14102 return getAsecPackageName(cid); 14103 } 14104 14105 boolean doPostDeleteLI(boolean delete) { 14106 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 14107 final List<String> allCodePaths = getAllCodePaths(); 14108 boolean mounted = PackageHelper.isContainerMounted(cid); 14109 if (mounted) { 14110 // Unmount first 14111 if (PackageHelper.unMountSdDir(cid)) { 14112 mounted = false; 14113 } 14114 } 14115 if (!mounted && delete) { 14116 cleanUpResourcesLI(allCodePaths); 14117 } 14118 return !mounted; 14119 } 14120 14121 @Override 14122 int doPreCopy() { 14123 if (isFwdLocked()) { 14124 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 14125 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 14126 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14127 } 14128 } 14129 14130 return PackageManager.INSTALL_SUCCEEDED; 14131 } 14132 14133 @Override 14134 int doPostCopy(int uid) { 14135 if (isFwdLocked()) { 14136 if (uid < Process.FIRST_APPLICATION_UID 14137 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 14138 RES_FILE_NAME)) { 14139 Slog.e(TAG, "Failed to finalize " + cid); 14140 PackageHelper.destroySdDir(cid); 14141 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14142 } 14143 } 14144 14145 return PackageManager.INSTALL_SUCCEEDED; 14146 } 14147 } 14148 14149 /** 14150 * Logic to handle movement of existing installed applications. 14151 */ 14152 class MoveInstallArgs extends InstallArgs { 14153 private File codeFile; 14154 private File resourceFile; 14155 14156 /** New install */ 14157 MoveInstallArgs(InstallParams params) { 14158 super(params.origin, params.move, params.observer, params.installFlags, 14159 params.installerPackageName, params.volumeUuid, 14160 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14161 params.grantedRuntimePermissions, 14162 params.traceMethod, params.traceCookie, params.certificates); 14163 } 14164 14165 int copyApk(IMediaContainerService imcs, boolean temp) { 14166 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 14167 + move.fromUuid + " to " + move.toUuid); 14168 synchronized (mInstaller) { 14169 try { 14170 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 14171 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 14172 } catch (InstallerException e) { 14173 Slog.w(TAG, "Failed to move app", e); 14174 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14175 } 14176 } 14177 14178 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 14179 resourceFile = codeFile; 14180 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 14181 14182 return PackageManager.INSTALL_SUCCEEDED; 14183 } 14184 14185 int doPreInstall(int status) { 14186 if (status != PackageManager.INSTALL_SUCCEEDED) { 14187 cleanUp(move.toUuid); 14188 } 14189 return status; 14190 } 14191 14192 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14193 if (status != PackageManager.INSTALL_SUCCEEDED) { 14194 cleanUp(move.toUuid); 14195 return false; 14196 } 14197 14198 // Reflect the move in app info 14199 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14200 pkg.setApplicationInfoCodePath(pkg.codePath); 14201 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14202 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14203 pkg.setApplicationInfoResourcePath(pkg.codePath); 14204 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14205 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14206 14207 return true; 14208 } 14209 14210 int doPostInstall(int status, int uid) { 14211 if (status == PackageManager.INSTALL_SUCCEEDED) { 14212 cleanUp(move.fromUuid); 14213 } else { 14214 cleanUp(move.toUuid); 14215 } 14216 return status; 14217 } 14218 14219 @Override 14220 String getCodePath() { 14221 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14222 } 14223 14224 @Override 14225 String getResourcePath() { 14226 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14227 } 14228 14229 private boolean cleanUp(String volumeUuid) { 14230 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14231 move.dataAppName); 14232 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14233 final int[] userIds = sUserManager.getUserIds(); 14234 synchronized (mInstallLock) { 14235 // Clean up both app data and code 14236 // All package moves are frozen until finished 14237 for (int userId : userIds) { 14238 try { 14239 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14240 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14241 } catch (InstallerException e) { 14242 Slog.w(TAG, String.valueOf(e)); 14243 } 14244 } 14245 removeCodePathLI(codeFile); 14246 } 14247 return true; 14248 } 14249 14250 void cleanUpResourcesLI() { 14251 throw new UnsupportedOperationException(); 14252 } 14253 14254 boolean doPostDeleteLI(boolean delete) { 14255 throw new UnsupportedOperationException(); 14256 } 14257 } 14258 14259 static String getAsecPackageName(String packageCid) { 14260 int idx = packageCid.lastIndexOf("-"); 14261 if (idx == -1) { 14262 return packageCid; 14263 } 14264 return packageCid.substring(0, idx); 14265 } 14266 14267 // Utility method used to create code paths based on package name and available index. 14268 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14269 String idxStr = ""; 14270 int idx = 1; 14271 // Fall back to default value of idx=1 if prefix is not 14272 // part of oldCodePath 14273 if (oldCodePath != null) { 14274 String subStr = oldCodePath; 14275 // Drop the suffix right away 14276 if (suffix != null && subStr.endsWith(suffix)) { 14277 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14278 } 14279 // If oldCodePath already contains prefix find out the 14280 // ending index to either increment or decrement. 14281 int sidx = subStr.lastIndexOf(prefix); 14282 if (sidx != -1) { 14283 subStr = subStr.substring(sidx + prefix.length()); 14284 if (subStr != null) { 14285 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14286 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14287 } 14288 try { 14289 idx = Integer.parseInt(subStr); 14290 if (idx <= 1) { 14291 idx++; 14292 } else { 14293 idx--; 14294 } 14295 } catch(NumberFormatException e) { 14296 } 14297 } 14298 } 14299 } 14300 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14301 return prefix + idxStr; 14302 } 14303 14304 private File getNextCodePath(File targetDir, String packageName) { 14305 File result; 14306 SecureRandom random = new SecureRandom(); 14307 byte[] bytes = new byte[16]; 14308 do { 14309 random.nextBytes(bytes); 14310 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 14311 result = new File(targetDir, packageName + "-" + suffix); 14312 } while (result.exists()); 14313 return result; 14314 } 14315 14316 // Utility method that returns the relative package path with respect 14317 // to the installation directory. Like say for /data/data/com.test-1.apk 14318 // string com.test-1 is returned. 14319 static String deriveCodePathName(String codePath) { 14320 if (codePath == null) { 14321 return null; 14322 } 14323 final File codeFile = new File(codePath); 14324 final String name = codeFile.getName(); 14325 if (codeFile.isDirectory()) { 14326 return name; 14327 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14328 final int lastDot = name.lastIndexOf('.'); 14329 return name.substring(0, lastDot); 14330 } else { 14331 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14332 return null; 14333 } 14334 } 14335 14336 static class PackageInstalledInfo { 14337 String name; 14338 int uid; 14339 // The set of users that originally had this package installed. 14340 int[] origUsers; 14341 // The set of users that now have this package installed. 14342 int[] newUsers; 14343 PackageParser.Package pkg; 14344 int returnCode; 14345 String returnMsg; 14346 PackageRemovedInfo removedInfo; 14347 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14348 14349 public void setError(int code, String msg) { 14350 setReturnCode(code); 14351 setReturnMessage(msg); 14352 Slog.w(TAG, msg); 14353 } 14354 14355 public void setError(String msg, PackageParserException e) { 14356 setReturnCode(e.error); 14357 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14358 Slog.w(TAG, msg, e); 14359 } 14360 14361 public void setError(String msg, PackageManagerException e) { 14362 returnCode = e.error; 14363 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14364 Slog.w(TAG, msg, e); 14365 } 14366 14367 public void setReturnCode(int returnCode) { 14368 this.returnCode = returnCode; 14369 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14370 for (int i = 0; i < childCount; i++) { 14371 addedChildPackages.valueAt(i).returnCode = returnCode; 14372 } 14373 } 14374 14375 private void setReturnMessage(String returnMsg) { 14376 this.returnMsg = returnMsg; 14377 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14378 for (int i = 0; i < childCount; i++) { 14379 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14380 } 14381 } 14382 14383 // In some error cases we want to convey more info back to the observer 14384 String origPackage; 14385 String origPermission; 14386 } 14387 14388 /* 14389 * Install a non-existing package. 14390 */ 14391 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14392 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14393 PackageInstalledInfo res) { 14394 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14395 14396 // Remember this for later, in case we need to rollback this install 14397 String pkgName = pkg.packageName; 14398 14399 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14400 14401 synchronized(mPackages) { 14402 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 14403 if (renamedPackage != null) { 14404 // A package with the same name is already installed, though 14405 // it has been renamed to an older name. The package we 14406 // are trying to install should be installed as an update to 14407 // the existing one, but that has not been requested, so bail. 14408 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14409 + " without first uninstalling package running as " 14410 + renamedPackage); 14411 return; 14412 } 14413 if (mPackages.containsKey(pkgName)) { 14414 // Don't allow installation over an existing package with the same name. 14415 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14416 + " without first uninstalling."); 14417 return; 14418 } 14419 } 14420 14421 try { 14422 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14423 System.currentTimeMillis(), user); 14424 14425 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14426 14427 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14428 prepareAppDataAfterInstallLIF(newPackage); 14429 14430 } else { 14431 // Remove package from internal structures, but keep around any 14432 // data that might have already existed 14433 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14434 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14435 } 14436 } catch (PackageManagerException e) { 14437 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14438 } 14439 14440 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14441 } 14442 14443 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14444 // Can't rotate keys during boot or if sharedUser. 14445 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14446 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14447 return false; 14448 } 14449 // app is using upgradeKeySets; make sure all are valid 14450 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14451 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14452 for (int i = 0; i < upgradeKeySets.length; i++) { 14453 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14454 Slog.wtf(TAG, "Package " 14455 + (oldPs.name != null ? oldPs.name : "<null>") 14456 + " contains upgrade-key-set reference to unknown key-set: " 14457 + upgradeKeySets[i] 14458 + " reverting to signatures check."); 14459 return false; 14460 } 14461 } 14462 return true; 14463 } 14464 14465 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14466 // Upgrade keysets are being used. Determine if new package has a superset of the 14467 // required keys. 14468 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14469 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14470 for (int i = 0; i < upgradeKeySets.length; i++) { 14471 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14472 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14473 return true; 14474 } 14475 } 14476 return false; 14477 } 14478 14479 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14480 try (DigestInputStream digestStream = 14481 new DigestInputStream(new FileInputStream(file), digest)) { 14482 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14483 } 14484 } 14485 14486 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14487 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14488 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14489 14490 final PackageParser.Package oldPackage; 14491 final String pkgName = pkg.packageName; 14492 final int[] allUsers; 14493 final int[] installedUsers; 14494 14495 synchronized(mPackages) { 14496 oldPackage = mPackages.get(pkgName); 14497 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14498 14499 // don't allow upgrade to target a release SDK from a pre-release SDK 14500 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14501 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14502 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14503 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14504 if (oldTargetsPreRelease 14505 && !newTargetsPreRelease 14506 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14507 Slog.w(TAG, "Can't install package targeting released sdk"); 14508 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14509 return; 14510 } 14511 14512 // don't allow an upgrade from full to ephemeral 14513 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14514 if (isEphemeral && !oldIsEphemeral) { 14515 // can't downgrade from full to ephemeral 14516 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14517 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14518 return; 14519 } 14520 14521 // verify signatures are valid 14522 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14523 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14524 if (!checkUpgradeKeySetLP(ps, pkg)) { 14525 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14526 "New package not signed by keys specified by upgrade-keysets: " 14527 + pkgName); 14528 return; 14529 } 14530 } else { 14531 // default to original signature matching 14532 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14533 != PackageManager.SIGNATURE_MATCH) { 14534 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14535 "New package has a different signature: " + pkgName); 14536 return; 14537 } 14538 } 14539 14540 // don't allow a system upgrade unless the upgrade hash matches 14541 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14542 byte[] digestBytes = null; 14543 try { 14544 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14545 updateDigest(digest, new File(pkg.baseCodePath)); 14546 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14547 for (String path : pkg.splitCodePaths) { 14548 updateDigest(digest, new File(path)); 14549 } 14550 } 14551 digestBytes = digest.digest(); 14552 } catch (NoSuchAlgorithmException | IOException e) { 14553 res.setError(INSTALL_FAILED_INVALID_APK, 14554 "Could not compute hash: " + pkgName); 14555 return; 14556 } 14557 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14558 res.setError(INSTALL_FAILED_INVALID_APK, 14559 "New package fails restrict-update check: " + pkgName); 14560 return; 14561 } 14562 // retain upgrade restriction 14563 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14564 } 14565 14566 // Check for shared user id changes 14567 String invalidPackageName = 14568 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14569 if (invalidPackageName != null) { 14570 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14571 "Package " + invalidPackageName + " tried to change user " 14572 + oldPackage.mSharedUserId); 14573 return; 14574 } 14575 14576 // In case of rollback, remember per-user/profile install state 14577 allUsers = sUserManager.getUserIds(); 14578 installedUsers = ps.queryInstalledUsers(allUsers, true); 14579 } 14580 14581 // Update what is removed 14582 res.removedInfo = new PackageRemovedInfo(); 14583 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14584 res.removedInfo.removedPackage = oldPackage.packageName; 14585 res.removedInfo.isUpdate = true; 14586 res.removedInfo.origUsers = installedUsers; 14587 final int childCount = (oldPackage.childPackages != null) 14588 ? oldPackage.childPackages.size() : 0; 14589 for (int i = 0; i < childCount; i++) { 14590 boolean childPackageUpdated = false; 14591 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14592 if (res.addedChildPackages != null) { 14593 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14594 if (childRes != null) { 14595 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14596 childRes.removedInfo.removedPackage = childPkg.packageName; 14597 childRes.removedInfo.isUpdate = true; 14598 childPackageUpdated = true; 14599 } 14600 } 14601 if (!childPackageUpdated) { 14602 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14603 childRemovedRes.removedPackage = childPkg.packageName; 14604 childRemovedRes.isUpdate = false; 14605 childRemovedRes.dataRemoved = true; 14606 synchronized (mPackages) { 14607 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 14608 if (childPs != null) { 14609 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14610 } 14611 } 14612 if (res.removedInfo.removedChildPackages == null) { 14613 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14614 } 14615 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14616 } 14617 } 14618 14619 boolean sysPkg = (isSystemApp(oldPackage)); 14620 if (sysPkg) { 14621 // Set the system/privileged flags as needed 14622 final boolean privileged = 14623 (oldPackage.applicationInfo.privateFlags 14624 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14625 final int systemPolicyFlags = policyFlags 14626 | PackageParser.PARSE_IS_SYSTEM 14627 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14628 14629 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14630 user, allUsers, installerPackageName, res); 14631 } else { 14632 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14633 user, allUsers, installerPackageName, res); 14634 } 14635 } 14636 14637 public List<String> getPreviousCodePaths(String packageName) { 14638 final PackageSetting ps = mSettings.mPackages.get(packageName); 14639 final List<String> result = new ArrayList<String>(); 14640 if (ps != null && ps.oldCodePaths != null) { 14641 result.addAll(ps.oldCodePaths); 14642 } 14643 return result; 14644 } 14645 14646 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14647 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14648 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14649 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14650 + deletedPackage); 14651 14652 String pkgName = deletedPackage.packageName; 14653 boolean deletedPkg = true; 14654 boolean addedPkg = false; 14655 boolean updatedSettings = false; 14656 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14657 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14658 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14659 14660 final long origUpdateTime = (pkg.mExtras != null) 14661 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14662 14663 // First delete the existing package while retaining the data directory 14664 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14665 res.removedInfo, true, pkg)) { 14666 // If the existing package wasn't successfully deleted 14667 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14668 deletedPkg = false; 14669 } else { 14670 // Successfully deleted the old package; proceed with replace. 14671 14672 // If deleted package lived in a container, give users a chance to 14673 // relinquish resources before killing. 14674 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14675 if (DEBUG_INSTALL) { 14676 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14677 } 14678 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14679 final ArrayList<String> pkgList = new ArrayList<String>(1); 14680 pkgList.add(deletedPackage.applicationInfo.packageName); 14681 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14682 } 14683 14684 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14685 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14686 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14687 14688 try { 14689 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14690 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14691 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14692 14693 // Update the in-memory copy of the previous code paths. 14694 PackageSetting ps = mSettings.mPackages.get(pkgName); 14695 if (!killApp) { 14696 if (ps.oldCodePaths == null) { 14697 ps.oldCodePaths = new ArraySet<>(); 14698 } 14699 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14700 if (deletedPackage.splitCodePaths != null) { 14701 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14702 } 14703 } else { 14704 ps.oldCodePaths = null; 14705 } 14706 if (ps.childPackageNames != null) { 14707 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14708 final String childPkgName = ps.childPackageNames.get(i); 14709 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14710 childPs.oldCodePaths = ps.oldCodePaths; 14711 } 14712 } 14713 prepareAppDataAfterInstallLIF(newPackage); 14714 addedPkg = true; 14715 } catch (PackageManagerException e) { 14716 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14717 } 14718 } 14719 14720 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14721 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14722 14723 // Revert all internal state mutations and added folders for the failed install 14724 if (addedPkg) { 14725 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14726 res.removedInfo, true, null); 14727 } 14728 14729 // Restore the old package 14730 if (deletedPkg) { 14731 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14732 File restoreFile = new File(deletedPackage.codePath); 14733 // Parse old package 14734 boolean oldExternal = isExternal(deletedPackage); 14735 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14736 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14737 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14738 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14739 try { 14740 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14741 null); 14742 } catch (PackageManagerException e) { 14743 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14744 + e.getMessage()); 14745 return; 14746 } 14747 14748 synchronized (mPackages) { 14749 // Ensure the installer package name up to date 14750 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14751 14752 // Update permissions for restored package 14753 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14754 14755 mSettings.writeLPr(); 14756 } 14757 14758 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14759 } 14760 } else { 14761 synchronized (mPackages) { 14762 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 14763 if (ps != null) { 14764 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14765 if (res.removedInfo.removedChildPackages != null) { 14766 final int childCount = res.removedInfo.removedChildPackages.size(); 14767 // Iterate in reverse as we may modify the collection 14768 for (int i = childCount - 1; i >= 0; i--) { 14769 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14770 if (res.addedChildPackages.containsKey(childPackageName)) { 14771 res.removedInfo.removedChildPackages.removeAt(i); 14772 } else { 14773 PackageRemovedInfo childInfo = res.removedInfo 14774 .removedChildPackages.valueAt(i); 14775 childInfo.removedForAllUsers = mPackages.get( 14776 childInfo.removedPackage) == null; 14777 } 14778 } 14779 } 14780 } 14781 } 14782 } 14783 } 14784 14785 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14786 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14787 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14788 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14789 + ", old=" + deletedPackage); 14790 14791 final boolean disabledSystem; 14792 14793 // Remove existing system package 14794 removePackageLI(deletedPackage, true); 14795 14796 synchronized (mPackages) { 14797 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14798 } 14799 if (!disabledSystem) { 14800 // We didn't need to disable the .apk as a current system package, 14801 // which means we are replacing another update that is already 14802 // installed. We need to make sure to delete the older one's .apk. 14803 res.removedInfo.args = createInstallArgsForExisting(0, 14804 deletedPackage.applicationInfo.getCodePath(), 14805 deletedPackage.applicationInfo.getResourcePath(), 14806 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14807 } else { 14808 res.removedInfo.args = null; 14809 } 14810 14811 // Successfully disabled the old package. Now proceed with re-installation 14812 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14813 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14814 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14815 14816 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14817 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14818 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14819 14820 PackageParser.Package newPackage = null; 14821 try { 14822 // Add the package to the internal data structures 14823 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14824 14825 // Set the update and install times 14826 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14827 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14828 System.currentTimeMillis()); 14829 14830 // Update the package dynamic state if succeeded 14831 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14832 // Now that the install succeeded make sure we remove data 14833 // directories for any child package the update removed. 14834 final int deletedChildCount = (deletedPackage.childPackages != null) 14835 ? deletedPackage.childPackages.size() : 0; 14836 final int newChildCount = (newPackage.childPackages != null) 14837 ? newPackage.childPackages.size() : 0; 14838 for (int i = 0; i < deletedChildCount; i++) { 14839 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14840 boolean childPackageDeleted = true; 14841 for (int j = 0; j < newChildCount; j++) { 14842 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14843 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14844 childPackageDeleted = false; 14845 break; 14846 } 14847 } 14848 if (childPackageDeleted) { 14849 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14850 deletedChildPkg.packageName); 14851 if (ps != null && res.removedInfo.removedChildPackages != null) { 14852 PackageRemovedInfo removedChildRes = res.removedInfo 14853 .removedChildPackages.get(deletedChildPkg.packageName); 14854 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14855 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14856 } 14857 } 14858 } 14859 14860 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14861 prepareAppDataAfterInstallLIF(newPackage); 14862 } 14863 } catch (PackageManagerException e) { 14864 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14865 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14866 } 14867 14868 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14869 // Re installation failed. Restore old information 14870 // Remove new pkg information 14871 if (newPackage != null) { 14872 removeInstalledPackageLI(newPackage, true); 14873 } 14874 // Add back the old system package 14875 try { 14876 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14877 } catch (PackageManagerException e) { 14878 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14879 } 14880 14881 synchronized (mPackages) { 14882 if (disabledSystem) { 14883 enableSystemPackageLPw(deletedPackage); 14884 } 14885 14886 // Ensure the installer package name up to date 14887 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14888 14889 // Update permissions for restored package 14890 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14891 14892 mSettings.writeLPr(); 14893 } 14894 14895 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14896 + " after failed upgrade"); 14897 } 14898 } 14899 14900 /** 14901 * Checks whether the parent or any of the child packages have a change shared 14902 * user. For a package to be a valid update the shred users of the parent and 14903 * the children should match. We may later support changing child shared users. 14904 * @param oldPkg The updated package. 14905 * @param newPkg The update package. 14906 * @return The shared user that change between the versions. 14907 */ 14908 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14909 PackageParser.Package newPkg) { 14910 // Check parent shared user 14911 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14912 return newPkg.packageName; 14913 } 14914 // Check child shared users 14915 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14916 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14917 for (int i = 0; i < newChildCount; i++) { 14918 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14919 // If this child was present, did it have the same shared user? 14920 for (int j = 0; j < oldChildCount; j++) { 14921 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14922 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14923 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14924 return newChildPkg.packageName; 14925 } 14926 } 14927 } 14928 return null; 14929 } 14930 14931 private void removeNativeBinariesLI(PackageSetting ps) { 14932 // Remove the lib path for the parent package 14933 if (ps != null) { 14934 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14935 // Remove the lib path for the child packages 14936 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14937 for (int i = 0; i < childCount; i++) { 14938 PackageSetting childPs = null; 14939 synchronized (mPackages) { 14940 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 14941 } 14942 if (childPs != null) { 14943 NativeLibraryHelper.removeNativeBinariesLI(childPs 14944 .legacyNativeLibraryPathString); 14945 } 14946 } 14947 } 14948 } 14949 14950 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14951 // Enable the parent package 14952 mSettings.enableSystemPackageLPw(pkg.packageName); 14953 // Enable the child packages 14954 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14955 for (int i = 0; i < childCount; i++) { 14956 PackageParser.Package childPkg = pkg.childPackages.get(i); 14957 mSettings.enableSystemPackageLPw(childPkg.packageName); 14958 } 14959 } 14960 14961 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14962 PackageParser.Package newPkg) { 14963 // Disable the parent package (parent always replaced) 14964 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14965 // Disable the child packages 14966 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14967 for (int i = 0; i < childCount; i++) { 14968 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14969 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14970 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14971 } 14972 return disabled; 14973 } 14974 14975 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14976 String installerPackageName) { 14977 // Enable the parent package 14978 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14979 // Enable the child packages 14980 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14981 for (int i = 0; i < childCount; i++) { 14982 PackageParser.Package childPkg = pkg.childPackages.get(i); 14983 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14984 } 14985 } 14986 14987 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14988 // Collect all used permissions in the UID 14989 ArraySet<String> usedPermissions = new ArraySet<>(); 14990 final int packageCount = su.packages.size(); 14991 for (int i = 0; i < packageCount; i++) { 14992 PackageSetting ps = su.packages.valueAt(i); 14993 if (ps.pkg == null) { 14994 continue; 14995 } 14996 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14997 for (int j = 0; j < requestedPermCount; j++) { 14998 String permission = ps.pkg.requestedPermissions.get(j); 14999 BasePermission bp = mSettings.mPermissions.get(permission); 15000 if (bp != null) { 15001 usedPermissions.add(permission); 15002 } 15003 } 15004 } 15005 15006 PermissionsState permissionsState = su.getPermissionsState(); 15007 // Prune install permissions 15008 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 15009 final int installPermCount = installPermStates.size(); 15010 for (int i = installPermCount - 1; i >= 0; i--) { 15011 PermissionState permissionState = installPermStates.get(i); 15012 if (!usedPermissions.contains(permissionState.getName())) { 15013 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15014 if (bp != null) { 15015 permissionsState.revokeInstallPermission(bp); 15016 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 15017 PackageManager.MASK_PERMISSION_FLAGS, 0); 15018 } 15019 } 15020 } 15021 15022 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 15023 15024 // Prune runtime permissions 15025 for (int userId : allUserIds) { 15026 List<PermissionState> runtimePermStates = permissionsState 15027 .getRuntimePermissionStates(userId); 15028 final int runtimePermCount = runtimePermStates.size(); 15029 for (int i = runtimePermCount - 1; i >= 0; i--) { 15030 PermissionState permissionState = runtimePermStates.get(i); 15031 if (!usedPermissions.contains(permissionState.getName())) { 15032 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15033 if (bp != null) { 15034 permissionsState.revokeRuntimePermission(bp, userId); 15035 permissionsState.updatePermissionFlags(bp, userId, 15036 PackageManager.MASK_PERMISSION_FLAGS, 0); 15037 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 15038 runtimePermissionChangedUserIds, userId); 15039 } 15040 } 15041 } 15042 } 15043 15044 return runtimePermissionChangedUserIds; 15045 } 15046 15047 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 15048 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 15049 // Update the parent package setting 15050 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 15051 res, user); 15052 // Update the child packages setting 15053 final int childCount = (newPackage.childPackages != null) 15054 ? newPackage.childPackages.size() : 0; 15055 for (int i = 0; i < childCount; i++) { 15056 PackageParser.Package childPackage = newPackage.childPackages.get(i); 15057 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 15058 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 15059 childRes.origUsers, childRes, user); 15060 } 15061 } 15062 15063 private void updateSettingsInternalLI(PackageParser.Package newPackage, 15064 String installerPackageName, int[] allUsers, int[] installedForUsers, 15065 PackageInstalledInfo res, UserHandle user) { 15066 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 15067 15068 String pkgName = newPackage.packageName; 15069 synchronized (mPackages) { 15070 //write settings. the installStatus will be incomplete at this stage. 15071 //note that the new package setting would have already been 15072 //added to mPackages. It hasn't been persisted yet. 15073 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 15074 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15075 mSettings.writeLPr(); 15076 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15077 } 15078 15079 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 15080 synchronized (mPackages) { 15081 updatePermissionsLPw(newPackage.packageName, newPackage, 15082 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 15083 ? UPDATE_PERMISSIONS_ALL : 0)); 15084 // For system-bundled packages, we assume that installing an upgraded version 15085 // of the package implies that the user actually wants to run that new code, 15086 // so we enable the package. 15087 PackageSetting ps = mSettings.mPackages.get(pkgName); 15088 final int userId = user.getIdentifier(); 15089 if (ps != null) { 15090 if (isSystemApp(newPackage)) { 15091 if (DEBUG_INSTALL) { 15092 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 15093 } 15094 // Enable system package for requested users 15095 if (res.origUsers != null) { 15096 for (int origUserId : res.origUsers) { 15097 if (userId == UserHandle.USER_ALL || userId == origUserId) { 15098 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 15099 origUserId, installerPackageName); 15100 } 15101 } 15102 } 15103 // Also convey the prior install/uninstall state 15104 if (allUsers != null && installedForUsers != null) { 15105 for (int currentUserId : allUsers) { 15106 final boolean installed = ArrayUtils.contains( 15107 installedForUsers, currentUserId); 15108 if (DEBUG_INSTALL) { 15109 Slog.d(TAG, " user " + currentUserId + " => " + installed); 15110 } 15111 ps.setInstalled(installed, currentUserId); 15112 } 15113 // these install state changes will be persisted in the 15114 // upcoming call to mSettings.writeLPr(). 15115 } 15116 } 15117 // It's implied that when a user requests installation, they want the app to be 15118 // installed and enabled. 15119 if (userId != UserHandle.USER_ALL) { 15120 ps.setInstalled(true, userId); 15121 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 15122 } 15123 } 15124 res.name = pkgName; 15125 res.uid = newPackage.applicationInfo.uid; 15126 res.pkg = newPackage; 15127 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 15128 mSettings.setInstallerPackageName(pkgName, installerPackageName); 15129 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15130 //to update install status 15131 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15132 mSettings.writeLPr(); 15133 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15134 } 15135 15136 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15137 } 15138 15139 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 15140 try { 15141 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 15142 installPackageLI(args, res); 15143 } finally { 15144 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15145 } 15146 } 15147 15148 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 15149 final int installFlags = args.installFlags; 15150 final String installerPackageName = args.installerPackageName; 15151 final String volumeUuid = args.volumeUuid; 15152 final File tmpPackageFile = new File(args.getCodePath()); 15153 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 15154 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 15155 || (args.volumeUuid != null)); 15156 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 15157 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 15158 boolean replace = false; 15159 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 15160 if (args.move != null) { 15161 // moving a complete application; perform an initial scan on the new install location 15162 scanFlags |= SCAN_INITIAL; 15163 } 15164 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 15165 scanFlags |= SCAN_DONT_KILL_APP; 15166 } 15167 15168 // Result object to be returned 15169 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15170 15171 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 15172 15173 // Sanity check 15174 if (ephemeral && (forwardLocked || onExternal)) { 15175 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 15176 + " external=" + onExternal); 15177 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15178 return; 15179 } 15180 15181 // Retrieve PackageSettings and parse package 15182 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 15183 | PackageParser.PARSE_ENFORCE_CODE 15184 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 15185 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 15186 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 15187 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 15188 PackageParser pp = new PackageParser(); 15189 pp.setSeparateProcesses(mSeparateProcesses); 15190 pp.setDisplayMetrics(mMetrics); 15191 15192 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 15193 final PackageParser.Package pkg; 15194 try { 15195 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 15196 } catch (PackageParserException e) { 15197 res.setError("Failed parse during installPackageLI", e); 15198 return; 15199 } finally { 15200 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15201 } 15202 15203 // If we are installing a clustered package add results for the children 15204 if (pkg.childPackages != null) { 15205 synchronized (mPackages) { 15206 final int childCount = pkg.childPackages.size(); 15207 for (int i = 0; i < childCount; i++) { 15208 PackageParser.Package childPkg = pkg.childPackages.get(i); 15209 PackageInstalledInfo childRes = new PackageInstalledInfo(); 15210 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15211 childRes.pkg = childPkg; 15212 childRes.name = childPkg.packageName; 15213 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15214 if (childPs != null) { 15215 childRes.origUsers = childPs.queryInstalledUsers( 15216 sUserManager.getUserIds(), true); 15217 } 15218 if ((mPackages.containsKey(childPkg.packageName))) { 15219 childRes.removedInfo = new PackageRemovedInfo(); 15220 childRes.removedInfo.removedPackage = childPkg.packageName; 15221 } 15222 if (res.addedChildPackages == null) { 15223 res.addedChildPackages = new ArrayMap<>(); 15224 } 15225 res.addedChildPackages.put(childPkg.packageName, childRes); 15226 } 15227 } 15228 } 15229 15230 // If package doesn't declare API override, mark that we have an install 15231 // time CPU ABI override. 15232 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15233 pkg.cpuAbiOverride = args.abiOverride; 15234 } 15235 15236 String pkgName = res.name = pkg.packageName; 15237 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15238 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15239 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15240 return; 15241 } 15242 } 15243 15244 try { 15245 // either use what we've been given or parse directly from the APK 15246 if (args.certificates != null) { 15247 try { 15248 PackageParser.populateCertificates(pkg, args.certificates); 15249 } catch (PackageParserException e) { 15250 // there was something wrong with the certificates we were given; 15251 // try to pull them from the APK 15252 PackageParser.collectCertificates(pkg, parseFlags); 15253 } 15254 } else { 15255 PackageParser.collectCertificates(pkg, parseFlags); 15256 } 15257 } catch (PackageParserException e) { 15258 res.setError("Failed collect during installPackageLI", e); 15259 return; 15260 } 15261 15262 // Get rid of all references to package scan path via parser. 15263 pp = null; 15264 String oldCodePath = null; 15265 boolean systemApp = false; 15266 synchronized (mPackages) { 15267 // Check if installing already existing package 15268 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15269 String oldName = mSettings.getRenamedPackageLPr(pkgName); 15270 if (pkg.mOriginalPackages != null 15271 && pkg.mOriginalPackages.contains(oldName) 15272 && mPackages.containsKey(oldName)) { 15273 // This package is derived from an original package, 15274 // and this device has been updating from that original 15275 // name. We must continue using the original name, so 15276 // rename the new package here. 15277 pkg.setPackageName(oldName); 15278 pkgName = pkg.packageName; 15279 replace = true; 15280 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15281 + oldName + " pkgName=" + pkgName); 15282 } else if (mPackages.containsKey(pkgName)) { 15283 // This package, under its official name, already exists 15284 // on the device; we should replace it. 15285 replace = true; 15286 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15287 } 15288 15289 // Child packages are installed through the parent package 15290 if (pkg.parentPackage != null) { 15291 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15292 "Package " + pkg.packageName + " is child of package " 15293 + pkg.parentPackage.parentPackage + ". Child packages " 15294 + "can be updated only through the parent package."); 15295 return; 15296 } 15297 15298 if (replace) { 15299 // Prevent apps opting out from runtime permissions 15300 PackageParser.Package oldPackage = mPackages.get(pkgName); 15301 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15302 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15303 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15304 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15305 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15306 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15307 + " doesn't support runtime permissions but the old" 15308 + " target SDK " + oldTargetSdk + " does."); 15309 return; 15310 } 15311 15312 // Prevent installing of child packages 15313 if (oldPackage.parentPackage != null) { 15314 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15315 "Package " + pkg.packageName + " is child of package " 15316 + oldPackage.parentPackage + ". Child packages " 15317 + "can be updated only through the parent package."); 15318 return; 15319 } 15320 } 15321 } 15322 15323 PackageSetting ps = mSettings.mPackages.get(pkgName); 15324 if (ps != null) { 15325 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15326 15327 // Quick sanity check that we're signed correctly if updating; 15328 // we'll check this again later when scanning, but we want to 15329 // bail early here before tripping over redefined permissions. 15330 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15331 if (!checkUpgradeKeySetLP(ps, pkg)) { 15332 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15333 + pkg.packageName + " upgrade keys do not match the " 15334 + "previously installed version"); 15335 return; 15336 } 15337 } else { 15338 try { 15339 verifySignaturesLP(ps, pkg); 15340 } catch (PackageManagerException e) { 15341 res.setError(e.error, e.getMessage()); 15342 return; 15343 } 15344 } 15345 15346 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15347 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15348 systemApp = (ps.pkg.applicationInfo.flags & 15349 ApplicationInfo.FLAG_SYSTEM) != 0; 15350 } 15351 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15352 } 15353 15354 // Check whether the newly-scanned package wants to define an already-defined perm 15355 int N = pkg.permissions.size(); 15356 for (int i = N-1; i >= 0; i--) { 15357 PackageParser.Permission perm = pkg.permissions.get(i); 15358 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15359 if (bp != null) { 15360 // If the defining package is signed with our cert, it's okay. This 15361 // also includes the "updating the same package" case, of course. 15362 // "updating same package" could also involve key-rotation. 15363 final boolean sigsOk; 15364 if (bp.sourcePackage.equals(pkg.packageName) 15365 && (bp.packageSetting instanceof PackageSetting) 15366 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15367 scanFlags))) { 15368 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15369 } else { 15370 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15371 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15372 } 15373 if (!sigsOk) { 15374 // If the owning package is the system itself, we log but allow 15375 // install to proceed; we fail the install on all other permission 15376 // redefinitions. 15377 if (!bp.sourcePackage.equals("android")) { 15378 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15379 + pkg.packageName + " attempting to redeclare permission " 15380 + perm.info.name + " already owned by " + bp.sourcePackage); 15381 res.origPermission = perm.info.name; 15382 res.origPackage = bp.sourcePackage; 15383 return; 15384 } else { 15385 Slog.w(TAG, "Package " + pkg.packageName 15386 + " attempting to redeclare system permission " 15387 + perm.info.name + "; ignoring new declaration"); 15388 pkg.permissions.remove(i); 15389 } 15390 } 15391 } 15392 } 15393 } 15394 15395 if (systemApp) { 15396 if (onExternal) { 15397 // Abort update; system app can't be replaced with app on sdcard 15398 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15399 "Cannot install updates to system apps on sdcard"); 15400 return; 15401 } else if (ephemeral) { 15402 // Abort update; system app can't be replaced with an ephemeral app 15403 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15404 "Cannot update a system app with an ephemeral app"); 15405 return; 15406 } 15407 } 15408 15409 if (args.move != null) { 15410 // We did an in-place move, so dex is ready to roll 15411 scanFlags |= SCAN_NO_DEX; 15412 scanFlags |= SCAN_MOVE; 15413 15414 synchronized (mPackages) { 15415 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15416 if (ps == null) { 15417 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15418 "Missing settings for moved package " + pkgName); 15419 } 15420 15421 // We moved the entire application as-is, so bring over the 15422 // previously derived ABI information. 15423 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15424 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15425 } 15426 15427 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15428 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15429 scanFlags |= SCAN_NO_DEX; 15430 15431 try { 15432 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15433 args.abiOverride : pkg.cpuAbiOverride); 15434 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15435 true /*extractLibs*/, mAppLib32InstallDir); 15436 } catch (PackageManagerException pme) { 15437 Slog.e(TAG, "Error deriving application ABI", pme); 15438 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15439 return; 15440 } 15441 15442 // Shared libraries for the package need to be updated. 15443 synchronized (mPackages) { 15444 try { 15445 updateSharedLibrariesLPr(pkg, null); 15446 } catch (PackageManagerException e) { 15447 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15448 } 15449 } 15450 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15451 // Do not run PackageDexOptimizer through the local performDexOpt 15452 // method because `pkg` may not be in `mPackages` yet. 15453 // 15454 // Also, don't fail application installs if the dexopt step fails. 15455 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15456 null /* instructionSets */, false /* checkProfiles */, 15457 getCompilerFilterForReason(REASON_INSTALL), 15458 getOrCreateCompilerPackageStats(pkg)); 15459 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15460 15461 // Notify BackgroundDexOptService that the package has been changed. 15462 // If this is an update of a package which used to fail to compile, 15463 // BDOS will remove it from its blacklist. 15464 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15465 } 15466 15467 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15468 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15469 return; 15470 } 15471 15472 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15473 15474 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15475 "installPackageLI")) { 15476 if (replace) { 15477 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15478 installerPackageName, res); 15479 } else { 15480 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15481 args.user, installerPackageName, volumeUuid, res); 15482 } 15483 } 15484 synchronized (mPackages) { 15485 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15486 if (ps != null) { 15487 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15488 } 15489 15490 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15491 for (int i = 0; i < childCount; i++) { 15492 PackageParser.Package childPkg = pkg.childPackages.get(i); 15493 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15494 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15495 if (childPs != null) { 15496 childRes.newUsers = childPs.queryInstalledUsers( 15497 sUserManager.getUserIds(), true); 15498 } 15499 } 15500 } 15501 } 15502 15503 private void startIntentFilterVerifications(int userId, boolean replacing, 15504 PackageParser.Package pkg) { 15505 if (mIntentFilterVerifierComponent == null) { 15506 Slog.w(TAG, "No IntentFilter verification will not be done as " 15507 + "there is no IntentFilterVerifier available!"); 15508 return; 15509 } 15510 15511 final int verifierUid = getPackageUid( 15512 mIntentFilterVerifierComponent.getPackageName(), 15513 MATCH_DEBUG_TRIAGED_MISSING, 15514 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15515 15516 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15517 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15518 mHandler.sendMessage(msg); 15519 15520 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15521 for (int i = 0; i < childCount; i++) { 15522 PackageParser.Package childPkg = pkg.childPackages.get(i); 15523 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15524 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15525 mHandler.sendMessage(msg); 15526 } 15527 } 15528 15529 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15530 PackageParser.Package pkg) { 15531 int size = pkg.activities.size(); 15532 if (size == 0) { 15533 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15534 "No activity, so no need to verify any IntentFilter!"); 15535 return; 15536 } 15537 15538 final boolean hasDomainURLs = hasDomainURLs(pkg); 15539 if (!hasDomainURLs) { 15540 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15541 "No domain URLs, so no need to verify any IntentFilter!"); 15542 return; 15543 } 15544 15545 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15546 + " if any IntentFilter from the " + size 15547 + " Activities needs verification ..."); 15548 15549 int count = 0; 15550 final String packageName = pkg.packageName; 15551 15552 synchronized (mPackages) { 15553 // If this is a new install and we see that we've already run verification for this 15554 // package, we have nothing to do: it means the state was restored from backup. 15555 if (!replacing) { 15556 IntentFilterVerificationInfo ivi = 15557 mSettings.getIntentFilterVerificationLPr(packageName); 15558 if (ivi != null) { 15559 if (DEBUG_DOMAIN_VERIFICATION) { 15560 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15561 + ivi.getStatusString()); 15562 } 15563 return; 15564 } 15565 } 15566 15567 // If any filters need to be verified, then all need to be. 15568 boolean needToVerify = false; 15569 for (PackageParser.Activity a : pkg.activities) { 15570 for (ActivityIntentInfo filter : a.intents) { 15571 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15572 if (DEBUG_DOMAIN_VERIFICATION) { 15573 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15574 } 15575 needToVerify = true; 15576 break; 15577 } 15578 } 15579 } 15580 15581 if (needToVerify) { 15582 final int verificationId = mIntentFilterVerificationToken++; 15583 for (PackageParser.Activity a : pkg.activities) { 15584 for (ActivityIntentInfo filter : a.intents) { 15585 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15586 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15587 "Verification needed for IntentFilter:" + filter.toString()); 15588 mIntentFilterVerifier.addOneIntentFilterVerification( 15589 verifierUid, userId, verificationId, filter, packageName); 15590 count++; 15591 } 15592 } 15593 } 15594 } 15595 } 15596 15597 if (count > 0) { 15598 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15599 + " IntentFilter verification" + (count > 1 ? "s" : "") 15600 + " for userId:" + userId); 15601 mIntentFilterVerifier.startVerifications(userId); 15602 } else { 15603 if (DEBUG_DOMAIN_VERIFICATION) { 15604 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15605 } 15606 } 15607 } 15608 15609 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15610 final ComponentName cn = filter.activity.getComponentName(); 15611 final String packageName = cn.getPackageName(); 15612 15613 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15614 packageName); 15615 if (ivi == null) { 15616 return true; 15617 } 15618 int status = ivi.getStatus(); 15619 switch (status) { 15620 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15621 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15622 return true; 15623 15624 default: 15625 // Nothing to do 15626 return false; 15627 } 15628 } 15629 15630 private static boolean isMultiArch(ApplicationInfo info) { 15631 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15632 } 15633 15634 private static boolean isExternal(PackageParser.Package pkg) { 15635 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15636 } 15637 15638 private static boolean isExternal(PackageSetting ps) { 15639 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15640 } 15641 15642 private static boolean isEphemeral(PackageParser.Package pkg) { 15643 return pkg.applicationInfo.isEphemeralApp(); 15644 } 15645 15646 private static boolean isEphemeral(PackageSetting ps) { 15647 return ps.pkg != null && isEphemeral(ps.pkg); 15648 } 15649 15650 private static boolean isSystemApp(PackageParser.Package pkg) { 15651 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15652 } 15653 15654 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15655 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15656 } 15657 15658 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15659 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15660 } 15661 15662 private static boolean isSystemApp(PackageSetting ps) { 15663 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15664 } 15665 15666 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15667 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15668 } 15669 15670 private int packageFlagsToInstallFlags(PackageSetting ps) { 15671 int installFlags = 0; 15672 if (isEphemeral(ps)) { 15673 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15674 } 15675 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15676 // This existing package was an external ASEC install when we have 15677 // the external flag without a UUID 15678 installFlags |= PackageManager.INSTALL_EXTERNAL; 15679 } 15680 if (ps.isForwardLocked()) { 15681 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15682 } 15683 return installFlags; 15684 } 15685 15686 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15687 if (isExternal(pkg)) { 15688 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15689 return StorageManager.UUID_PRIMARY_PHYSICAL; 15690 } else { 15691 return pkg.volumeUuid; 15692 } 15693 } else { 15694 return StorageManager.UUID_PRIVATE_INTERNAL; 15695 } 15696 } 15697 15698 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15699 if (isExternal(pkg)) { 15700 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15701 return mSettings.getExternalVersion(); 15702 } else { 15703 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15704 } 15705 } else { 15706 return mSettings.getInternalVersion(); 15707 } 15708 } 15709 15710 private void deleteTempPackageFiles() { 15711 final FilenameFilter filter = new FilenameFilter() { 15712 public boolean accept(File dir, String name) { 15713 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15714 } 15715 }; 15716 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15717 file.delete(); 15718 } 15719 } 15720 15721 @Override 15722 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15723 int flags) { 15724 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15725 flags); 15726 } 15727 15728 @Override 15729 public void deletePackage(final String packageName, 15730 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15731 mContext.enforceCallingOrSelfPermission( 15732 android.Manifest.permission.DELETE_PACKAGES, null); 15733 Preconditions.checkNotNull(packageName); 15734 Preconditions.checkNotNull(observer); 15735 final int uid = Binder.getCallingUid(); 15736 if (!isOrphaned(packageName) 15737 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 15738 try { 15739 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 15740 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 15741 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 15742 observer.onUserActionRequired(intent); 15743 } catch (RemoteException re) { 15744 } 15745 return; 15746 } 15747 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15748 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15749 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15750 mContext.enforceCallingOrSelfPermission( 15751 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15752 "deletePackage for user " + userId); 15753 } 15754 15755 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15756 try { 15757 observer.onPackageDeleted(packageName, 15758 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15759 } catch (RemoteException re) { 15760 } 15761 return; 15762 } 15763 15764 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15765 try { 15766 observer.onPackageDeleted(packageName, 15767 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15768 } catch (RemoteException re) { 15769 } 15770 return; 15771 } 15772 15773 if (DEBUG_REMOVE) { 15774 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15775 + " deleteAllUsers: " + deleteAllUsers ); 15776 } 15777 // Queue up an async operation since the package deletion may take a little while. 15778 mHandler.post(new Runnable() { 15779 public void run() { 15780 mHandler.removeCallbacks(this); 15781 int returnCode; 15782 if (!deleteAllUsers) { 15783 returnCode = deletePackageX(packageName, userId, deleteFlags); 15784 } else { 15785 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15786 // If nobody is blocking uninstall, proceed with delete for all users 15787 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15788 returnCode = deletePackageX(packageName, userId, deleteFlags); 15789 } else { 15790 // Otherwise uninstall individually for users with blockUninstalls=false 15791 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15792 for (int userId : users) { 15793 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15794 returnCode = deletePackageX(packageName, userId, userFlags); 15795 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15796 Slog.w(TAG, "Package delete failed for user " + userId 15797 + ", returnCode " + returnCode); 15798 } 15799 } 15800 } 15801 // The app has only been marked uninstalled for certain users. 15802 // We still need to report that delete was blocked 15803 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15804 } 15805 } 15806 try { 15807 observer.onPackageDeleted(packageName, returnCode, null); 15808 } catch (RemoteException e) { 15809 Log.i(TAG, "Observer no longer exists."); 15810 } //end catch 15811 } //end run 15812 }); 15813 } 15814 15815 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 15816 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 15817 || callingUid == Process.SYSTEM_UID) { 15818 return true; 15819 } 15820 final int callingUserId = UserHandle.getUserId(callingUid); 15821 // If the caller installed the pkgName, then allow it to silently uninstall. 15822 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 15823 return true; 15824 } 15825 15826 // Allow package verifier to silently uninstall. 15827 if (mRequiredVerifierPackage != null && 15828 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 15829 return true; 15830 } 15831 15832 // Allow package uninstaller to silently uninstall. 15833 if (mRequiredUninstallerPackage != null && 15834 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 15835 return true; 15836 } 15837 15838 // Allow storage manager to silently uninstall. 15839 if (mStorageManagerPackage != null && 15840 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 15841 return true; 15842 } 15843 return false; 15844 } 15845 15846 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15847 int[] result = EMPTY_INT_ARRAY; 15848 for (int userId : userIds) { 15849 if (getBlockUninstallForUser(packageName, userId)) { 15850 result = ArrayUtils.appendInt(result, userId); 15851 } 15852 } 15853 return result; 15854 } 15855 15856 @Override 15857 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15858 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15859 } 15860 15861 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15862 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15863 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15864 try { 15865 if (dpm != null) { 15866 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15867 /* callingUserOnly =*/ false); 15868 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15869 : deviceOwnerComponentName.getPackageName(); 15870 // Does the package contains the device owner? 15871 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15872 // this check is probably not needed, since DO should be registered as a device 15873 // admin on some user too. (Original bug for this: b/17657954) 15874 if (packageName.equals(deviceOwnerPackageName)) { 15875 return true; 15876 } 15877 // Does it contain a device admin for any user? 15878 int[] users; 15879 if (userId == UserHandle.USER_ALL) { 15880 users = sUserManager.getUserIds(); 15881 } else { 15882 users = new int[]{userId}; 15883 } 15884 for (int i = 0; i < users.length; ++i) { 15885 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15886 return true; 15887 } 15888 } 15889 } 15890 } catch (RemoteException e) { 15891 } 15892 return false; 15893 } 15894 15895 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15896 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15897 } 15898 15899 /** 15900 * This method is an internal method that could be get invoked either 15901 * to delete an installed package or to clean up a failed installation. 15902 * After deleting an installed package, a broadcast is sent to notify any 15903 * listeners that the package has been removed. For cleaning up a failed 15904 * installation, the broadcast is not necessary since the package's 15905 * installation wouldn't have sent the initial broadcast either 15906 * The key steps in deleting a package are 15907 * deleting the package information in internal structures like mPackages, 15908 * deleting the packages base directories through installd 15909 * updating mSettings to reflect current status 15910 * persisting settings for later use 15911 * sending a broadcast if necessary 15912 */ 15913 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15914 final PackageRemovedInfo info = new PackageRemovedInfo(); 15915 final boolean res; 15916 15917 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15918 ? UserHandle.USER_ALL : userId; 15919 15920 if (isPackageDeviceAdmin(packageName, removeUser)) { 15921 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15922 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15923 } 15924 15925 PackageSetting uninstalledPs = null; 15926 15927 // for the uninstall-updates case and restricted profiles, remember the per- 15928 // user handle installed state 15929 int[] allUsers; 15930 synchronized (mPackages) { 15931 uninstalledPs = mSettings.mPackages.get(packageName); 15932 if (uninstalledPs == null) { 15933 Slog.w(TAG, "Not removing non-existent package " + packageName); 15934 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15935 } 15936 allUsers = sUserManager.getUserIds(); 15937 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15938 } 15939 15940 final int freezeUser; 15941 if (isUpdatedSystemApp(uninstalledPs) 15942 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15943 // We're downgrading a system app, which will apply to all users, so 15944 // freeze them all during the downgrade 15945 freezeUser = UserHandle.USER_ALL; 15946 } else { 15947 freezeUser = removeUser; 15948 } 15949 15950 synchronized (mInstallLock) { 15951 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15952 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15953 deleteFlags, "deletePackageX")) { 15954 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15955 deleteFlags | REMOVE_CHATTY, info, true, null); 15956 } 15957 synchronized (mPackages) { 15958 if (res) { 15959 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15960 } 15961 } 15962 } 15963 15964 if (res) { 15965 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15966 info.sendPackageRemovedBroadcasts(killApp); 15967 info.sendSystemPackageUpdatedBroadcasts(); 15968 info.sendSystemPackageAppearedBroadcasts(); 15969 } 15970 // Force a gc here. 15971 Runtime.getRuntime().gc(); 15972 // Delete the resources here after sending the broadcast to let 15973 // other processes clean up before deleting resources. 15974 if (info.args != null) { 15975 synchronized (mInstallLock) { 15976 info.args.doPostDeleteLI(true); 15977 } 15978 } 15979 15980 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15981 } 15982 15983 class PackageRemovedInfo { 15984 String removedPackage; 15985 int uid = -1; 15986 int removedAppId = -1; 15987 int[] origUsers; 15988 int[] removedUsers = null; 15989 boolean isRemovedPackageSystemUpdate = false; 15990 boolean isUpdate; 15991 boolean dataRemoved; 15992 boolean removedForAllUsers; 15993 // Clean up resources deleted packages. 15994 InstallArgs args = null; 15995 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15996 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15997 15998 void sendPackageRemovedBroadcasts(boolean killApp) { 15999 sendPackageRemovedBroadcastInternal(killApp); 16000 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 16001 for (int i = 0; i < childCount; i++) { 16002 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 16003 childInfo.sendPackageRemovedBroadcastInternal(killApp); 16004 } 16005 } 16006 16007 void sendSystemPackageUpdatedBroadcasts() { 16008 if (isRemovedPackageSystemUpdate) { 16009 sendSystemPackageUpdatedBroadcastsInternal(); 16010 final int childCount = (removedChildPackages != null) 16011 ? removedChildPackages.size() : 0; 16012 for (int i = 0; i < childCount; i++) { 16013 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 16014 if (childInfo.isRemovedPackageSystemUpdate) { 16015 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 16016 } 16017 } 16018 } 16019 } 16020 16021 void sendSystemPackageAppearedBroadcasts() { 16022 final int packageCount = (appearedChildPackages != null) 16023 ? appearedChildPackages.size() : 0; 16024 for (int i = 0; i < packageCount; i++) { 16025 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 16026 sendPackageAddedForNewUsers(installedInfo.name, true, 16027 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 16028 } 16029 } 16030 16031 private void sendSystemPackageUpdatedBroadcastsInternal() { 16032 Bundle extras = new Bundle(2); 16033 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16034 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16035 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 16036 extras, 0, null, null, null); 16037 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 16038 extras, 0, null, null, null); 16039 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 16040 null, 0, removedPackage, null, null); 16041 } 16042 16043 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 16044 Bundle extras = new Bundle(2); 16045 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16046 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 16047 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 16048 if (isUpdate || isRemovedPackageSystemUpdate) { 16049 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16050 } 16051 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 16052 if (removedPackage != null) { 16053 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 16054 extras, 0, null, null, removedUsers); 16055 if (dataRemoved && !isRemovedPackageSystemUpdate) { 16056 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 16057 removedPackage, extras, 0, null, null, removedUsers); 16058 } 16059 } 16060 if (removedAppId >= 0) { 16061 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 16062 removedUsers); 16063 } 16064 } 16065 } 16066 16067 /* 16068 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 16069 * flag is not set, the data directory is removed as well. 16070 * make sure this flag is set for partially installed apps. If not its meaningless to 16071 * delete a partially installed application. 16072 */ 16073 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 16074 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 16075 String packageName = ps.name; 16076 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 16077 // Retrieve object to delete permissions for shared user later on 16078 final PackageParser.Package deletedPkg; 16079 final PackageSetting deletedPs; 16080 // reader 16081 synchronized (mPackages) { 16082 deletedPkg = mPackages.get(packageName); 16083 deletedPs = mSettings.mPackages.get(packageName); 16084 if (outInfo != null) { 16085 outInfo.removedPackage = packageName; 16086 outInfo.removedUsers = deletedPs != null 16087 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 16088 : null; 16089 } 16090 } 16091 16092 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 16093 16094 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 16095 final PackageParser.Package resolvedPkg; 16096 if (deletedPkg != null) { 16097 resolvedPkg = deletedPkg; 16098 } else { 16099 // We don't have a parsed package when it lives on an ejected 16100 // adopted storage device, so fake something together 16101 resolvedPkg = new PackageParser.Package(ps.name); 16102 resolvedPkg.setVolumeUuid(ps.volumeUuid); 16103 } 16104 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 16105 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16106 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 16107 if (outInfo != null) { 16108 outInfo.dataRemoved = true; 16109 } 16110 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 16111 } 16112 16113 // writer 16114 synchronized (mPackages) { 16115 if (deletedPs != null) { 16116 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 16117 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 16118 clearDefaultBrowserIfNeeded(packageName); 16119 if (outInfo != null) { 16120 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 16121 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 16122 } 16123 updatePermissionsLPw(deletedPs.name, null, 0); 16124 if (deletedPs.sharedUser != null) { 16125 // Remove permissions associated with package. Since runtime 16126 // permissions are per user we have to kill the removed package 16127 // or packages running under the shared user of the removed 16128 // package if revoking the permissions requested only by the removed 16129 // package is successful and this causes a change in gids. 16130 for (int userId : UserManagerService.getInstance().getUserIds()) { 16131 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 16132 userId); 16133 if (userIdToKill == UserHandle.USER_ALL 16134 || userIdToKill >= UserHandle.USER_SYSTEM) { 16135 // If gids changed for this user, kill all affected packages. 16136 mHandler.post(new Runnable() { 16137 @Override 16138 public void run() { 16139 // This has to happen with no lock held. 16140 killApplication(deletedPs.name, deletedPs.appId, 16141 KILL_APP_REASON_GIDS_CHANGED); 16142 } 16143 }); 16144 break; 16145 } 16146 } 16147 } 16148 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 16149 } 16150 // make sure to preserve per-user disabled state if this removal was just 16151 // a downgrade of a system app to the factory package 16152 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 16153 if (DEBUG_REMOVE) { 16154 Slog.d(TAG, "Propagating install state across downgrade"); 16155 } 16156 for (int userId : allUserHandles) { 16157 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16158 if (DEBUG_REMOVE) { 16159 Slog.d(TAG, " user " + userId + " => " + installed); 16160 } 16161 ps.setInstalled(installed, userId); 16162 } 16163 } 16164 } 16165 // can downgrade to reader 16166 if (writeSettings) { 16167 // Save settings now 16168 mSettings.writeLPr(); 16169 } 16170 } 16171 if (outInfo != null) { 16172 // A user ID was deleted here. Go through all users and remove it 16173 // from KeyStore. 16174 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 16175 } 16176 } 16177 16178 static boolean locationIsPrivileged(File path) { 16179 try { 16180 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 16181 .getCanonicalPath(); 16182 return path.getCanonicalPath().startsWith(privilegedAppDir); 16183 } catch (IOException e) { 16184 Slog.e(TAG, "Unable to access code path " + path); 16185 } 16186 return false; 16187 } 16188 16189 /* 16190 * Tries to delete system package. 16191 */ 16192 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 16193 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 16194 boolean writeSettings) { 16195 if (deletedPs.parentPackageName != null) { 16196 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 16197 return false; 16198 } 16199 16200 final boolean applyUserRestrictions 16201 = (allUserHandles != null) && (outInfo.origUsers != null); 16202 final PackageSetting disabledPs; 16203 // Confirm if the system package has been updated 16204 // An updated system app can be deleted. This will also have to restore 16205 // the system pkg from system partition 16206 // reader 16207 synchronized (mPackages) { 16208 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 16209 } 16210 16211 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 16212 + " disabledPs=" + disabledPs); 16213 16214 if (disabledPs == null) { 16215 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 16216 return false; 16217 } else if (DEBUG_REMOVE) { 16218 Slog.d(TAG, "Deleting system pkg from data partition"); 16219 } 16220 16221 if (DEBUG_REMOVE) { 16222 if (applyUserRestrictions) { 16223 Slog.d(TAG, "Remembering install states:"); 16224 for (int userId : allUserHandles) { 16225 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 16226 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 16227 } 16228 } 16229 } 16230 16231 // Delete the updated package 16232 outInfo.isRemovedPackageSystemUpdate = true; 16233 if (outInfo.removedChildPackages != null) { 16234 final int childCount = (deletedPs.childPackageNames != null) 16235 ? deletedPs.childPackageNames.size() : 0; 16236 for (int i = 0; i < childCount; i++) { 16237 String childPackageName = deletedPs.childPackageNames.get(i); 16238 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16239 .contains(childPackageName)) { 16240 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16241 childPackageName); 16242 if (childInfo != null) { 16243 childInfo.isRemovedPackageSystemUpdate = true; 16244 } 16245 } 16246 } 16247 } 16248 16249 if (disabledPs.versionCode < deletedPs.versionCode) { 16250 // Delete data for downgrades 16251 flags &= ~PackageManager.DELETE_KEEP_DATA; 16252 } else { 16253 // Preserve data by setting flag 16254 flags |= PackageManager.DELETE_KEEP_DATA; 16255 } 16256 16257 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16258 outInfo, writeSettings, disabledPs.pkg); 16259 if (!ret) { 16260 return false; 16261 } 16262 16263 // writer 16264 synchronized (mPackages) { 16265 // Reinstate the old system package 16266 enableSystemPackageLPw(disabledPs.pkg); 16267 // Remove any native libraries from the upgraded package. 16268 removeNativeBinariesLI(deletedPs); 16269 } 16270 16271 // Install the system package 16272 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16273 int parseFlags = mDefParseFlags 16274 | PackageParser.PARSE_MUST_BE_APK 16275 | PackageParser.PARSE_IS_SYSTEM 16276 | PackageParser.PARSE_IS_SYSTEM_DIR; 16277 if (locationIsPrivileged(disabledPs.codePath)) { 16278 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16279 } 16280 16281 final PackageParser.Package newPkg; 16282 try { 16283 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 16284 0 /* currentTime */, null); 16285 } catch (PackageManagerException e) { 16286 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16287 + e.getMessage()); 16288 return false; 16289 } 16290 try { 16291 // update shared libraries for the newly re-installed system package 16292 updateSharedLibrariesLPr(newPkg, null); 16293 } catch (PackageManagerException e) { 16294 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16295 } 16296 16297 prepareAppDataAfterInstallLIF(newPkg); 16298 16299 // writer 16300 synchronized (mPackages) { 16301 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16302 16303 // Propagate the permissions state as we do not want to drop on the floor 16304 // runtime permissions. The update permissions method below will take 16305 // care of removing obsolete permissions and grant install permissions. 16306 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16307 updatePermissionsLPw(newPkg.packageName, newPkg, 16308 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16309 16310 if (applyUserRestrictions) { 16311 if (DEBUG_REMOVE) { 16312 Slog.d(TAG, "Propagating install state across reinstall"); 16313 } 16314 for (int userId : allUserHandles) { 16315 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16316 if (DEBUG_REMOVE) { 16317 Slog.d(TAG, " user " + userId + " => " + installed); 16318 } 16319 ps.setInstalled(installed, userId); 16320 16321 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16322 } 16323 // Regardless of writeSettings we need to ensure that this restriction 16324 // state propagation is persisted 16325 mSettings.writeAllUsersPackageRestrictionsLPr(); 16326 } 16327 // can downgrade to reader here 16328 if (writeSettings) { 16329 mSettings.writeLPr(); 16330 } 16331 } 16332 return true; 16333 } 16334 16335 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16336 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16337 PackageRemovedInfo outInfo, boolean writeSettings, 16338 PackageParser.Package replacingPackage) { 16339 synchronized (mPackages) { 16340 if (outInfo != null) { 16341 outInfo.uid = ps.appId; 16342 } 16343 16344 if (outInfo != null && outInfo.removedChildPackages != null) { 16345 final int childCount = (ps.childPackageNames != null) 16346 ? ps.childPackageNames.size() : 0; 16347 for (int i = 0; i < childCount; i++) { 16348 String childPackageName = ps.childPackageNames.get(i); 16349 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16350 if (childPs == null) { 16351 return false; 16352 } 16353 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16354 childPackageName); 16355 if (childInfo != null) { 16356 childInfo.uid = childPs.appId; 16357 } 16358 } 16359 } 16360 } 16361 16362 // Delete package data from internal structures and also remove data if flag is set 16363 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16364 16365 // Delete the child packages data 16366 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16367 for (int i = 0; i < childCount; i++) { 16368 PackageSetting childPs; 16369 synchronized (mPackages) { 16370 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16371 } 16372 if (childPs != null) { 16373 PackageRemovedInfo childOutInfo = (outInfo != null 16374 && outInfo.removedChildPackages != null) 16375 ? outInfo.removedChildPackages.get(childPs.name) : null; 16376 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16377 && (replacingPackage != null 16378 && !replacingPackage.hasChildPackage(childPs.name)) 16379 ? flags & ~DELETE_KEEP_DATA : flags; 16380 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16381 deleteFlags, writeSettings); 16382 } 16383 } 16384 16385 // Delete application code and resources only for parent packages 16386 if (ps.parentPackageName == null) { 16387 if (deleteCodeAndResources && (outInfo != null)) { 16388 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16389 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16390 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16391 } 16392 } 16393 16394 return true; 16395 } 16396 16397 @Override 16398 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16399 int userId) { 16400 mContext.enforceCallingOrSelfPermission( 16401 android.Manifest.permission.DELETE_PACKAGES, null); 16402 synchronized (mPackages) { 16403 PackageSetting ps = mSettings.mPackages.get(packageName); 16404 if (ps == null) { 16405 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16406 return false; 16407 } 16408 if (!ps.getInstalled(userId)) { 16409 // Can't block uninstall for an app that is not installed or enabled. 16410 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16411 return false; 16412 } 16413 ps.setBlockUninstall(blockUninstall, userId); 16414 mSettings.writePackageRestrictionsLPr(userId); 16415 } 16416 return true; 16417 } 16418 16419 @Override 16420 public boolean getBlockUninstallForUser(String packageName, int userId) { 16421 synchronized (mPackages) { 16422 PackageSetting ps = mSettings.mPackages.get(packageName); 16423 if (ps == null) { 16424 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16425 return false; 16426 } 16427 return ps.getBlockUninstall(userId); 16428 } 16429 } 16430 16431 @Override 16432 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16433 int callingUid = Binder.getCallingUid(); 16434 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16435 throw new SecurityException( 16436 "setRequiredForSystemUser can only be run by the system or root"); 16437 } 16438 synchronized (mPackages) { 16439 PackageSetting ps = mSettings.mPackages.get(packageName); 16440 if (ps == null) { 16441 Log.w(TAG, "Package doesn't exist: " + packageName); 16442 return false; 16443 } 16444 if (systemUserApp) { 16445 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16446 } else { 16447 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16448 } 16449 mSettings.writeLPr(); 16450 } 16451 return true; 16452 } 16453 16454 /* 16455 * This method handles package deletion in general 16456 */ 16457 private boolean deletePackageLIF(String packageName, UserHandle user, 16458 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16459 PackageRemovedInfo outInfo, boolean writeSettings, 16460 PackageParser.Package replacingPackage) { 16461 if (packageName == null) { 16462 Slog.w(TAG, "Attempt to delete null packageName."); 16463 return false; 16464 } 16465 16466 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16467 16468 PackageSetting ps; 16469 16470 synchronized (mPackages) { 16471 ps = mSettings.mPackages.get(packageName); 16472 if (ps == null) { 16473 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16474 return false; 16475 } 16476 16477 if (ps.parentPackageName != null && (!isSystemApp(ps) 16478 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16479 if (DEBUG_REMOVE) { 16480 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16481 + ((user == null) ? UserHandle.USER_ALL : user)); 16482 } 16483 final int removedUserId = (user != null) ? user.getIdentifier() 16484 : UserHandle.USER_ALL; 16485 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16486 return false; 16487 } 16488 markPackageUninstalledForUserLPw(ps, user); 16489 scheduleWritePackageRestrictionsLocked(user); 16490 return true; 16491 } 16492 } 16493 16494 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16495 && user.getIdentifier() != UserHandle.USER_ALL)) { 16496 // The caller is asking that the package only be deleted for a single 16497 // user. To do this, we just mark its uninstalled state and delete 16498 // its data. If this is a system app, we only allow this to happen if 16499 // they have set the special DELETE_SYSTEM_APP which requests different 16500 // semantics than normal for uninstalling system apps. 16501 markPackageUninstalledForUserLPw(ps, user); 16502 16503 if (!isSystemApp(ps)) { 16504 // Do not uninstall the APK if an app should be cached 16505 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16506 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16507 // Other user still have this package installed, so all 16508 // we need to do is clear this user's data and save that 16509 // it is uninstalled. 16510 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16511 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16512 return false; 16513 } 16514 scheduleWritePackageRestrictionsLocked(user); 16515 return true; 16516 } else { 16517 // We need to set it back to 'installed' so the uninstall 16518 // broadcasts will be sent correctly. 16519 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16520 ps.setInstalled(true, user.getIdentifier()); 16521 } 16522 } else { 16523 // This is a system app, so we assume that the 16524 // other users still have this package installed, so all 16525 // we need to do is clear this user's data and save that 16526 // it is uninstalled. 16527 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16528 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16529 return false; 16530 } 16531 scheduleWritePackageRestrictionsLocked(user); 16532 return true; 16533 } 16534 } 16535 16536 // If we are deleting a composite package for all users, keep track 16537 // of result for each child. 16538 if (ps.childPackageNames != null && outInfo != null) { 16539 synchronized (mPackages) { 16540 final int childCount = ps.childPackageNames.size(); 16541 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16542 for (int i = 0; i < childCount; i++) { 16543 String childPackageName = ps.childPackageNames.get(i); 16544 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16545 childInfo.removedPackage = childPackageName; 16546 outInfo.removedChildPackages.put(childPackageName, childInfo); 16547 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16548 if (childPs != null) { 16549 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16550 } 16551 } 16552 } 16553 } 16554 16555 boolean ret = false; 16556 if (isSystemApp(ps)) { 16557 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16558 // When an updated system application is deleted we delete the existing resources 16559 // as well and fall back to existing code in system partition 16560 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16561 } else { 16562 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16563 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16564 outInfo, writeSettings, replacingPackage); 16565 } 16566 16567 // Take a note whether we deleted the package for all users 16568 if (outInfo != null) { 16569 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16570 if (outInfo.removedChildPackages != null) { 16571 synchronized (mPackages) { 16572 final int childCount = outInfo.removedChildPackages.size(); 16573 for (int i = 0; i < childCount; i++) { 16574 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16575 if (childInfo != null) { 16576 childInfo.removedForAllUsers = mPackages.get( 16577 childInfo.removedPackage) == null; 16578 } 16579 } 16580 } 16581 } 16582 // If we uninstalled an update to a system app there may be some 16583 // child packages that appeared as they are declared in the system 16584 // app but were not declared in the update. 16585 if (isSystemApp(ps)) { 16586 synchronized (mPackages) { 16587 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 16588 final int childCount = (updatedPs.childPackageNames != null) 16589 ? updatedPs.childPackageNames.size() : 0; 16590 for (int i = 0; i < childCount; i++) { 16591 String childPackageName = updatedPs.childPackageNames.get(i); 16592 if (outInfo.removedChildPackages == null 16593 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16594 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16595 if (childPs == null) { 16596 continue; 16597 } 16598 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16599 installRes.name = childPackageName; 16600 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16601 installRes.pkg = mPackages.get(childPackageName); 16602 installRes.uid = childPs.pkg.applicationInfo.uid; 16603 if (outInfo.appearedChildPackages == null) { 16604 outInfo.appearedChildPackages = new ArrayMap<>(); 16605 } 16606 outInfo.appearedChildPackages.put(childPackageName, installRes); 16607 } 16608 } 16609 } 16610 } 16611 } 16612 16613 return ret; 16614 } 16615 16616 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16617 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16618 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16619 for (int nextUserId : userIds) { 16620 if (DEBUG_REMOVE) { 16621 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16622 } 16623 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16624 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16625 false /*hidden*/, false /*suspended*/, null, null, null, 16626 false /*blockUninstall*/, 16627 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16628 } 16629 } 16630 16631 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16632 PackageRemovedInfo outInfo) { 16633 final PackageParser.Package pkg; 16634 synchronized (mPackages) { 16635 pkg = mPackages.get(ps.name); 16636 } 16637 16638 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16639 : new int[] {userId}; 16640 for (int nextUserId : userIds) { 16641 if (DEBUG_REMOVE) { 16642 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16643 + nextUserId); 16644 } 16645 16646 destroyAppDataLIF(pkg, userId, 16647 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16648 destroyAppProfilesLIF(pkg, userId); 16649 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16650 schedulePackageCleaning(ps.name, nextUserId, false); 16651 synchronized (mPackages) { 16652 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16653 scheduleWritePackageRestrictionsLocked(nextUserId); 16654 } 16655 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16656 } 16657 } 16658 16659 if (outInfo != null) { 16660 outInfo.removedPackage = ps.name; 16661 outInfo.removedAppId = ps.appId; 16662 outInfo.removedUsers = userIds; 16663 } 16664 16665 return true; 16666 } 16667 16668 private final class ClearStorageConnection implements ServiceConnection { 16669 IMediaContainerService mContainerService; 16670 16671 @Override 16672 public void onServiceConnected(ComponentName name, IBinder service) { 16673 synchronized (this) { 16674 mContainerService = IMediaContainerService.Stub 16675 .asInterface(Binder.allowBlocking(service)); 16676 notifyAll(); 16677 } 16678 } 16679 16680 @Override 16681 public void onServiceDisconnected(ComponentName name) { 16682 } 16683 } 16684 16685 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16686 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16687 16688 final boolean mounted; 16689 if (Environment.isExternalStorageEmulated()) { 16690 mounted = true; 16691 } else { 16692 final String status = Environment.getExternalStorageState(); 16693 16694 mounted = status.equals(Environment.MEDIA_MOUNTED) 16695 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16696 } 16697 16698 if (!mounted) { 16699 return; 16700 } 16701 16702 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16703 int[] users; 16704 if (userId == UserHandle.USER_ALL) { 16705 users = sUserManager.getUserIds(); 16706 } else { 16707 users = new int[] { userId }; 16708 } 16709 final ClearStorageConnection conn = new ClearStorageConnection(); 16710 if (mContext.bindServiceAsUser( 16711 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16712 try { 16713 for (int curUser : users) { 16714 long timeout = SystemClock.uptimeMillis() + 5000; 16715 synchronized (conn) { 16716 long now; 16717 while (conn.mContainerService == null && 16718 (now = SystemClock.uptimeMillis()) < timeout) { 16719 try { 16720 conn.wait(timeout - now); 16721 } catch (InterruptedException e) { 16722 } 16723 } 16724 } 16725 if (conn.mContainerService == null) { 16726 return; 16727 } 16728 16729 final UserEnvironment userEnv = new UserEnvironment(curUser); 16730 clearDirectory(conn.mContainerService, 16731 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16732 if (allData) { 16733 clearDirectory(conn.mContainerService, 16734 userEnv.buildExternalStorageAppDataDirs(packageName)); 16735 clearDirectory(conn.mContainerService, 16736 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16737 } 16738 } 16739 } finally { 16740 mContext.unbindService(conn); 16741 } 16742 } 16743 } 16744 16745 @Override 16746 public void clearApplicationProfileData(String packageName) { 16747 enforceSystemOrRoot("Only the system can clear all profile data"); 16748 16749 final PackageParser.Package pkg; 16750 synchronized (mPackages) { 16751 pkg = mPackages.get(packageName); 16752 } 16753 16754 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16755 synchronized (mInstallLock) { 16756 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16757 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16758 true /* removeBaseMarker */); 16759 } 16760 } 16761 } 16762 16763 @Override 16764 public void clearApplicationUserData(final String packageName, 16765 final IPackageDataObserver observer, final int userId) { 16766 mContext.enforceCallingOrSelfPermission( 16767 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16768 16769 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16770 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16771 16772 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16773 throw new SecurityException("Cannot clear data for a protected package: " 16774 + packageName); 16775 } 16776 // Queue up an async operation since the package deletion may take a little while. 16777 mHandler.post(new Runnable() { 16778 public void run() { 16779 mHandler.removeCallbacks(this); 16780 final boolean succeeded; 16781 try (PackageFreezer freezer = freezePackage(packageName, 16782 "clearApplicationUserData")) { 16783 synchronized (mInstallLock) { 16784 succeeded = clearApplicationUserDataLIF(packageName, userId); 16785 } 16786 clearExternalStorageDataSync(packageName, userId, true); 16787 } 16788 if (succeeded) { 16789 // invoke DeviceStorageMonitor's update method to clear any notifications 16790 DeviceStorageMonitorInternal dsm = LocalServices 16791 .getService(DeviceStorageMonitorInternal.class); 16792 if (dsm != null) { 16793 dsm.checkMemory(); 16794 } 16795 } 16796 if(observer != null) { 16797 try { 16798 observer.onRemoveCompleted(packageName, succeeded); 16799 } catch (RemoteException e) { 16800 Log.i(TAG, "Observer no longer exists."); 16801 } 16802 } //end if observer 16803 } //end run 16804 }); 16805 } 16806 16807 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16808 if (packageName == null) { 16809 Slog.w(TAG, "Attempt to delete null packageName."); 16810 return false; 16811 } 16812 16813 // Try finding details about the requested package 16814 PackageParser.Package pkg; 16815 synchronized (mPackages) { 16816 pkg = mPackages.get(packageName); 16817 if (pkg == null) { 16818 final PackageSetting ps = mSettings.mPackages.get(packageName); 16819 if (ps != null) { 16820 pkg = ps.pkg; 16821 } 16822 } 16823 16824 if (pkg == null) { 16825 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16826 return false; 16827 } 16828 16829 PackageSetting ps = (PackageSetting) pkg.mExtras; 16830 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16831 } 16832 16833 clearAppDataLIF(pkg, userId, 16834 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16835 16836 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16837 removeKeystoreDataIfNeeded(userId, appId); 16838 16839 UserManagerInternal umInternal = getUserManagerInternal(); 16840 final int flags; 16841 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16842 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16843 } else if (umInternal.isUserRunning(userId)) { 16844 flags = StorageManager.FLAG_STORAGE_DE; 16845 } else { 16846 flags = 0; 16847 } 16848 prepareAppDataContentsLIF(pkg, userId, flags); 16849 16850 return true; 16851 } 16852 16853 /** 16854 * Reverts user permission state changes (permissions and flags) in 16855 * all packages for a given user. 16856 * 16857 * @param userId The device user for which to do a reset. 16858 */ 16859 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16860 final int packageCount = mPackages.size(); 16861 for (int i = 0; i < packageCount; i++) { 16862 PackageParser.Package pkg = mPackages.valueAt(i); 16863 PackageSetting ps = (PackageSetting) pkg.mExtras; 16864 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16865 } 16866 } 16867 16868 private void resetNetworkPolicies(int userId) { 16869 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16870 } 16871 16872 /** 16873 * Reverts user permission state changes (permissions and flags). 16874 * 16875 * @param ps The package for which to reset. 16876 * @param userId The device user for which to do a reset. 16877 */ 16878 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16879 final PackageSetting ps, final int userId) { 16880 if (ps.pkg == null) { 16881 return; 16882 } 16883 16884 // These are flags that can change base on user actions. 16885 final int userSettableMask = FLAG_PERMISSION_USER_SET 16886 | FLAG_PERMISSION_USER_FIXED 16887 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16888 | FLAG_PERMISSION_REVIEW_REQUIRED; 16889 16890 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16891 | FLAG_PERMISSION_POLICY_FIXED; 16892 16893 boolean writeInstallPermissions = false; 16894 boolean writeRuntimePermissions = false; 16895 16896 final int permissionCount = ps.pkg.requestedPermissions.size(); 16897 for (int i = 0; i < permissionCount; i++) { 16898 String permission = ps.pkg.requestedPermissions.get(i); 16899 16900 BasePermission bp = mSettings.mPermissions.get(permission); 16901 if (bp == null) { 16902 continue; 16903 } 16904 16905 // If shared user we just reset the state to which only this app contributed. 16906 if (ps.sharedUser != null) { 16907 boolean used = false; 16908 final int packageCount = ps.sharedUser.packages.size(); 16909 for (int j = 0; j < packageCount; j++) { 16910 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16911 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16912 && pkg.pkg.requestedPermissions.contains(permission)) { 16913 used = true; 16914 break; 16915 } 16916 } 16917 if (used) { 16918 continue; 16919 } 16920 } 16921 16922 PermissionsState permissionsState = ps.getPermissionsState(); 16923 16924 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16925 16926 // Always clear the user settable flags. 16927 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16928 bp.name) != null; 16929 // If permission review is enabled and this is a legacy app, mark the 16930 // permission as requiring a review as this is the initial state. 16931 int flags = 0; 16932 if (mPermissionReviewRequired 16933 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16934 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16935 } 16936 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16937 if (hasInstallState) { 16938 writeInstallPermissions = true; 16939 } else { 16940 writeRuntimePermissions = true; 16941 } 16942 } 16943 16944 // Below is only runtime permission handling. 16945 if (!bp.isRuntime()) { 16946 continue; 16947 } 16948 16949 // Never clobber system or policy. 16950 if ((oldFlags & policyOrSystemFlags) != 0) { 16951 continue; 16952 } 16953 16954 // If this permission was granted by default, make sure it is. 16955 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16956 if (permissionsState.grantRuntimePermission(bp, userId) 16957 != PERMISSION_OPERATION_FAILURE) { 16958 writeRuntimePermissions = true; 16959 } 16960 // If permission review is enabled the permissions for a legacy apps 16961 // are represented as constantly granted runtime ones, so don't revoke. 16962 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16963 // Otherwise, reset the permission. 16964 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16965 switch (revokeResult) { 16966 case PERMISSION_OPERATION_SUCCESS: 16967 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16968 writeRuntimePermissions = true; 16969 final int appId = ps.appId; 16970 mHandler.post(new Runnable() { 16971 @Override 16972 public void run() { 16973 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16974 } 16975 }); 16976 } break; 16977 } 16978 } 16979 } 16980 16981 // Synchronously write as we are taking permissions away. 16982 if (writeRuntimePermissions) { 16983 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16984 } 16985 16986 // Synchronously write as we are taking permissions away. 16987 if (writeInstallPermissions) { 16988 mSettings.writeLPr(); 16989 } 16990 } 16991 16992 /** 16993 * Remove entries from the keystore daemon. Will only remove it if the 16994 * {@code appId} is valid. 16995 */ 16996 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16997 if (appId < 0) { 16998 return; 16999 } 17000 17001 final KeyStore keyStore = KeyStore.getInstance(); 17002 if (keyStore != null) { 17003 if (userId == UserHandle.USER_ALL) { 17004 for (final int individual : sUserManager.getUserIds()) { 17005 keyStore.clearUid(UserHandle.getUid(individual, appId)); 17006 } 17007 } else { 17008 keyStore.clearUid(UserHandle.getUid(userId, appId)); 17009 } 17010 } else { 17011 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 17012 } 17013 } 17014 17015 @Override 17016 public void deleteApplicationCacheFiles(final String packageName, 17017 final IPackageDataObserver observer) { 17018 final int userId = UserHandle.getCallingUserId(); 17019 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 17020 } 17021 17022 @Override 17023 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 17024 final IPackageDataObserver observer) { 17025 mContext.enforceCallingOrSelfPermission( 17026 android.Manifest.permission.DELETE_CACHE_FILES, null); 17027 enforceCrossUserPermission(Binder.getCallingUid(), userId, 17028 /* requireFullPermission= */ true, /* checkShell= */ false, 17029 "delete application cache files"); 17030 17031 final PackageParser.Package pkg; 17032 synchronized (mPackages) { 17033 pkg = mPackages.get(packageName); 17034 } 17035 17036 // Queue up an async operation since the package deletion may take a little while. 17037 mHandler.post(new Runnable() { 17038 public void run() { 17039 synchronized (mInstallLock) { 17040 final int flags = StorageManager.FLAG_STORAGE_DE 17041 | StorageManager.FLAG_STORAGE_CE; 17042 // We're only clearing cache files, so we don't care if the 17043 // app is unfrozen and still able to run 17044 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 17045 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 17046 } 17047 clearExternalStorageDataSync(packageName, userId, false); 17048 if (observer != null) { 17049 try { 17050 observer.onRemoveCompleted(packageName, true); 17051 } catch (RemoteException e) { 17052 Log.i(TAG, "Observer no longer exists."); 17053 } 17054 } 17055 } 17056 }); 17057 } 17058 17059 @Override 17060 public void getPackageSizeInfo(final String packageName, int userHandle, 17061 final IPackageStatsObserver observer) { 17062 mContext.enforceCallingOrSelfPermission( 17063 android.Manifest.permission.GET_PACKAGE_SIZE, null); 17064 if (packageName == null) { 17065 throw new IllegalArgumentException("Attempt to get size of null packageName"); 17066 } 17067 17068 PackageStats stats = new PackageStats(packageName, userHandle); 17069 17070 /* 17071 * Queue up an async operation since the package measurement may take a 17072 * little while. 17073 */ 17074 Message msg = mHandler.obtainMessage(INIT_COPY); 17075 msg.obj = new MeasureParams(stats, observer); 17076 mHandler.sendMessage(msg); 17077 } 17078 17079 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 17080 final PackageSetting ps; 17081 synchronized (mPackages) { 17082 ps = mSettings.mPackages.get(packageName); 17083 if (ps == null) { 17084 Slog.w(TAG, "Failed to find settings for " + packageName); 17085 return false; 17086 } 17087 } 17088 try { 17089 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 17090 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 17091 ps.getCeDataInode(userId), ps.codePathString, stats); 17092 } catch (InstallerException e) { 17093 Slog.w(TAG, String.valueOf(e)); 17094 return false; 17095 } 17096 17097 // For now, ignore code size of packages on system partition 17098 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 17099 stats.codeSize = 0; 17100 } 17101 17102 return true; 17103 } 17104 17105 private int getUidTargetSdkVersionLockedLPr(int uid) { 17106 Object obj = mSettings.getUserIdLPr(uid); 17107 if (obj instanceof SharedUserSetting) { 17108 final SharedUserSetting sus = (SharedUserSetting) obj; 17109 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 17110 final Iterator<PackageSetting> it = sus.packages.iterator(); 17111 while (it.hasNext()) { 17112 final PackageSetting ps = it.next(); 17113 if (ps.pkg != null) { 17114 int v = ps.pkg.applicationInfo.targetSdkVersion; 17115 if (v < vers) vers = v; 17116 } 17117 } 17118 return vers; 17119 } else if (obj instanceof PackageSetting) { 17120 final PackageSetting ps = (PackageSetting) obj; 17121 if (ps.pkg != null) { 17122 return ps.pkg.applicationInfo.targetSdkVersion; 17123 } 17124 } 17125 return Build.VERSION_CODES.CUR_DEVELOPMENT; 17126 } 17127 17128 @Override 17129 public void addPreferredActivity(IntentFilter filter, int match, 17130 ComponentName[] set, ComponentName activity, int userId) { 17131 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17132 "Adding preferred"); 17133 } 17134 17135 private void addPreferredActivityInternal(IntentFilter filter, int match, 17136 ComponentName[] set, ComponentName activity, boolean always, int userId, 17137 String opname) { 17138 // writer 17139 int callingUid = Binder.getCallingUid(); 17140 enforceCrossUserPermission(callingUid, userId, 17141 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 17142 if (filter.countActions() == 0) { 17143 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17144 return; 17145 } 17146 synchronized (mPackages) { 17147 if (mContext.checkCallingOrSelfPermission( 17148 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17149 != PackageManager.PERMISSION_GRANTED) { 17150 if (getUidTargetSdkVersionLockedLPr(callingUid) 17151 < Build.VERSION_CODES.FROYO) { 17152 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 17153 + callingUid); 17154 return; 17155 } 17156 mContext.enforceCallingOrSelfPermission( 17157 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17158 } 17159 17160 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 17161 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 17162 + userId + ":"); 17163 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17164 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 17165 scheduleWritePackageRestrictionsLocked(userId); 17166 postPreferredActivityChangedBroadcast(userId); 17167 } 17168 } 17169 17170 private void postPreferredActivityChangedBroadcast(int userId) { 17171 mHandler.post(() -> { 17172 final IActivityManager am = ActivityManager.getService(); 17173 if (am == null) { 17174 return; 17175 } 17176 17177 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 17178 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17179 try { 17180 am.broadcastIntent(null, intent, null, null, 17181 0, null, null, null, android.app.AppOpsManager.OP_NONE, 17182 null, false, false, userId); 17183 } catch (RemoteException e) { 17184 } 17185 }); 17186 } 17187 17188 @Override 17189 public void replacePreferredActivity(IntentFilter filter, int match, 17190 ComponentName[] set, ComponentName activity, int userId) { 17191 if (filter.countActions() != 1) { 17192 throw new IllegalArgumentException( 17193 "replacePreferredActivity expects filter to have only 1 action."); 17194 } 17195 if (filter.countDataAuthorities() != 0 17196 || filter.countDataPaths() != 0 17197 || filter.countDataSchemes() > 1 17198 || filter.countDataTypes() != 0) { 17199 throw new IllegalArgumentException( 17200 "replacePreferredActivity expects filter to have no data authorities, " + 17201 "paths, or types; and at most one scheme."); 17202 } 17203 17204 final int callingUid = Binder.getCallingUid(); 17205 enforceCrossUserPermission(callingUid, userId, 17206 true /* requireFullPermission */, false /* checkShell */, 17207 "replace preferred activity"); 17208 synchronized (mPackages) { 17209 if (mContext.checkCallingOrSelfPermission( 17210 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17211 != PackageManager.PERMISSION_GRANTED) { 17212 if (getUidTargetSdkVersionLockedLPr(callingUid) 17213 < Build.VERSION_CODES.FROYO) { 17214 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 17215 + Binder.getCallingUid()); 17216 return; 17217 } 17218 mContext.enforceCallingOrSelfPermission( 17219 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17220 } 17221 17222 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17223 if (pir != null) { 17224 // Get all of the existing entries that exactly match this filter. 17225 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 17226 if (existing != null && existing.size() == 1) { 17227 PreferredActivity cur = existing.get(0); 17228 if (DEBUG_PREFERRED) { 17229 Slog.i(TAG, "Checking replace of preferred:"); 17230 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17231 if (!cur.mPref.mAlways) { 17232 Slog.i(TAG, " -- CUR; not mAlways!"); 17233 } else { 17234 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 17235 Slog.i(TAG, " -- CUR: mSet=" 17236 + Arrays.toString(cur.mPref.mSetComponents)); 17237 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 17238 Slog.i(TAG, " -- NEW: mMatch=" 17239 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 17240 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17241 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17242 } 17243 } 17244 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17245 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17246 && cur.mPref.sameSet(set)) { 17247 // Setting the preferred activity to what it happens to be already 17248 if (DEBUG_PREFERRED) { 17249 Slog.i(TAG, "Replacing with same preferred activity " 17250 + cur.mPref.mShortComponent + " for user " 17251 + userId + ":"); 17252 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17253 } 17254 return; 17255 } 17256 } 17257 17258 if (existing != null) { 17259 if (DEBUG_PREFERRED) { 17260 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17261 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17262 } 17263 for (int i = 0; i < existing.size(); i++) { 17264 PreferredActivity pa = existing.get(i); 17265 if (DEBUG_PREFERRED) { 17266 Slog.i(TAG, "Removing existing preferred activity " 17267 + pa.mPref.mComponent + ":"); 17268 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17269 } 17270 pir.removeFilter(pa); 17271 } 17272 } 17273 } 17274 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17275 "Replacing preferred"); 17276 } 17277 } 17278 17279 @Override 17280 public void clearPackagePreferredActivities(String packageName) { 17281 final int uid = Binder.getCallingUid(); 17282 // writer 17283 synchronized (mPackages) { 17284 PackageParser.Package pkg = mPackages.get(packageName); 17285 if (pkg == null || pkg.applicationInfo.uid != uid) { 17286 if (mContext.checkCallingOrSelfPermission( 17287 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17288 != PackageManager.PERMISSION_GRANTED) { 17289 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17290 < Build.VERSION_CODES.FROYO) { 17291 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17292 + Binder.getCallingUid()); 17293 return; 17294 } 17295 mContext.enforceCallingOrSelfPermission( 17296 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17297 } 17298 } 17299 17300 int user = UserHandle.getCallingUserId(); 17301 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17302 scheduleWritePackageRestrictionsLocked(user); 17303 } 17304 } 17305 } 17306 17307 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17308 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17309 ArrayList<PreferredActivity> removed = null; 17310 boolean changed = false; 17311 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17312 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17313 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17314 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17315 continue; 17316 } 17317 Iterator<PreferredActivity> it = pir.filterIterator(); 17318 while (it.hasNext()) { 17319 PreferredActivity pa = it.next(); 17320 // Mark entry for removal only if it matches the package name 17321 // and the entry is of type "always". 17322 if (packageName == null || 17323 (pa.mPref.mComponent.getPackageName().equals(packageName) 17324 && pa.mPref.mAlways)) { 17325 if (removed == null) { 17326 removed = new ArrayList<PreferredActivity>(); 17327 } 17328 removed.add(pa); 17329 } 17330 } 17331 if (removed != null) { 17332 for (int j=0; j<removed.size(); j++) { 17333 PreferredActivity pa = removed.get(j); 17334 pir.removeFilter(pa); 17335 } 17336 changed = true; 17337 } 17338 } 17339 if (changed) { 17340 postPreferredActivityChangedBroadcast(userId); 17341 } 17342 return changed; 17343 } 17344 17345 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17346 private void clearIntentFilterVerificationsLPw(int userId) { 17347 final int packageCount = mPackages.size(); 17348 for (int i = 0; i < packageCount; i++) { 17349 PackageParser.Package pkg = mPackages.valueAt(i); 17350 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17351 } 17352 } 17353 17354 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17355 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17356 if (userId == UserHandle.USER_ALL) { 17357 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17358 sUserManager.getUserIds())) { 17359 for (int oneUserId : sUserManager.getUserIds()) { 17360 scheduleWritePackageRestrictionsLocked(oneUserId); 17361 } 17362 } 17363 } else { 17364 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17365 scheduleWritePackageRestrictionsLocked(userId); 17366 } 17367 } 17368 } 17369 17370 void clearDefaultBrowserIfNeeded(String packageName) { 17371 for (int oneUserId : sUserManager.getUserIds()) { 17372 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17373 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17374 if (packageName.equals(defaultBrowserPackageName)) { 17375 setDefaultBrowserPackageName(null, oneUserId); 17376 } 17377 } 17378 } 17379 17380 @Override 17381 public void resetApplicationPreferences(int userId) { 17382 mContext.enforceCallingOrSelfPermission( 17383 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17384 final long identity = Binder.clearCallingIdentity(); 17385 // writer 17386 try { 17387 synchronized (mPackages) { 17388 clearPackagePreferredActivitiesLPw(null, userId); 17389 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17390 // TODO: We have to reset the default SMS and Phone. This requires 17391 // significant refactoring to keep all default apps in the package 17392 // manager (cleaner but more work) or have the services provide 17393 // callbacks to the package manager to request a default app reset. 17394 applyFactoryDefaultBrowserLPw(userId); 17395 clearIntentFilterVerificationsLPw(userId); 17396 primeDomainVerificationsLPw(userId); 17397 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17398 scheduleWritePackageRestrictionsLocked(userId); 17399 } 17400 resetNetworkPolicies(userId); 17401 } finally { 17402 Binder.restoreCallingIdentity(identity); 17403 } 17404 } 17405 17406 @Override 17407 public int getPreferredActivities(List<IntentFilter> outFilters, 17408 List<ComponentName> outActivities, String packageName) { 17409 17410 int num = 0; 17411 final int userId = UserHandle.getCallingUserId(); 17412 // reader 17413 synchronized (mPackages) { 17414 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17415 if (pir != null) { 17416 final Iterator<PreferredActivity> it = pir.filterIterator(); 17417 while (it.hasNext()) { 17418 final PreferredActivity pa = it.next(); 17419 if (packageName == null 17420 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17421 && pa.mPref.mAlways)) { 17422 if (outFilters != null) { 17423 outFilters.add(new IntentFilter(pa)); 17424 } 17425 if (outActivities != null) { 17426 outActivities.add(pa.mPref.mComponent); 17427 } 17428 } 17429 } 17430 } 17431 } 17432 17433 return num; 17434 } 17435 17436 @Override 17437 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17438 int userId) { 17439 int callingUid = Binder.getCallingUid(); 17440 if (callingUid != Process.SYSTEM_UID) { 17441 throw new SecurityException( 17442 "addPersistentPreferredActivity can only be run by the system"); 17443 } 17444 if (filter.countActions() == 0) { 17445 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17446 return; 17447 } 17448 synchronized (mPackages) { 17449 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17450 ":"); 17451 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17452 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17453 new PersistentPreferredActivity(filter, activity)); 17454 scheduleWritePackageRestrictionsLocked(userId); 17455 postPreferredActivityChangedBroadcast(userId); 17456 } 17457 } 17458 17459 @Override 17460 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17461 int callingUid = Binder.getCallingUid(); 17462 if (callingUid != Process.SYSTEM_UID) { 17463 throw new SecurityException( 17464 "clearPackagePersistentPreferredActivities can only be run by the system"); 17465 } 17466 ArrayList<PersistentPreferredActivity> removed = null; 17467 boolean changed = false; 17468 synchronized (mPackages) { 17469 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17470 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17471 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17472 .valueAt(i); 17473 if (userId != thisUserId) { 17474 continue; 17475 } 17476 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17477 while (it.hasNext()) { 17478 PersistentPreferredActivity ppa = it.next(); 17479 // Mark entry for removal only if it matches the package name. 17480 if (ppa.mComponent.getPackageName().equals(packageName)) { 17481 if (removed == null) { 17482 removed = new ArrayList<PersistentPreferredActivity>(); 17483 } 17484 removed.add(ppa); 17485 } 17486 } 17487 if (removed != null) { 17488 for (int j=0; j<removed.size(); j++) { 17489 PersistentPreferredActivity ppa = removed.get(j); 17490 ppir.removeFilter(ppa); 17491 } 17492 changed = true; 17493 } 17494 } 17495 17496 if (changed) { 17497 scheduleWritePackageRestrictionsLocked(userId); 17498 postPreferredActivityChangedBroadcast(userId); 17499 } 17500 } 17501 } 17502 17503 /** 17504 * Common machinery for picking apart a restored XML blob and passing 17505 * it to a caller-supplied functor to be applied to the running system. 17506 */ 17507 private void restoreFromXml(XmlPullParser parser, int userId, 17508 String expectedStartTag, BlobXmlRestorer functor) 17509 throws IOException, XmlPullParserException { 17510 int type; 17511 while ((type = parser.next()) != XmlPullParser.START_TAG 17512 && type != XmlPullParser.END_DOCUMENT) { 17513 } 17514 if (type != XmlPullParser.START_TAG) { 17515 // oops didn't find a start tag?! 17516 if (DEBUG_BACKUP) { 17517 Slog.e(TAG, "Didn't find start tag during restore"); 17518 } 17519 return; 17520 } 17521Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17522 // this is supposed to be TAG_PREFERRED_BACKUP 17523 if (!expectedStartTag.equals(parser.getName())) { 17524 if (DEBUG_BACKUP) { 17525 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17526 } 17527 return; 17528 } 17529 17530 // skip interfering stuff, then we're aligned with the backing implementation 17531 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17532Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17533 functor.apply(parser, userId); 17534 } 17535 17536 private interface BlobXmlRestorer { 17537 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17538 } 17539 17540 /** 17541 * Non-Binder method, support for the backup/restore mechanism: write the 17542 * full set of preferred activities in its canonical XML format. Returns the 17543 * XML output as a byte array, or null if there is none. 17544 */ 17545 @Override 17546 public byte[] getPreferredActivityBackup(int userId) { 17547 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17548 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17549 } 17550 17551 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17552 try { 17553 final XmlSerializer serializer = new FastXmlSerializer(); 17554 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17555 serializer.startDocument(null, true); 17556 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17557 17558 synchronized (mPackages) { 17559 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17560 } 17561 17562 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17563 serializer.endDocument(); 17564 serializer.flush(); 17565 } catch (Exception e) { 17566 if (DEBUG_BACKUP) { 17567 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17568 } 17569 return null; 17570 } 17571 17572 return dataStream.toByteArray(); 17573 } 17574 17575 @Override 17576 public void restorePreferredActivities(byte[] backup, int userId) { 17577 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17578 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17579 } 17580 17581 try { 17582 final XmlPullParser parser = Xml.newPullParser(); 17583 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17584 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17585 new BlobXmlRestorer() { 17586 @Override 17587 public void apply(XmlPullParser parser, int userId) 17588 throws XmlPullParserException, IOException { 17589 synchronized (mPackages) { 17590 mSettings.readPreferredActivitiesLPw(parser, userId); 17591 } 17592 } 17593 } ); 17594 } catch (Exception e) { 17595 if (DEBUG_BACKUP) { 17596 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17597 } 17598 } 17599 } 17600 17601 /** 17602 * Non-Binder method, support for the backup/restore mechanism: write the 17603 * default browser (etc) settings in its canonical XML format. Returns the default 17604 * browser XML representation as a byte array, or null if there is none. 17605 */ 17606 @Override 17607 public byte[] getDefaultAppsBackup(int userId) { 17608 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17609 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17610 } 17611 17612 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17613 try { 17614 final XmlSerializer serializer = new FastXmlSerializer(); 17615 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17616 serializer.startDocument(null, true); 17617 serializer.startTag(null, TAG_DEFAULT_APPS); 17618 17619 synchronized (mPackages) { 17620 mSettings.writeDefaultAppsLPr(serializer, userId); 17621 } 17622 17623 serializer.endTag(null, TAG_DEFAULT_APPS); 17624 serializer.endDocument(); 17625 serializer.flush(); 17626 } catch (Exception e) { 17627 if (DEBUG_BACKUP) { 17628 Slog.e(TAG, "Unable to write default apps for backup", e); 17629 } 17630 return null; 17631 } 17632 17633 return dataStream.toByteArray(); 17634 } 17635 17636 @Override 17637 public void restoreDefaultApps(byte[] backup, int userId) { 17638 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17639 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17640 } 17641 17642 try { 17643 final XmlPullParser parser = Xml.newPullParser(); 17644 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17645 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17646 new BlobXmlRestorer() { 17647 @Override 17648 public void apply(XmlPullParser parser, int userId) 17649 throws XmlPullParserException, IOException { 17650 synchronized (mPackages) { 17651 mSettings.readDefaultAppsLPw(parser, userId); 17652 } 17653 } 17654 } ); 17655 } catch (Exception e) { 17656 if (DEBUG_BACKUP) { 17657 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17658 } 17659 } 17660 } 17661 17662 @Override 17663 public byte[] getIntentFilterVerificationBackup(int userId) { 17664 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17665 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17666 } 17667 17668 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17669 try { 17670 final XmlSerializer serializer = new FastXmlSerializer(); 17671 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17672 serializer.startDocument(null, true); 17673 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17674 17675 synchronized (mPackages) { 17676 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17677 } 17678 17679 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17680 serializer.endDocument(); 17681 serializer.flush(); 17682 } catch (Exception e) { 17683 if (DEBUG_BACKUP) { 17684 Slog.e(TAG, "Unable to write default apps for backup", e); 17685 } 17686 return null; 17687 } 17688 17689 return dataStream.toByteArray(); 17690 } 17691 17692 @Override 17693 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17694 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17695 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17696 } 17697 17698 try { 17699 final XmlPullParser parser = Xml.newPullParser(); 17700 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17701 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17702 new BlobXmlRestorer() { 17703 @Override 17704 public void apply(XmlPullParser parser, int userId) 17705 throws XmlPullParserException, IOException { 17706 synchronized (mPackages) { 17707 mSettings.readAllDomainVerificationsLPr(parser, userId); 17708 mSettings.writeLPr(); 17709 } 17710 } 17711 } ); 17712 } catch (Exception e) { 17713 if (DEBUG_BACKUP) { 17714 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17715 } 17716 } 17717 } 17718 17719 @Override 17720 public byte[] getPermissionGrantBackup(int userId) { 17721 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17722 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17723 } 17724 17725 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17726 try { 17727 final XmlSerializer serializer = new FastXmlSerializer(); 17728 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17729 serializer.startDocument(null, true); 17730 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17731 17732 synchronized (mPackages) { 17733 serializeRuntimePermissionGrantsLPr(serializer, userId); 17734 } 17735 17736 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17737 serializer.endDocument(); 17738 serializer.flush(); 17739 } catch (Exception e) { 17740 if (DEBUG_BACKUP) { 17741 Slog.e(TAG, "Unable to write default apps for backup", e); 17742 } 17743 return null; 17744 } 17745 17746 return dataStream.toByteArray(); 17747 } 17748 17749 @Override 17750 public void restorePermissionGrants(byte[] backup, int userId) { 17751 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17752 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17753 } 17754 17755 try { 17756 final XmlPullParser parser = Xml.newPullParser(); 17757 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17758 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17759 new BlobXmlRestorer() { 17760 @Override 17761 public void apply(XmlPullParser parser, int userId) 17762 throws XmlPullParserException, IOException { 17763 synchronized (mPackages) { 17764 processRestoredPermissionGrantsLPr(parser, userId); 17765 } 17766 } 17767 } ); 17768 } catch (Exception e) { 17769 if (DEBUG_BACKUP) { 17770 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17771 } 17772 } 17773 } 17774 17775 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17776 throws IOException { 17777 serializer.startTag(null, TAG_ALL_GRANTS); 17778 17779 final int N = mSettings.mPackages.size(); 17780 for (int i = 0; i < N; i++) { 17781 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17782 boolean pkgGrantsKnown = false; 17783 17784 PermissionsState packagePerms = ps.getPermissionsState(); 17785 17786 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17787 final int grantFlags = state.getFlags(); 17788 // only look at grants that are not system/policy fixed 17789 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17790 final boolean isGranted = state.isGranted(); 17791 // And only back up the user-twiddled state bits 17792 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17793 final String packageName = mSettings.mPackages.keyAt(i); 17794 if (!pkgGrantsKnown) { 17795 serializer.startTag(null, TAG_GRANT); 17796 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17797 pkgGrantsKnown = true; 17798 } 17799 17800 final boolean userSet = 17801 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17802 final boolean userFixed = 17803 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17804 final boolean revoke = 17805 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17806 17807 serializer.startTag(null, TAG_PERMISSION); 17808 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17809 if (isGranted) { 17810 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17811 } 17812 if (userSet) { 17813 serializer.attribute(null, ATTR_USER_SET, "true"); 17814 } 17815 if (userFixed) { 17816 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17817 } 17818 if (revoke) { 17819 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17820 } 17821 serializer.endTag(null, TAG_PERMISSION); 17822 } 17823 } 17824 } 17825 17826 if (pkgGrantsKnown) { 17827 serializer.endTag(null, TAG_GRANT); 17828 } 17829 } 17830 17831 serializer.endTag(null, TAG_ALL_GRANTS); 17832 } 17833 17834 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17835 throws XmlPullParserException, IOException { 17836 String pkgName = null; 17837 int outerDepth = parser.getDepth(); 17838 int type; 17839 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17840 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17841 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17842 continue; 17843 } 17844 17845 final String tagName = parser.getName(); 17846 if (tagName.equals(TAG_GRANT)) { 17847 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17848 if (DEBUG_BACKUP) { 17849 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17850 } 17851 } else if (tagName.equals(TAG_PERMISSION)) { 17852 17853 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17854 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17855 17856 int newFlagSet = 0; 17857 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17858 newFlagSet |= FLAG_PERMISSION_USER_SET; 17859 } 17860 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17861 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17862 } 17863 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17864 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17865 } 17866 if (DEBUG_BACKUP) { 17867 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17868 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17869 } 17870 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17871 if (ps != null) { 17872 // Already installed so we apply the grant immediately 17873 if (DEBUG_BACKUP) { 17874 Slog.v(TAG, " + already installed; applying"); 17875 } 17876 PermissionsState perms = ps.getPermissionsState(); 17877 BasePermission bp = mSettings.mPermissions.get(permName); 17878 if (bp != null) { 17879 if (isGranted) { 17880 perms.grantRuntimePermission(bp, userId); 17881 } 17882 if (newFlagSet != 0) { 17883 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17884 } 17885 } 17886 } else { 17887 // Need to wait for post-restore install to apply the grant 17888 if (DEBUG_BACKUP) { 17889 Slog.v(TAG, " - not yet installed; saving for later"); 17890 } 17891 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17892 isGranted, newFlagSet, userId); 17893 } 17894 } else { 17895 PackageManagerService.reportSettingsProblem(Log.WARN, 17896 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17897 XmlUtils.skipCurrentTag(parser); 17898 } 17899 } 17900 17901 scheduleWriteSettingsLocked(); 17902 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17903 } 17904 17905 @Override 17906 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17907 int sourceUserId, int targetUserId, int flags) { 17908 mContext.enforceCallingOrSelfPermission( 17909 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17910 int callingUid = Binder.getCallingUid(); 17911 enforceOwnerRights(ownerPackage, callingUid); 17912 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17913 if (intentFilter.countActions() == 0) { 17914 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17915 return; 17916 } 17917 synchronized (mPackages) { 17918 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17919 ownerPackage, targetUserId, flags); 17920 CrossProfileIntentResolver resolver = 17921 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17922 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17923 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17924 if (existing != null) { 17925 int size = existing.size(); 17926 for (int i = 0; i < size; i++) { 17927 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17928 return; 17929 } 17930 } 17931 } 17932 resolver.addFilter(newFilter); 17933 scheduleWritePackageRestrictionsLocked(sourceUserId); 17934 } 17935 } 17936 17937 @Override 17938 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17939 mContext.enforceCallingOrSelfPermission( 17940 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17941 int callingUid = Binder.getCallingUid(); 17942 enforceOwnerRights(ownerPackage, callingUid); 17943 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17944 synchronized (mPackages) { 17945 CrossProfileIntentResolver resolver = 17946 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17947 ArraySet<CrossProfileIntentFilter> set = 17948 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17949 for (CrossProfileIntentFilter filter : set) { 17950 if (filter.getOwnerPackage().equals(ownerPackage)) { 17951 resolver.removeFilter(filter); 17952 } 17953 } 17954 scheduleWritePackageRestrictionsLocked(sourceUserId); 17955 } 17956 } 17957 17958 // Enforcing that callingUid is owning pkg on userId 17959 private void enforceOwnerRights(String pkg, int callingUid) { 17960 // The system owns everything. 17961 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17962 return; 17963 } 17964 int callingUserId = UserHandle.getUserId(callingUid); 17965 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17966 if (pi == null) { 17967 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17968 + callingUserId); 17969 } 17970 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17971 throw new SecurityException("Calling uid " + callingUid 17972 + " does not own package " + pkg); 17973 } 17974 } 17975 17976 @Override 17977 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17978 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17979 } 17980 17981 private Intent getHomeIntent() { 17982 Intent intent = new Intent(Intent.ACTION_MAIN); 17983 intent.addCategory(Intent.CATEGORY_HOME); 17984 intent.addCategory(Intent.CATEGORY_DEFAULT); 17985 return intent; 17986 } 17987 17988 private IntentFilter getHomeFilter() { 17989 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17990 filter.addCategory(Intent.CATEGORY_HOME); 17991 filter.addCategory(Intent.CATEGORY_DEFAULT); 17992 return filter; 17993 } 17994 17995 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17996 int userId) { 17997 Intent intent = getHomeIntent(); 17998 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17999 PackageManager.GET_META_DATA, userId); 18000 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 18001 true, false, false, userId); 18002 18003 allHomeCandidates.clear(); 18004 if (list != null) { 18005 for (ResolveInfo ri : list) { 18006 allHomeCandidates.add(ri); 18007 } 18008 } 18009 return (preferred == null || preferred.activityInfo == null) 18010 ? null 18011 : new ComponentName(preferred.activityInfo.packageName, 18012 preferred.activityInfo.name); 18013 } 18014 18015 @Override 18016 public void setHomeActivity(ComponentName comp, int userId) { 18017 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 18018 getHomeActivitiesAsUser(homeActivities, userId); 18019 18020 boolean found = false; 18021 18022 final int size = homeActivities.size(); 18023 final ComponentName[] set = new ComponentName[size]; 18024 for (int i = 0; i < size; i++) { 18025 final ResolveInfo candidate = homeActivities.get(i); 18026 final ActivityInfo info = candidate.activityInfo; 18027 final ComponentName activityName = new ComponentName(info.packageName, info.name); 18028 set[i] = activityName; 18029 if (!found && activityName.equals(comp)) { 18030 found = true; 18031 } 18032 } 18033 if (!found) { 18034 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 18035 + userId); 18036 } 18037 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 18038 set, comp, userId); 18039 } 18040 18041 private @Nullable String getSetupWizardPackageName() { 18042 final Intent intent = new Intent(Intent.ACTION_MAIN); 18043 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 18044 18045 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18046 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18047 | MATCH_DISABLED_COMPONENTS, 18048 UserHandle.myUserId()); 18049 if (matches.size() == 1) { 18050 return matches.get(0).getComponentInfo().packageName; 18051 } else { 18052 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 18053 + ": matches=" + matches); 18054 return null; 18055 } 18056 } 18057 18058 private @Nullable String getStorageManagerPackageName() { 18059 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 18060 18061 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18062 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18063 | MATCH_DISABLED_COMPONENTS, 18064 UserHandle.myUserId()); 18065 if (matches.size() == 1) { 18066 return matches.get(0).getComponentInfo().packageName; 18067 } else { 18068 Slog.e(TAG, "There should probably be exactly one storage manager; found " 18069 + matches.size() + ": matches=" + matches); 18070 return null; 18071 } 18072 } 18073 18074 @Override 18075 public void setApplicationEnabledSetting(String appPackageName, 18076 int newState, int flags, int userId, String callingPackage) { 18077 if (!sUserManager.exists(userId)) return; 18078 if (callingPackage == null) { 18079 callingPackage = Integer.toString(Binder.getCallingUid()); 18080 } 18081 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 18082 } 18083 18084 @Override 18085 public void setComponentEnabledSetting(ComponentName componentName, 18086 int newState, int flags, int userId) { 18087 if (!sUserManager.exists(userId)) return; 18088 setEnabledSetting(componentName.getPackageName(), 18089 componentName.getClassName(), newState, flags, userId, null); 18090 } 18091 18092 private void setEnabledSetting(final String packageName, String className, int newState, 18093 final int flags, int userId, String callingPackage) { 18094 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 18095 || newState == COMPONENT_ENABLED_STATE_ENABLED 18096 || newState == COMPONENT_ENABLED_STATE_DISABLED 18097 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18098 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 18099 throw new IllegalArgumentException("Invalid new component state: " 18100 + newState); 18101 } 18102 PackageSetting pkgSetting; 18103 final int uid = Binder.getCallingUid(); 18104 final int permission; 18105 if (uid == Process.SYSTEM_UID) { 18106 permission = PackageManager.PERMISSION_GRANTED; 18107 } else { 18108 permission = mContext.checkCallingOrSelfPermission( 18109 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18110 } 18111 enforceCrossUserPermission(uid, userId, 18112 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 18113 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18114 boolean sendNow = false; 18115 boolean isApp = (className == null); 18116 String componentName = isApp ? packageName : className; 18117 int packageUid = -1; 18118 ArrayList<String> components; 18119 18120 // writer 18121 synchronized (mPackages) { 18122 pkgSetting = mSettings.mPackages.get(packageName); 18123 if (pkgSetting == null) { 18124 if (className == null) { 18125 throw new IllegalArgumentException("Unknown package: " + packageName); 18126 } 18127 throw new IllegalArgumentException( 18128 "Unknown component: " + packageName + "/" + className); 18129 } 18130 } 18131 18132 // Limit who can change which apps 18133 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 18134 // Don't allow apps that don't have permission to modify other apps 18135 if (!allowedByPermission) { 18136 throw new SecurityException( 18137 "Permission Denial: attempt to change component state from pid=" 18138 + Binder.getCallingPid() 18139 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 18140 } 18141 // Don't allow changing protected packages. 18142 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 18143 throw new SecurityException("Cannot disable a protected package: " + packageName); 18144 } 18145 } 18146 18147 synchronized (mPackages) { 18148 if (uid == Process.SHELL_UID 18149 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 18150 // Shell can only change whole packages between ENABLED and DISABLED_USER states 18151 // unless it is a test package. 18152 int oldState = pkgSetting.getEnabled(userId); 18153 if (className == null 18154 && 18155 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 18156 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 18157 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 18158 && 18159 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18160 || newState == COMPONENT_ENABLED_STATE_DEFAULT 18161 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 18162 // ok 18163 } else { 18164 throw new SecurityException( 18165 "Shell cannot change component state for " + packageName + "/" 18166 + className + " to " + newState); 18167 } 18168 } 18169 if (className == null) { 18170 // We're dealing with an application/package level state change 18171 if (pkgSetting.getEnabled(userId) == newState) { 18172 // Nothing to do 18173 return; 18174 } 18175 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 18176 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 18177 // Don't care about who enables an app. 18178 callingPackage = null; 18179 } 18180 pkgSetting.setEnabled(newState, userId, callingPackage); 18181 // pkgSetting.pkg.mSetEnabled = newState; 18182 } else { 18183 // We're dealing with a component level state change 18184 // First, verify that this is a valid class name. 18185 PackageParser.Package pkg = pkgSetting.pkg; 18186 if (pkg == null || !pkg.hasComponentClassName(className)) { 18187 if (pkg != null && 18188 pkg.applicationInfo.targetSdkVersion >= 18189 Build.VERSION_CODES.JELLY_BEAN) { 18190 throw new IllegalArgumentException("Component class " + className 18191 + " does not exist in " + packageName); 18192 } else { 18193 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 18194 + className + " does not exist in " + packageName); 18195 } 18196 } 18197 switch (newState) { 18198 case COMPONENT_ENABLED_STATE_ENABLED: 18199 if (!pkgSetting.enableComponentLPw(className, userId)) { 18200 return; 18201 } 18202 break; 18203 case COMPONENT_ENABLED_STATE_DISABLED: 18204 if (!pkgSetting.disableComponentLPw(className, userId)) { 18205 return; 18206 } 18207 break; 18208 case COMPONENT_ENABLED_STATE_DEFAULT: 18209 if (!pkgSetting.restoreComponentLPw(className, userId)) { 18210 return; 18211 } 18212 break; 18213 default: 18214 Slog.e(TAG, "Invalid new component state: " + newState); 18215 return; 18216 } 18217 } 18218 scheduleWritePackageRestrictionsLocked(userId); 18219 components = mPendingBroadcasts.get(userId, packageName); 18220 final boolean newPackage = components == null; 18221 if (newPackage) { 18222 components = new ArrayList<String>(); 18223 } 18224 if (!components.contains(componentName)) { 18225 components.add(componentName); 18226 } 18227 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 18228 sendNow = true; 18229 // Purge entry from pending broadcast list if another one exists already 18230 // since we are sending one right away. 18231 mPendingBroadcasts.remove(userId, packageName); 18232 } else { 18233 if (newPackage) { 18234 mPendingBroadcasts.put(userId, packageName, components); 18235 } 18236 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 18237 // Schedule a message 18238 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 18239 } 18240 } 18241 } 18242 18243 long callingId = Binder.clearCallingIdentity(); 18244 try { 18245 if (sendNow) { 18246 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18247 sendPackageChangedBroadcast(packageName, 18248 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18249 } 18250 } finally { 18251 Binder.restoreCallingIdentity(callingId); 18252 } 18253 } 18254 18255 @Override 18256 public void flushPackageRestrictionsAsUser(int userId) { 18257 if (!sUserManager.exists(userId)) { 18258 return; 18259 } 18260 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18261 false /* checkShell */, "flushPackageRestrictions"); 18262 synchronized (mPackages) { 18263 mSettings.writePackageRestrictionsLPr(userId); 18264 mDirtyUsers.remove(userId); 18265 if (mDirtyUsers.isEmpty()) { 18266 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18267 } 18268 } 18269 } 18270 18271 private void sendPackageChangedBroadcast(String packageName, 18272 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18273 if (DEBUG_INSTALL) 18274 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18275 + componentNames); 18276 Bundle extras = new Bundle(4); 18277 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18278 String nameList[] = new String[componentNames.size()]; 18279 componentNames.toArray(nameList); 18280 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18281 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18282 extras.putInt(Intent.EXTRA_UID, packageUid); 18283 // If this is not reporting a change of the overall package, then only send it 18284 // to registered receivers. We don't want to launch a swath of apps for every 18285 // little component state change. 18286 final int flags = !componentNames.contains(packageName) 18287 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18288 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18289 new int[] {UserHandle.getUserId(packageUid)}); 18290 } 18291 18292 @Override 18293 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18294 if (!sUserManager.exists(userId)) return; 18295 final int uid = Binder.getCallingUid(); 18296 final int permission = mContext.checkCallingOrSelfPermission( 18297 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18298 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18299 enforceCrossUserPermission(uid, userId, 18300 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18301 // writer 18302 synchronized (mPackages) { 18303 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18304 allowedByPermission, uid, userId)) { 18305 scheduleWritePackageRestrictionsLocked(userId); 18306 } 18307 } 18308 } 18309 18310 @Override 18311 public String getInstallerPackageName(String packageName) { 18312 // reader 18313 synchronized (mPackages) { 18314 return mSettings.getInstallerPackageNameLPr(packageName); 18315 } 18316 } 18317 18318 public boolean isOrphaned(String packageName) { 18319 // reader 18320 synchronized (mPackages) { 18321 return mSettings.isOrphaned(packageName); 18322 } 18323 } 18324 18325 @Override 18326 public int getApplicationEnabledSetting(String packageName, int userId) { 18327 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18328 int uid = Binder.getCallingUid(); 18329 enforceCrossUserPermission(uid, userId, 18330 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18331 // reader 18332 synchronized (mPackages) { 18333 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18334 } 18335 } 18336 18337 @Override 18338 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18339 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18340 int uid = Binder.getCallingUid(); 18341 enforceCrossUserPermission(uid, userId, 18342 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18343 // reader 18344 synchronized (mPackages) { 18345 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18346 } 18347 } 18348 18349 @Override 18350 public void enterSafeMode() { 18351 enforceSystemOrRoot("Only the system can request entering safe mode"); 18352 18353 if (!mSystemReady) { 18354 mSafeMode = true; 18355 } 18356 } 18357 18358 @Override 18359 public void systemReady() { 18360 mSystemReady = true; 18361 18362 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18363 // disabled after already being started. 18364 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18365 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18366 18367 // Read the compatibilty setting when the system is ready. 18368 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18369 mContext.getContentResolver(), 18370 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18371 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18372 if (DEBUG_SETTINGS) { 18373 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18374 } 18375 18376 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18377 18378 synchronized (mPackages) { 18379 // Verify that all of the preferred activity components actually 18380 // exist. It is possible for applications to be updated and at 18381 // that point remove a previously declared activity component that 18382 // had been set as a preferred activity. We try to clean this up 18383 // the next time we encounter that preferred activity, but it is 18384 // possible for the user flow to never be able to return to that 18385 // situation so here we do a sanity check to make sure we haven't 18386 // left any junk around. 18387 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18388 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18389 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18390 removed.clear(); 18391 for (PreferredActivity pa : pir.filterSet()) { 18392 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18393 removed.add(pa); 18394 } 18395 } 18396 if (removed.size() > 0) { 18397 for (int r=0; r<removed.size(); r++) { 18398 PreferredActivity pa = removed.get(r); 18399 Slog.w(TAG, "Removing dangling preferred activity: " 18400 + pa.mPref.mComponent); 18401 pir.removeFilter(pa); 18402 } 18403 mSettings.writePackageRestrictionsLPr( 18404 mSettings.mPreferredActivities.keyAt(i)); 18405 } 18406 } 18407 18408 for (int userId : UserManagerService.getInstance().getUserIds()) { 18409 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18410 grantPermissionsUserIds = ArrayUtils.appendInt( 18411 grantPermissionsUserIds, userId); 18412 } 18413 } 18414 } 18415 sUserManager.systemReady(); 18416 18417 // If we upgraded grant all default permissions before kicking off. 18418 for (int userId : grantPermissionsUserIds) { 18419 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18420 } 18421 18422 // If we did not grant default permissions, we preload from this the 18423 // default permission exceptions lazily to ensure we don't hit the 18424 // disk on a new user creation. 18425 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18426 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18427 } 18428 18429 // Kick off any messages waiting for system ready 18430 if (mPostSystemReadyMessages != null) { 18431 for (Message msg : mPostSystemReadyMessages) { 18432 msg.sendToTarget(); 18433 } 18434 mPostSystemReadyMessages = null; 18435 } 18436 18437 // Watch for external volumes that come and go over time 18438 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18439 storage.registerListener(mStorageListener); 18440 18441 mInstallerService.systemReady(); 18442 mPackageDexOptimizer.systemReady(); 18443 18444 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 18445 StorageManagerInternal.class); 18446 StorageManagerInternal.addExternalStoragePolicy( 18447 new StorageManagerInternal.ExternalStorageMountPolicy() { 18448 @Override 18449 public int getMountMode(int uid, String packageName) { 18450 if (Process.isIsolated(uid)) { 18451 return Zygote.MOUNT_EXTERNAL_NONE; 18452 } 18453 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18454 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18455 } 18456 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18457 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18458 } 18459 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18460 return Zygote.MOUNT_EXTERNAL_READ; 18461 } 18462 return Zygote.MOUNT_EXTERNAL_WRITE; 18463 } 18464 18465 @Override 18466 public boolean hasExternalStorage(int uid, String packageName) { 18467 return true; 18468 } 18469 }); 18470 18471 // Now that we're mostly running, clean up stale users and apps 18472 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18473 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18474 } 18475 18476 @Override 18477 public boolean isSafeMode() { 18478 return mSafeMode; 18479 } 18480 18481 @Override 18482 public boolean hasSystemUidErrors() { 18483 return mHasSystemUidErrors; 18484 } 18485 18486 static String arrayToString(int[] array) { 18487 StringBuffer buf = new StringBuffer(128); 18488 buf.append('['); 18489 if (array != null) { 18490 for (int i=0; i<array.length; i++) { 18491 if (i > 0) buf.append(", "); 18492 buf.append(array[i]); 18493 } 18494 } 18495 buf.append(']'); 18496 return buf.toString(); 18497 } 18498 18499 static class DumpState { 18500 public static final int DUMP_LIBS = 1 << 0; 18501 public static final int DUMP_FEATURES = 1 << 1; 18502 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18503 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18504 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18505 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18506 public static final int DUMP_PERMISSIONS = 1 << 6; 18507 public static final int DUMP_PACKAGES = 1 << 7; 18508 public static final int DUMP_SHARED_USERS = 1 << 8; 18509 public static final int DUMP_MESSAGES = 1 << 9; 18510 public static final int DUMP_PROVIDERS = 1 << 10; 18511 public static final int DUMP_VERIFIERS = 1 << 11; 18512 public static final int DUMP_PREFERRED = 1 << 12; 18513 public static final int DUMP_PREFERRED_XML = 1 << 13; 18514 public static final int DUMP_KEYSETS = 1 << 14; 18515 public static final int DUMP_VERSION = 1 << 15; 18516 public static final int DUMP_INSTALLS = 1 << 16; 18517 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18518 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18519 public static final int DUMP_FROZEN = 1 << 19; 18520 public static final int DUMP_DEXOPT = 1 << 20; 18521 public static final int DUMP_COMPILER_STATS = 1 << 21; 18522 18523 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18524 18525 private int mTypes; 18526 18527 private int mOptions; 18528 18529 private boolean mTitlePrinted; 18530 18531 private SharedUserSetting mSharedUser; 18532 18533 public boolean isDumping(int type) { 18534 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18535 return true; 18536 } 18537 18538 return (mTypes & type) != 0; 18539 } 18540 18541 public void setDump(int type) { 18542 mTypes |= type; 18543 } 18544 18545 public boolean isOptionEnabled(int option) { 18546 return (mOptions & option) != 0; 18547 } 18548 18549 public void setOptionEnabled(int option) { 18550 mOptions |= option; 18551 } 18552 18553 public boolean onTitlePrinted() { 18554 final boolean printed = mTitlePrinted; 18555 mTitlePrinted = true; 18556 return printed; 18557 } 18558 18559 public boolean getTitlePrinted() { 18560 return mTitlePrinted; 18561 } 18562 18563 public void setTitlePrinted(boolean enabled) { 18564 mTitlePrinted = enabled; 18565 } 18566 18567 public SharedUserSetting getSharedUser() { 18568 return mSharedUser; 18569 } 18570 18571 public void setSharedUser(SharedUserSetting user) { 18572 mSharedUser = user; 18573 } 18574 } 18575 18576 @Override 18577 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18578 FileDescriptor err, String[] args, ShellCallback callback, 18579 ResultReceiver resultReceiver) { 18580 (new PackageManagerShellCommand(this)).exec( 18581 this, in, out, err, args, callback, resultReceiver); 18582 } 18583 18584 @Override 18585 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18586 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18587 != PackageManager.PERMISSION_GRANTED) { 18588 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18589 + Binder.getCallingPid() 18590 + ", uid=" + Binder.getCallingUid() 18591 + " without permission " 18592 + android.Manifest.permission.DUMP); 18593 return; 18594 } 18595 18596 DumpState dumpState = new DumpState(); 18597 boolean fullPreferred = false; 18598 boolean checkin = false; 18599 18600 String packageName = null; 18601 ArraySet<String> permissionNames = null; 18602 18603 int opti = 0; 18604 while (opti < args.length) { 18605 String opt = args[opti]; 18606 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18607 break; 18608 } 18609 opti++; 18610 18611 if ("-a".equals(opt)) { 18612 // Right now we only know how to print all. 18613 } else if ("-h".equals(opt)) { 18614 pw.println("Package manager dump options:"); 18615 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18616 pw.println(" --checkin: dump for a checkin"); 18617 pw.println(" -f: print details of intent filters"); 18618 pw.println(" -h: print this help"); 18619 pw.println(" cmd may be one of:"); 18620 pw.println(" l[ibraries]: list known shared libraries"); 18621 pw.println(" f[eatures]: list device features"); 18622 pw.println(" k[eysets]: print known keysets"); 18623 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18624 pw.println(" perm[issions]: dump permissions"); 18625 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18626 pw.println(" pref[erred]: print preferred package settings"); 18627 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18628 pw.println(" prov[iders]: dump content providers"); 18629 pw.println(" p[ackages]: dump installed packages"); 18630 pw.println(" s[hared-users]: dump shared user IDs"); 18631 pw.println(" m[essages]: print collected runtime messages"); 18632 pw.println(" v[erifiers]: print package verifier info"); 18633 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18634 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18635 pw.println(" version: print database version info"); 18636 pw.println(" write: write current settings now"); 18637 pw.println(" installs: details about install sessions"); 18638 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18639 pw.println(" dexopt: dump dexopt state"); 18640 pw.println(" compiler-stats: dump compiler statistics"); 18641 pw.println(" <package.name>: info about given package"); 18642 return; 18643 } else if ("--checkin".equals(opt)) { 18644 checkin = true; 18645 } else if ("-f".equals(opt)) { 18646 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18647 } else { 18648 pw.println("Unknown argument: " + opt + "; use -h for help"); 18649 } 18650 } 18651 18652 // Is the caller requesting to dump a particular piece of data? 18653 if (opti < args.length) { 18654 String cmd = args[opti]; 18655 opti++; 18656 // Is this a package name? 18657 if ("android".equals(cmd) || cmd.contains(".")) { 18658 packageName = cmd; 18659 // When dumping a single package, we always dump all of its 18660 // filter information since the amount of data will be reasonable. 18661 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18662 } else if ("check-permission".equals(cmd)) { 18663 if (opti >= args.length) { 18664 pw.println("Error: check-permission missing permission argument"); 18665 return; 18666 } 18667 String perm = args[opti]; 18668 opti++; 18669 if (opti >= args.length) { 18670 pw.println("Error: check-permission missing package argument"); 18671 return; 18672 } 18673 String pkg = args[opti]; 18674 opti++; 18675 int user = UserHandle.getUserId(Binder.getCallingUid()); 18676 if (opti < args.length) { 18677 try { 18678 user = Integer.parseInt(args[opti]); 18679 } catch (NumberFormatException e) { 18680 pw.println("Error: check-permission user argument is not a number: " 18681 + args[opti]); 18682 return; 18683 } 18684 } 18685 pw.println(checkPermission(perm, pkg, user)); 18686 return; 18687 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18688 dumpState.setDump(DumpState.DUMP_LIBS); 18689 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18690 dumpState.setDump(DumpState.DUMP_FEATURES); 18691 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18692 if (opti >= args.length) { 18693 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18694 | DumpState.DUMP_SERVICE_RESOLVERS 18695 | DumpState.DUMP_RECEIVER_RESOLVERS 18696 | DumpState.DUMP_CONTENT_RESOLVERS); 18697 } else { 18698 while (opti < args.length) { 18699 String name = args[opti]; 18700 if ("a".equals(name) || "activity".equals(name)) { 18701 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18702 } else if ("s".equals(name) || "service".equals(name)) { 18703 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18704 } else if ("r".equals(name) || "receiver".equals(name)) { 18705 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18706 } else if ("c".equals(name) || "content".equals(name)) { 18707 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18708 } else { 18709 pw.println("Error: unknown resolver table type: " + name); 18710 return; 18711 } 18712 opti++; 18713 } 18714 } 18715 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18716 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18717 } else if ("permission".equals(cmd)) { 18718 if (opti >= args.length) { 18719 pw.println("Error: permission requires permission name"); 18720 return; 18721 } 18722 permissionNames = new ArraySet<>(); 18723 while (opti < args.length) { 18724 permissionNames.add(args[opti]); 18725 opti++; 18726 } 18727 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18728 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18729 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18730 dumpState.setDump(DumpState.DUMP_PREFERRED); 18731 } else if ("preferred-xml".equals(cmd)) { 18732 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18733 if (opti < args.length && "--full".equals(args[opti])) { 18734 fullPreferred = true; 18735 opti++; 18736 } 18737 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18738 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18739 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18740 dumpState.setDump(DumpState.DUMP_PACKAGES); 18741 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18742 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18743 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18744 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18745 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18746 dumpState.setDump(DumpState.DUMP_MESSAGES); 18747 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18748 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18749 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18750 || "intent-filter-verifiers".equals(cmd)) { 18751 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18752 } else if ("version".equals(cmd)) { 18753 dumpState.setDump(DumpState.DUMP_VERSION); 18754 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18755 dumpState.setDump(DumpState.DUMP_KEYSETS); 18756 } else if ("installs".equals(cmd)) { 18757 dumpState.setDump(DumpState.DUMP_INSTALLS); 18758 } else if ("frozen".equals(cmd)) { 18759 dumpState.setDump(DumpState.DUMP_FROZEN); 18760 } else if ("dexopt".equals(cmd)) { 18761 dumpState.setDump(DumpState.DUMP_DEXOPT); 18762 } else if ("compiler-stats".equals(cmd)) { 18763 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18764 } else if ("write".equals(cmd)) { 18765 synchronized (mPackages) { 18766 mSettings.writeLPr(); 18767 pw.println("Settings written."); 18768 return; 18769 } 18770 } 18771 } 18772 18773 if (checkin) { 18774 pw.println("vers,1"); 18775 } 18776 18777 // reader 18778 synchronized (mPackages) { 18779 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18780 if (!checkin) { 18781 if (dumpState.onTitlePrinted()) 18782 pw.println(); 18783 pw.println("Database versions:"); 18784 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18785 } 18786 } 18787 18788 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18789 if (!checkin) { 18790 if (dumpState.onTitlePrinted()) 18791 pw.println(); 18792 pw.println("Verifiers:"); 18793 pw.print(" Required: "); 18794 pw.print(mRequiredVerifierPackage); 18795 pw.print(" (uid="); 18796 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18797 UserHandle.USER_SYSTEM)); 18798 pw.println(")"); 18799 } else if (mRequiredVerifierPackage != null) { 18800 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18801 pw.print(","); 18802 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18803 UserHandle.USER_SYSTEM)); 18804 } 18805 } 18806 18807 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18808 packageName == null) { 18809 if (mIntentFilterVerifierComponent != null) { 18810 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18811 if (!checkin) { 18812 if (dumpState.onTitlePrinted()) 18813 pw.println(); 18814 pw.println("Intent Filter Verifier:"); 18815 pw.print(" Using: "); 18816 pw.print(verifierPackageName); 18817 pw.print(" (uid="); 18818 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18819 UserHandle.USER_SYSTEM)); 18820 pw.println(")"); 18821 } else if (verifierPackageName != null) { 18822 pw.print("ifv,"); pw.print(verifierPackageName); 18823 pw.print(","); 18824 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18825 UserHandle.USER_SYSTEM)); 18826 } 18827 } else { 18828 pw.println(); 18829 pw.println("No Intent Filter Verifier available!"); 18830 } 18831 } 18832 18833 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18834 boolean printedHeader = false; 18835 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18836 while (it.hasNext()) { 18837 String name = it.next(); 18838 SharedLibraryEntry ent = mSharedLibraries.get(name); 18839 if (!checkin) { 18840 if (!printedHeader) { 18841 if (dumpState.onTitlePrinted()) 18842 pw.println(); 18843 pw.println("Libraries:"); 18844 printedHeader = true; 18845 } 18846 pw.print(" "); 18847 } else { 18848 pw.print("lib,"); 18849 } 18850 pw.print(name); 18851 if (!checkin) { 18852 pw.print(" -> "); 18853 } 18854 if (ent.path != null) { 18855 if (!checkin) { 18856 pw.print("(jar) "); 18857 pw.print(ent.path); 18858 } else { 18859 pw.print(",jar,"); 18860 pw.print(ent.path); 18861 } 18862 } else { 18863 if (!checkin) { 18864 pw.print("(apk) "); 18865 pw.print(ent.apk); 18866 } else { 18867 pw.print(",apk,"); 18868 pw.print(ent.apk); 18869 } 18870 } 18871 pw.println(); 18872 } 18873 } 18874 18875 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18876 if (dumpState.onTitlePrinted()) 18877 pw.println(); 18878 if (!checkin) { 18879 pw.println("Features:"); 18880 } 18881 18882 for (FeatureInfo feat : mAvailableFeatures.values()) { 18883 if (checkin) { 18884 pw.print("feat,"); 18885 pw.print(feat.name); 18886 pw.print(","); 18887 pw.println(feat.version); 18888 } else { 18889 pw.print(" "); 18890 pw.print(feat.name); 18891 if (feat.version > 0) { 18892 pw.print(" version="); 18893 pw.print(feat.version); 18894 } 18895 pw.println(); 18896 } 18897 } 18898 } 18899 18900 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18901 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18902 : "Activity Resolver Table:", " ", packageName, 18903 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18904 dumpState.setTitlePrinted(true); 18905 } 18906 } 18907 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18908 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18909 : "Receiver Resolver Table:", " ", packageName, 18910 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18911 dumpState.setTitlePrinted(true); 18912 } 18913 } 18914 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18915 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18916 : "Service Resolver Table:", " ", packageName, 18917 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18918 dumpState.setTitlePrinted(true); 18919 } 18920 } 18921 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18922 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18923 : "Provider Resolver Table:", " ", packageName, 18924 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18925 dumpState.setTitlePrinted(true); 18926 } 18927 } 18928 18929 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18930 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18931 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18932 int user = mSettings.mPreferredActivities.keyAt(i); 18933 if (pir.dump(pw, 18934 dumpState.getTitlePrinted() 18935 ? "\nPreferred Activities User " + user + ":" 18936 : "Preferred Activities User " + user + ":", " ", 18937 packageName, true, false)) { 18938 dumpState.setTitlePrinted(true); 18939 } 18940 } 18941 } 18942 18943 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18944 pw.flush(); 18945 FileOutputStream fout = new FileOutputStream(fd); 18946 BufferedOutputStream str = new BufferedOutputStream(fout); 18947 XmlSerializer serializer = new FastXmlSerializer(); 18948 try { 18949 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18950 serializer.startDocument(null, true); 18951 serializer.setFeature( 18952 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18953 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18954 serializer.endDocument(); 18955 serializer.flush(); 18956 } catch (IllegalArgumentException e) { 18957 pw.println("Failed writing: " + e); 18958 } catch (IllegalStateException e) { 18959 pw.println("Failed writing: " + e); 18960 } catch (IOException e) { 18961 pw.println("Failed writing: " + e); 18962 } 18963 } 18964 18965 if (!checkin 18966 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18967 && packageName == null) { 18968 pw.println(); 18969 int count = mSettings.mPackages.size(); 18970 if (count == 0) { 18971 pw.println("No applications!"); 18972 pw.println(); 18973 } else { 18974 final String prefix = " "; 18975 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18976 if (allPackageSettings.size() == 0) { 18977 pw.println("No domain preferred apps!"); 18978 pw.println(); 18979 } else { 18980 pw.println("App verification status:"); 18981 pw.println(); 18982 count = 0; 18983 for (PackageSetting ps : allPackageSettings) { 18984 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18985 if (ivi == null || ivi.getPackageName() == null) continue; 18986 pw.println(prefix + "Package: " + ivi.getPackageName()); 18987 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18988 pw.println(prefix + "Status: " + ivi.getStatusString()); 18989 pw.println(); 18990 count++; 18991 } 18992 if (count == 0) { 18993 pw.println(prefix + "No app verification established."); 18994 pw.println(); 18995 } 18996 for (int userId : sUserManager.getUserIds()) { 18997 pw.println("App linkages for user " + userId + ":"); 18998 pw.println(); 18999 count = 0; 19000 for (PackageSetting ps : allPackageSettings) { 19001 final long status = ps.getDomainVerificationStatusForUser(userId); 19002 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 19003 continue; 19004 } 19005 pw.println(prefix + "Package: " + ps.name); 19006 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 19007 String statusStr = IntentFilterVerificationInfo. 19008 getStatusStringFromValue(status); 19009 pw.println(prefix + "Status: " + statusStr); 19010 pw.println(); 19011 count++; 19012 } 19013 if (count == 0) { 19014 pw.println(prefix + "No configured app linkages."); 19015 pw.println(); 19016 } 19017 } 19018 } 19019 } 19020 } 19021 19022 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 19023 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 19024 if (packageName == null && permissionNames == null) { 19025 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 19026 if (iperm == 0) { 19027 if (dumpState.onTitlePrinted()) 19028 pw.println(); 19029 pw.println("AppOp Permissions:"); 19030 } 19031 pw.print(" AppOp Permission "); 19032 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 19033 pw.println(":"); 19034 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 19035 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 19036 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 19037 } 19038 } 19039 } 19040 } 19041 19042 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 19043 boolean printedSomething = false; 19044 for (PackageParser.Provider p : mProviders.mProviders.values()) { 19045 if (packageName != null && !packageName.equals(p.info.packageName)) { 19046 continue; 19047 } 19048 if (!printedSomething) { 19049 if (dumpState.onTitlePrinted()) 19050 pw.println(); 19051 pw.println("Registered ContentProviders:"); 19052 printedSomething = true; 19053 } 19054 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 19055 pw.print(" "); pw.println(p.toString()); 19056 } 19057 printedSomething = false; 19058 for (Map.Entry<String, PackageParser.Provider> entry : 19059 mProvidersByAuthority.entrySet()) { 19060 PackageParser.Provider p = entry.getValue(); 19061 if (packageName != null && !packageName.equals(p.info.packageName)) { 19062 continue; 19063 } 19064 if (!printedSomething) { 19065 if (dumpState.onTitlePrinted()) 19066 pw.println(); 19067 pw.println("ContentProvider Authorities:"); 19068 printedSomething = true; 19069 } 19070 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 19071 pw.print(" "); pw.println(p.toString()); 19072 if (p.info != null && p.info.applicationInfo != null) { 19073 final String appInfo = p.info.applicationInfo.toString(); 19074 pw.print(" applicationInfo="); pw.println(appInfo); 19075 } 19076 } 19077 } 19078 19079 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 19080 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 19081 } 19082 19083 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 19084 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 19085 } 19086 19087 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 19088 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 19089 } 19090 19091 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 19092 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 19093 } 19094 19095 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 19096 // XXX should handle packageName != null by dumping only install data that 19097 // the given package is involved with. 19098 if (dumpState.onTitlePrinted()) pw.println(); 19099 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 19100 } 19101 19102 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 19103 // XXX should handle packageName != null by dumping only install data that 19104 // the given package is involved with. 19105 if (dumpState.onTitlePrinted()) pw.println(); 19106 19107 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19108 ipw.println(); 19109 ipw.println("Frozen packages:"); 19110 ipw.increaseIndent(); 19111 if (mFrozenPackages.size() == 0) { 19112 ipw.println("(none)"); 19113 } else { 19114 for (int i = 0; i < mFrozenPackages.size(); i++) { 19115 ipw.println(mFrozenPackages.valueAt(i)); 19116 } 19117 } 19118 ipw.decreaseIndent(); 19119 } 19120 19121 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 19122 if (dumpState.onTitlePrinted()) pw.println(); 19123 dumpDexoptStateLPr(pw, packageName); 19124 } 19125 19126 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 19127 if (dumpState.onTitlePrinted()) pw.println(); 19128 dumpCompilerStatsLPr(pw, packageName); 19129 } 19130 19131 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 19132 if (dumpState.onTitlePrinted()) pw.println(); 19133 mSettings.dumpReadMessagesLPr(pw, dumpState); 19134 19135 pw.println(); 19136 pw.println("Package warning messages:"); 19137 BufferedReader in = null; 19138 String line = null; 19139 try { 19140 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19141 while ((line = in.readLine()) != null) { 19142 if (line.contains("ignored: updated version")) continue; 19143 pw.println(line); 19144 } 19145 } catch (IOException ignored) { 19146 } finally { 19147 IoUtils.closeQuietly(in); 19148 } 19149 } 19150 19151 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 19152 BufferedReader in = null; 19153 String line = null; 19154 try { 19155 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19156 while ((line = in.readLine()) != null) { 19157 if (line.contains("ignored: updated version")) continue; 19158 pw.print("msg,"); 19159 pw.println(line); 19160 } 19161 } catch (IOException ignored) { 19162 } finally { 19163 IoUtils.closeQuietly(in); 19164 } 19165 } 19166 } 19167 } 19168 19169 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 19170 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19171 ipw.println(); 19172 ipw.println("Dexopt state:"); 19173 ipw.increaseIndent(); 19174 Collection<PackageParser.Package> packages = null; 19175 if (packageName != null) { 19176 PackageParser.Package targetPackage = mPackages.get(packageName); 19177 if (targetPackage != null) { 19178 packages = Collections.singletonList(targetPackage); 19179 } else { 19180 ipw.println("Unable to find package: " + packageName); 19181 return; 19182 } 19183 } else { 19184 packages = mPackages.values(); 19185 } 19186 19187 for (PackageParser.Package pkg : packages) { 19188 ipw.println("[" + pkg.packageName + "]"); 19189 ipw.increaseIndent(); 19190 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 19191 ipw.decreaseIndent(); 19192 } 19193 } 19194 19195 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 19196 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19197 ipw.println(); 19198 ipw.println("Compiler stats:"); 19199 ipw.increaseIndent(); 19200 Collection<PackageParser.Package> packages = null; 19201 if (packageName != null) { 19202 PackageParser.Package targetPackage = mPackages.get(packageName); 19203 if (targetPackage != null) { 19204 packages = Collections.singletonList(targetPackage); 19205 } else { 19206 ipw.println("Unable to find package: " + packageName); 19207 return; 19208 } 19209 } else { 19210 packages = mPackages.values(); 19211 } 19212 19213 for (PackageParser.Package pkg : packages) { 19214 ipw.println("[" + pkg.packageName + "]"); 19215 ipw.increaseIndent(); 19216 19217 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 19218 if (stats == null) { 19219 ipw.println("(No recorded stats)"); 19220 } else { 19221 stats.dump(ipw); 19222 } 19223 ipw.decreaseIndent(); 19224 } 19225 } 19226 19227 private String dumpDomainString(String packageName) { 19228 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 19229 .getList(); 19230 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 19231 19232 ArraySet<String> result = new ArraySet<>(); 19233 if (iviList.size() > 0) { 19234 for (IntentFilterVerificationInfo ivi : iviList) { 19235 for (String host : ivi.getDomains()) { 19236 result.add(host); 19237 } 19238 } 19239 } 19240 if (filters != null && filters.size() > 0) { 19241 for (IntentFilter filter : filters) { 19242 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 19243 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19244 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19245 result.addAll(filter.getHostsList()); 19246 } 19247 } 19248 } 19249 19250 StringBuilder sb = new StringBuilder(result.size() * 16); 19251 for (String domain : result) { 19252 if (sb.length() > 0) sb.append(" "); 19253 sb.append(domain); 19254 } 19255 return sb.toString(); 19256 } 19257 19258 // ------- apps on sdcard specific code ------- 19259 static final boolean DEBUG_SD_INSTALL = false; 19260 19261 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19262 19263 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19264 19265 private boolean mMediaMounted = false; 19266 19267 static String getEncryptKey() { 19268 try { 19269 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19270 SD_ENCRYPTION_KEYSTORE_NAME); 19271 if (sdEncKey == null) { 19272 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19273 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19274 if (sdEncKey == null) { 19275 Slog.e(TAG, "Failed to create encryption keys"); 19276 return null; 19277 } 19278 } 19279 return sdEncKey; 19280 } catch (NoSuchAlgorithmException nsae) { 19281 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19282 return null; 19283 } catch (IOException ioe) { 19284 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19285 return null; 19286 } 19287 } 19288 19289 /* 19290 * Update media status on PackageManager. 19291 */ 19292 @Override 19293 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19294 int callingUid = Binder.getCallingUid(); 19295 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19296 throw new SecurityException("Media status can only be updated by the system"); 19297 } 19298 // reader; this apparently protects mMediaMounted, but should probably 19299 // be a different lock in that case. 19300 synchronized (mPackages) { 19301 Log.i(TAG, "Updating external media status from " 19302 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19303 + (mediaStatus ? "mounted" : "unmounted")); 19304 if (DEBUG_SD_INSTALL) 19305 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19306 + ", mMediaMounted=" + mMediaMounted); 19307 if (mediaStatus == mMediaMounted) { 19308 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19309 : 0, -1); 19310 mHandler.sendMessage(msg); 19311 return; 19312 } 19313 mMediaMounted = mediaStatus; 19314 } 19315 // Queue up an async operation since the package installation may take a 19316 // little while. 19317 mHandler.post(new Runnable() { 19318 public void run() { 19319 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19320 } 19321 }); 19322 } 19323 19324 /** 19325 * Called by StorageManagerService when the initial ASECs to scan are available. 19326 * Should block until all the ASEC containers are finished being scanned. 19327 */ 19328 public void scanAvailableAsecs() { 19329 updateExternalMediaStatusInner(true, false, false); 19330 } 19331 19332 /* 19333 * Collect information of applications on external media, map them against 19334 * existing containers and update information based on current mount status. 19335 * Please note that we always have to report status if reportStatus has been 19336 * set to true especially when unloading packages. 19337 */ 19338 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19339 boolean externalStorage) { 19340 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19341 int[] uidArr = EmptyArray.INT; 19342 19343 final String[] list = PackageHelper.getSecureContainerList(); 19344 if (ArrayUtils.isEmpty(list)) { 19345 Log.i(TAG, "No secure containers found"); 19346 } else { 19347 // Process list of secure containers and categorize them 19348 // as active or stale based on their package internal state. 19349 19350 // reader 19351 synchronized (mPackages) { 19352 for (String cid : list) { 19353 // Leave stages untouched for now; installer service owns them 19354 if (PackageInstallerService.isStageName(cid)) continue; 19355 19356 if (DEBUG_SD_INSTALL) 19357 Log.i(TAG, "Processing container " + cid); 19358 String pkgName = getAsecPackageName(cid); 19359 if (pkgName == null) { 19360 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19361 continue; 19362 } 19363 if (DEBUG_SD_INSTALL) 19364 Log.i(TAG, "Looking for pkg : " + pkgName); 19365 19366 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19367 if (ps == null) { 19368 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19369 continue; 19370 } 19371 19372 /* 19373 * Skip packages that are not external if we're unmounting 19374 * external storage. 19375 */ 19376 if (externalStorage && !isMounted && !isExternal(ps)) { 19377 continue; 19378 } 19379 19380 final AsecInstallArgs args = new AsecInstallArgs(cid, 19381 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19382 // The package status is changed only if the code path 19383 // matches between settings and the container id. 19384 if (ps.codePathString != null 19385 && ps.codePathString.startsWith(args.getCodePath())) { 19386 if (DEBUG_SD_INSTALL) { 19387 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19388 + " at code path: " + ps.codePathString); 19389 } 19390 19391 // We do have a valid package installed on sdcard 19392 processCids.put(args, ps.codePathString); 19393 final int uid = ps.appId; 19394 if (uid != -1) { 19395 uidArr = ArrayUtils.appendInt(uidArr, uid); 19396 } 19397 } else { 19398 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19399 + ps.codePathString); 19400 } 19401 } 19402 } 19403 19404 Arrays.sort(uidArr); 19405 } 19406 19407 // Process packages with valid entries. 19408 if (isMounted) { 19409 if (DEBUG_SD_INSTALL) 19410 Log.i(TAG, "Loading packages"); 19411 loadMediaPackages(processCids, uidArr, externalStorage); 19412 startCleaningPackages(); 19413 mInstallerService.onSecureContainersAvailable(); 19414 } else { 19415 if (DEBUG_SD_INSTALL) 19416 Log.i(TAG, "Unloading packages"); 19417 unloadMediaPackages(processCids, uidArr, reportStatus); 19418 } 19419 } 19420 19421 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19422 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19423 final int size = infos.size(); 19424 final String[] packageNames = new String[size]; 19425 final int[] packageUids = new int[size]; 19426 for (int i = 0; i < size; i++) { 19427 final ApplicationInfo info = infos.get(i); 19428 packageNames[i] = info.packageName; 19429 packageUids[i] = info.uid; 19430 } 19431 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19432 finishedReceiver); 19433 } 19434 19435 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19436 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19437 sendResourcesChangedBroadcast(mediaStatus, replacing, 19438 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19439 } 19440 19441 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19442 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19443 int size = pkgList.length; 19444 if (size > 0) { 19445 // Send broadcasts here 19446 Bundle extras = new Bundle(); 19447 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19448 if (uidArr != null) { 19449 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19450 } 19451 if (replacing) { 19452 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19453 } 19454 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19455 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19456 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19457 } 19458 } 19459 19460 /* 19461 * Look at potentially valid container ids from processCids If package 19462 * information doesn't match the one on record or package scanning fails, 19463 * the cid is added to list of removeCids. We currently don't delete stale 19464 * containers. 19465 */ 19466 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19467 boolean externalStorage) { 19468 ArrayList<String> pkgList = new ArrayList<String>(); 19469 Set<AsecInstallArgs> keys = processCids.keySet(); 19470 19471 for (AsecInstallArgs args : keys) { 19472 String codePath = processCids.get(args); 19473 if (DEBUG_SD_INSTALL) 19474 Log.i(TAG, "Loading container : " + args.cid); 19475 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19476 try { 19477 // Make sure there are no container errors first. 19478 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19479 Slog.e(TAG, "Failed to mount cid : " + args.cid 19480 + " when installing from sdcard"); 19481 continue; 19482 } 19483 // Check code path here. 19484 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19485 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19486 + " does not match one in settings " + codePath); 19487 continue; 19488 } 19489 // Parse package 19490 int parseFlags = mDefParseFlags; 19491 if (args.isExternalAsec()) { 19492 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19493 } 19494 if (args.isFwdLocked()) { 19495 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19496 } 19497 19498 synchronized (mInstallLock) { 19499 PackageParser.Package pkg = null; 19500 try { 19501 // Sadly we don't know the package name yet to freeze it 19502 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19503 SCAN_IGNORE_FROZEN, 0, null); 19504 } catch (PackageManagerException e) { 19505 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19506 } 19507 // Scan the package 19508 if (pkg != null) { 19509 /* 19510 * TODO why is the lock being held? doPostInstall is 19511 * called in other places without the lock. This needs 19512 * to be straightened out. 19513 */ 19514 // writer 19515 synchronized (mPackages) { 19516 retCode = PackageManager.INSTALL_SUCCEEDED; 19517 pkgList.add(pkg.packageName); 19518 // Post process args 19519 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19520 pkg.applicationInfo.uid); 19521 } 19522 } else { 19523 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19524 } 19525 } 19526 19527 } finally { 19528 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19529 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19530 } 19531 } 19532 } 19533 // writer 19534 synchronized (mPackages) { 19535 // If the platform SDK has changed since the last time we booted, 19536 // we need to re-grant app permission to catch any new ones that 19537 // appear. This is really a hack, and means that apps can in some 19538 // cases get permissions that the user didn't initially explicitly 19539 // allow... it would be nice to have some better way to handle 19540 // this situation. 19541 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19542 : mSettings.getInternalVersion(); 19543 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19544 : StorageManager.UUID_PRIVATE_INTERNAL; 19545 19546 int updateFlags = UPDATE_PERMISSIONS_ALL; 19547 if (ver.sdkVersion != mSdkVersion) { 19548 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19549 + mSdkVersion + "; regranting permissions for external"); 19550 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19551 } 19552 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19553 19554 // Yay, everything is now upgraded 19555 ver.forceCurrent(); 19556 19557 // can downgrade to reader 19558 // Persist settings 19559 mSettings.writeLPr(); 19560 } 19561 // Send a broadcast to let everyone know we are done processing 19562 if (pkgList.size() > 0) { 19563 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19564 } 19565 } 19566 19567 /* 19568 * Utility method to unload a list of specified containers 19569 */ 19570 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19571 // Just unmount all valid containers. 19572 for (AsecInstallArgs arg : cidArgs) { 19573 synchronized (mInstallLock) { 19574 arg.doPostDeleteLI(false); 19575 } 19576 } 19577 } 19578 19579 /* 19580 * Unload packages mounted on external media. This involves deleting package 19581 * data from internal structures, sending broadcasts about disabled packages, 19582 * gc'ing to free up references, unmounting all secure containers 19583 * corresponding to packages on external media, and posting a 19584 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19585 * that we always have to post this message if status has been requested no 19586 * matter what. 19587 */ 19588 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19589 final boolean reportStatus) { 19590 if (DEBUG_SD_INSTALL) 19591 Log.i(TAG, "unloading media packages"); 19592 ArrayList<String> pkgList = new ArrayList<String>(); 19593 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19594 final Set<AsecInstallArgs> keys = processCids.keySet(); 19595 for (AsecInstallArgs args : keys) { 19596 String pkgName = args.getPackageName(); 19597 if (DEBUG_SD_INSTALL) 19598 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19599 // Delete package internally 19600 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19601 synchronized (mInstallLock) { 19602 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19603 final boolean res; 19604 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19605 "unloadMediaPackages")) { 19606 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19607 null); 19608 } 19609 if (res) { 19610 pkgList.add(pkgName); 19611 } else { 19612 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19613 failedList.add(args); 19614 } 19615 } 19616 } 19617 19618 // reader 19619 synchronized (mPackages) { 19620 // We didn't update the settings after removing each package; 19621 // write them now for all packages. 19622 mSettings.writeLPr(); 19623 } 19624 19625 // We have to absolutely send UPDATED_MEDIA_STATUS only 19626 // after confirming that all the receivers processed the ordered 19627 // broadcast when packages get disabled, force a gc to clean things up. 19628 // and unload all the containers. 19629 if (pkgList.size() > 0) { 19630 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19631 new IIntentReceiver.Stub() { 19632 public void performReceive(Intent intent, int resultCode, String data, 19633 Bundle extras, boolean ordered, boolean sticky, 19634 int sendingUser) throws RemoteException { 19635 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19636 reportStatus ? 1 : 0, 1, keys); 19637 mHandler.sendMessage(msg); 19638 } 19639 }); 19640 } else { 19641 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19642 keys); 19643 mHandler.sendMessage(msg); 19644 } 19645 } 19646 19647 private void loadPrivatePackages(final VolumeInfo vol) { 19648 mHandler.post(new Runnable() { 19649 @Override 19650 public void run() { 19651 loadPrivatePackagesInner(vol); 19652 } 19653 }); 19654 } 19655 19656 private void loadPrivatePackagesInner(VolumeInfo vol) { 19657 final String volumeUuid = vol.fsUuid; 19658 if (TextUtils.isEmpty(volumeUuid)) { 19659 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19660 return; 19661 } 19662 19663 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19664 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19665 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19666 19667 final VersionInfo ver; 19668 final List<PackageSetting> packages; 19669 synchronized (mPackages) { 19670 ver = mSettings.findOrCreateVersion(volumeUuid); 19671 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19672 } 19673 19674 for (PackageSetting ps : packages) { 19675 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19676 synchronized (mInstallLock) { 19677 final PackageParser.Package pkg; 19678 try { 19679 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19680 loaded.add(pkg.applicationInfo); 19681 19682 } catch (PackageManagerException e) { 19683 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19684 } 19685 19686 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19687 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19688 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19689 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19690 } 19691 } 19692 } 19693 19694 // Reconcile app data for all started/unlocked users 19695 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19696 final UserManager um = mContext.getSystemService(UserManager.class); 19697 UserManagerInternal umInternal = getUserManagerInternal(); 19698 for (UserInfo user : um.getUsers()) { 19699 final int flags; 19700 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19701 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19702 } else if (umInternal.isUserRunning(user.id)) { 19703 flags = StorageManager.FLAG_STORAGE_DE; 19704 } else { 19705 continue; 19706 } 19707 19708 try { 19709 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19710 synchronized (mInstallLock) { 19711 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 19712 } 19713 } catch (IllegalStateException e) { 19714 // Device was probably ejected, and we'll process that event momentarily 19715 Slog.w(TAG, "Failed to prepare storage: " + e); 19716 } 19717 } 19718 19719 synchronized (mPackages) { 19720 int updateFlags = UPDATE_PERMISSIONS_ALL; 19721 if (ver.sdkVersion != mSdkVersion) { 19722 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19723 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19724 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19725 } 19726 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19727 19728 // Yay, everything is now upgraded 19729 ver.forceCurrent(); 19730 19731 mSettings.writeLPr(); 19732 } 19733 19734 for (PackageFreezer freezer : freezers) { 19735 freezer.close(); 19736 } 19737 19738 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19739 sendResourcesChangedBroadcast(true, false, loaded, null); 19740 } 19741 19742 private void unloadPrivatePackages(final VolumeInfo vol) { 19743 mHandler.post(new Runnable() { 19744 @Override 19745 public void run() { 19746 unloadPrivatePackagesInner(vol); 19747 } 19748 }); 19749 } 19750 19751 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19752 final String volumeUuid = vol.fsUuid; 19753 if (TextUtils.isEmpty(volumeUuid)) { 19754 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19755 return; 19756 } 19757 19758 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19759 synchronized (mInstallLock) { 19760 synchronized (mPackages) { 19761 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19762 for (PackageSetting ps : packages) { 19763 if (ps.pkg == null) continue; 19764 19765 final ApplicationInfo info = ps.pkg.applicationInfo; 19766 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19767 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19768 19769 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19770 "unloadPrivatePackagesInner")) { 19771 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19772 false, null)) { 19773 unloaded.add(info); 19774 } else { 19775 Slog.w(TAG, "Failed to unload " + ps.codePath); 19776 } 19777 } 19778 19779 // Try very hard to release any references to this package 19780 // so we don't risk the system server being killed due to 19781 // open FDs 19782 AttributeCache.instance().removePackage(ps.name); 19783 } 19784 19785 mSettings.writeLPr(); 19786 } 19787 } 19788 19789 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19790 sendResourcesChangedBroadcast(false, false, unloaded, null); 19791 19792 // Try very hard to release any references to this path so we don't risk 19793 // the system server being killed due to open FDs 19794 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19795 19796 for (int i = 0; i < 3; i++) { 19797 System.gc(); 19798 System.runFinalization(); 19799 } 19800 } 19801 19802 /** 19803 * Prepare storage areas for given user on all mounted devices. 19804 */ 19805 void prepareUserData(int userId, int userSerial, int flags) { 19806 synchronized (mInstallLock) { 19807 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19808 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19809 final String volumeUuid = vol.getFsUuid(); 19810 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19811 } 19812 } 19813 } 19814 19815 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19816 boolean allowRecover) { 19817 // Prepare storage and verify that serial numbers are consistent; if 19818 // there's a mismatch we need to destroy to avoid leaking data 19819 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19820 try { 19821 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19822 19823 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19824 UserManagerService.enforceSerialNumber( 19825 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19826 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19827 UserManagerService.enforceSerialNumber( 19828 Environment.getDataSystemDeDirectory(userId), userSerial); 19829 } 19830 } 19831 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19832 UserManagerService.enforceSerialNumber( 19833 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19834 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19835 UserManagerService.enforceSerialNumber( 19836 Environment.getDataSystemCeDirectory(userId), userSerial); 19837 } 19838 } 19839 19840 synchronized (mInstallLock) { 19841 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19842 } 19843 } catch (Exception e) { 19844 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19845 + " because we failed to prepare: " + e); 19846 destroyUserDataLI(volumeUuid, userId, 19847 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19848 19849 if (allowRecover) { 19850 // Try one last time; if we fail again we're really in trouble 19851 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19852 } 19853 } 19854 } 19855 19856 /** 19857 * Destroy storage areas for given user on all mounted devices. 19858 */ 19859 void destroyUserData(int userId, int flags) { 19860 synchronized (mInstallLock) { 19861 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19862 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19863 final String volumeUuid = vol.getFsUuid(); 19864 destroyUserDataLI(volumeUuid, userId, flags); 19865 } 19866 } 19867 } 19868 19869 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19870 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19871 try { 19872 // Clean up app data, profile data, and media data 19873 mInstaller.destroyUserData(volumeUuid, userId, flags); 19874 19875 // Clean up system data 19876 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19877 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19878 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19879 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19880 } 19881 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19882 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19883 } 19884 } 19885 19886 // Data with special labels is now gone, so finish the job 19887 storage.destroyUserStorage(volumeUuid, userId, flags); 19888 19889 } catch (Exception e) { 19890 logCriticalInfo(Log.WARN, 19891 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19892 } 19893 } 19894 19895 /** 19896 * Examine all users present on given mounted volume, and destroy data 19897 * belonging to users that are no longer valid, or whose user ID has been 19898 * recycled. 19899 */ 19900 private void reconcileUsers(String volumeUuid) { 19901 final List<File> files = new ArrayList<>(); 19902 Collections.addAll(files, FileUtils 19903 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19904 Collections.addAll(files, FileUtils 19905 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19906 Collections.addAll(files, FileUtils 19907 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19908 Collections.addAll(files, FileUtils 19909 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19910 for (File file : files) { 19911 if (!file.isDirectory()) continue; 19912 19913 final int userId; 19914 final UserInfo info; 19915 try { 19916 userId = Integer.parseInt(file.getName()); 19917 info = sUserManager.getUserInfo(userId); 19918 } catch (NumberFormatException e) { 19919 Slog.w(TAG, "Invalid user directory " + file); 19920 continue; 19921 } 19922 19923 boolean destroyUser = false; 19924 if (info == null) { 19925 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19926 + " because no matching user was found"); 19927 destroyUser = true; 19928 } else if (!mOnlyCore) { 19929 try { 19930 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19931 } catch (IOException e) { 19932 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19933 + " because we failed to enforce serial number: " + e); 19934 destroyUser = true; 19935 } 19936 } 19937 19938 if (destroyUser) { 19939 synchronized (mInstallLock) { 19940 destroyUserDataLI(volumeUuid, userId, 19941 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19942 } 19943 } 19944 } 19945 } 19946 19947 private void assertPackageKnown(String volumeUuid, String packageName) 19948 throws PackageManagerException { 19949 synchronized (mPackages) { 19950 final PackageSetting ps = mSettings.mPackages.get(packageName); 19951 if (ps == null) { 19952 throw new PackageManagerException("Package " + packageName + " is unknown"); 19953 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19954 throw new PackageManagerException( 19955 "Package " + packageName + " found on unknown volume " + volumeUuid 19956 + "; expected volume " + ps.volumeUuid); 19957 } 19958 } 19959 } 19960 19961 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19962 throws PackageManagerException { 19963 synchronized (mPackages) { 19964 final PackageSetting ps = mSettings.mPackages.get(packageName); 19965 if (ps == null) { 19966 throw new PackageManagerException("Package " + packageName + " is unknown"); 19967 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19968 throw new PackageManagerException( 19969 "Package " + packageName + " found on unknown volume " + volumeUuid 19970 + "; expected volume " + ps.volumeUuid); 19971 } else if (!ps.getInstalled(userId)) { 19972 throw new PackageManagerException( 19973 "Package " + packageName + " not installed for user " + userId); 19974 } 19975 } 19976 } 19977 19978 /** 19979 * Examine all apps present on given mounted volume, and destroy apps that 19980 * aren't expected, either due to uninstallation or reinstallation on 19981 * another volume. 19982 */ 19983 private void reconcileApps(String volumeUuid) { 19984 final File[] files = FileUtils 19985 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19986 for (File file : files) { 19987 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19988 && !PackageInstallerService.isStageName(file.getName()); 19989 if (!isPackage) { 19990 // Ignore entries which are not packages 19991 continue; 19992 } 19993 19994 try { 19995 final PackageLite pkg = PackageParser.parsePackageLite(file, 19996 PackageParser.PARSE_MUST_BE_APK); 19997 assertPackageKnown(volumeUuid, pkg.packageName); 19998 19999 } catch (PackageParserException | PackageManagerException e) { 20000 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20001 synchronized (mInstallLock) { 20002 removeCodePathLI(file); 20003 } 20004 } 20005 } 20006 } 20007 20008 /** 20009 * Reconcile all app data for the given user. 20010 * <p> 20011 * Verifies that directories exist and that ownership and labeling is 20012 * correct for all installed apps on all mounted volumes. 20013 */ 20014 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 20015 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20016 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20017 final String volumeUuid = vol.getFsUuid(); 20018 synchronized (mInstallLock) { 20019 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 20020 } 20021 } 20022 } 20023 20024 /** 20025 * Reconcile all app data on given mounted volume. 20026 * <p> 20027 * Destroys app data that isn't expected, either due to uninstallation or 20028 * reinstallation on another volume. 20029 * <p> 20030 * Verifies that directories exist and that ownership and labeling is 20031 * correct for all installed apps. 20032 */ 20033 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 20034 boolean migrateAppData) { 20035 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 20036 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 20037 20038 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 20039 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 20040 20041 // First look for stale data that doesn't belong, and check if things 20042 // have changed since we did our last restorecon 20043 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20044 if (StorageManager.isFileEncryptedNativeOrEmulated() 20045 && !StorageManager.isUserKeyUnlocked(userId)) { 20046 throw new RuntimeException( 20047 "Yikes, someone asked us to reconcile CE storage while " + userId 20048 + " was still locked; this would have caused massive data loss!"); 20049 } 20050 20051 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 20052 for (File file : files) { 20053 final String packageName = file.getName(); 20054 try { 20055 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20056 } catch (PackageManagerException e) { 20057 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20058 try { 20059 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20060 StorageManager.FLAG_STORAGE_CE, 0); 20061 } catch (InstallerException e2) { 20062 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20063 } 20064 } 20065 } 20066 } 20067 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20068 final File[] files = FileUtils.listFilesOrEmpty(deDir); 20069 for (File file : files) { 20070 final String packageName = file.getName(); 20071 try { 20072 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20073 } catch (PackageManagerException e) { 20074 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20075 try { 20076 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20077 StorageManager.FLAG_STORAGE_DE, 0); 20078 } catch (InstallerException e2) { 20079 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20080 } 20081 } 20082 } 20083 } 20084 20085 // Ensure that data directories are ready to roll for all packages 20086 // installed for this volume and user 20087 final List<PackageSetting> packages; 20088 synchronized (mPackages) { 20089 packages = mSettings.getVolumePackagesLPr(volumeUuid); 20090 } 20091 int preparedCount = 0; 20092 for (PackageSetting ps : packages) { 20093 final String packageName = ps.name; 20094 if (ps.pkg == null) { 20095 Slog.w(TAG, "Odd, missing scanned package " + packageName); 20096 // TODO: might be due to legacy ASEC apps; we should circle back 20097 // and reconcile again once they're scanned 20098 continue; 20099 } 20100 20101 if (ps.getInstalled(userId)) { 20102 prepareAppDataLIF(ps.pkg, userId, flags); 20103 20104 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 20105 // We may have just shuffled around app data directories, so 20106 // prepare them one more time 20107 prepareAppDataLIF(ps.pkg, userId, flags); 20108 } 20109 20110 preparedCount++; 20111 } 20112 } 20113 20114 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 20115 } 20116 20117 /** 20118 * Prepare app data for the given app just after it was installed or 20119 * upgraded. This method carefully only touches users that it's installed 20120 * for, and it forces a restorecon to handle any seinfo changes. 20121 * <p> 20122 * Verifies that directories exist and that ownership and labeling is 20123 * correct for all installed apps. If there is an ownership mismatch, it 20124 * will try recovering system apps by wiping data; third-party app data is 20125 * left intact. 20126 * <p> 20127 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 20128 */ 20129 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 20130 final PackageSetting ps; 20131 synchronized (mPackages) { 20132 ps = mSettings.mPackages.get(pkg.packageName); 20133 mSettings.writeKernelMappingLPr(ps); 20134 } 20135 20136 final UserManager um = mContext.getSystemService(UserManager.class); 20137 UserManagerInternal umInternal = getUserManagerInternal(); 20138 for (UserInfo user : um.getUsers()) { 20139 final int flags; 20140 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20141 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20142 } else if (umInternal.isUserRunning(user.id)) { 20143 flags = StorageManager.FLAG_STORAGE_DE; 20144 } else { 20145 continue; 20146 } 20147 20148 if (ps.getInstalled(user.id)) { 20149 // TODO: when user data is locked, mark that we're still dirty 20150 prepareAppDataLIF(pkg, user.id, flags); 20151 } 20152 } 20153 } 20154 20155 /** 20156 * Prepare app data for the given app. 20157 * <p> 20158 * Verifies that directories exist and that ownership and labeling is 20159 * correct for all installed apps. If there is an ownership mismatch, this 20160 * will try recovering system apps by wiping data; third-party app data is 20161 * left intact. 20162 */ 20163 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 20164 if (pkg == null) { 20165 Slog.wtf(TAG, "Package was null!", new Throwable()); 20166 return; 20167 } 20168 prepareAppDataLeafLIF(pkg, userId, flags); 20169 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20170 for (int i = 0; i < childCount; i++) { 20171 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 20172 } 20173 } 20174 20175 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20176 if (DEBUG_APP_DATA) { 20177 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 20178 + Integer.toHexString(flags)); 20179 } 20180 20181 final String volumeUuid = pkg.volumeUuid; 20182 final String packageName = pkg.packageName; 20183 final ApplicationInfo app = pkg.applicationInfo; 20184 final int appId = UserHandle.getAppId(app.uid); 20185 20186 Preconditions.checkNotNull(app.seinfo); 20187 20188 try { 20189 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20190 appId, app.seinfo, app.targetSdkVersion); 20191 } catch (InstallerException e) { 20192 if (app.isSystemApp()) { 20193 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 20194 + ", but trying to recover: " + e); 20195 destroyAppDataLeafLIF(pkg, userId, flags); 20196 try { 20197 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20198 appId, app.seinfo, app.targetSdkVersion); 20199 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 20200 } catch (InstallerException e2) { 20201 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 20202 } 20203 } else { 20204 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 20205 } 20206 } 20207 20208 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20209 try { 20210 // CE storage is unlocked right now, so read out the inode and 20211 // remember for use later when it's locked 20212 // TODO: mark this structure as dirty so we persist it! 20213 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 20214 StorageManager.FLAG_STORAGE_CE); 20215 synchronized (mPackages) { 20216 final PackageSetting ps = mSettings.mPackages.get(packageName); 20217 if (ps != null) { 20218 ps.setCeDataInode(ceDataInode, userId); 20219 } 20220 } 20221 } catch (InstallerException e) { 20222 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 20223 } 20224 } 20225 20226 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20227 } 20228 20229 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 20230 if (pkg == null) { 20231 Slog.wtf(TAG, "Package was null!", new Throwable()); 20232 return; 20233 } 20234 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20235 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20236 for (int i = 0; i < childCount; i++) { 20237 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 20238 } 20239 } 20240 20241 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20242 final String volumeUuid = pkg.volumeUuid; 20243 final String packageName = pkg.packageName; 20244 final ApplicationInfo app = pkg.applicationInfo; 20245 20246 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20247 // Create a native library symlink only if we have native libraries 20248 // and if the native libraries are 32 bit libraries. We do not provide 20249 // this symlink for 64 bit libraries. 20250 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20251 final String nativeLibPath = app.nativeLibraryDir; 20252 try { 20253 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20254 nativeLibPath, userId); 20255 } catch (InstallerException e) { 20256 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20257 } 20258 } 20259 } 20260 } 20261 20262 /** 20263 * For system apps on non-FBE devices, this method migrates any existing 20264 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20265 * requested by the app. 20266 */ 20267 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20268 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20269 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20270 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20271 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20272 try { 20273 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20274 storageTarget); 20275 } catch (InstallerException e) { 20276 logCriticalInfo(Log.WARN, 20277 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20278 } 20279 return true; 20280 } else { 20281 return false; 20282 } 20283 } 20284 20285 public PackageFreezer freezePackage(String packageName, String killReason) { 20286 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20287 } 20288 20289 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20290 return new PackageFreezer(packageName, userId, killReason); 20291 } 20292 20293 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20294 String killReason) { 20295 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20296 } 20297 20298 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20299 String killReason) { 20300 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20301 return new PackageFreezer(); 20302 } else { 20303 return freezePackage(packageName, userId, killReason); 20304 } 20305 } 20306 20307 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20308 String killReason) { 20309 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20310 } 20311 20312 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20313 String killReason) { 20314 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20315 return new PackageFreezer(); 20316 } else { 20317 return freezePackage(packageName, userId, killReason); 20318 } 20319 } 20320 20321 /** 20322 * Class that freezes and kills the given package upon creation, and 20323 * unfreezes it upon closing. This is typically used when doing surgery on 20324 * app code/data to prevent the app from running while you're working. 20325 */ 20326 private class PackageFreezer implements AutoCloseable { 20327 private final String mPackageName; 20328 private final PackageFreezer[] mChildren; 20329 20330 private final boolean mWeFroze; 20331 20332 private final AtomicBoolean mClosed = new AtomicBoolean(); 20333 private final CloseGuard mCloseGuard = CloseGuard.get(); 20334 20335 /** 20336 * Create and return a stub freezer that doesn't actually do anything, 20337 * typically used when someone requested 20338 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20339 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20340 */ 20341 public PackageFreezer() { 20342 mPackageName = null; 20343 mChildren = null; 20344 mWeFroze = false; 20345 mCloseGuard.open("close"); 20346 } 20347 20348 public PackageFreezer(String packageName, int userId, String killReason) { 20349 synchronized (mPackages) { 20350 mPackageName = packageName; 20351 mWeFroze = mFrozenPackages.add(mPackageName); 20352 20353 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20354 if (ps != null) { 20355 killApplication(ps.name, ps.appId, userId, killReason); 20356 } 20357 20358 final PackageParser.Package p = mPackages.get(packageName); 20359 if (p != null && p.childPackages != null) { 20360 final int N = p.childPackages.size(); 20361 mChildren = new PackageFreezer[N]; 20362 for (int i = 0; i < N; i++) { 20363 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20364 userId, killReason); 20365 } 20366 } else { 20367 mChildren = null; 20368 } 20369 } 20370 mCloseGuard.open("close"); 20371 } 20372 20373 @Override 20374 protected void finalize() throws Throwable { 20375 try { 20376 mCloseGuard.warnIfOpen(); 20377 close(); 20378 } finally { 20379 super.finalize(); 20380 } 20381 } 20382 20383 @Override 20384 public void close() { 20385 mCloseGuard.close(); 20386 if (mClosed.compareAndSet(false, true)) { 20387 synchronized (mPackages) { 20388 if (mWeFroze) { 20389 mFrozenPackages.remove(mPackageName); 20390 } 20391 20392 if (mChildren != null) { 20393 for (PackageFreezer freezer : mChildren) { 20394 freezer.close(); 20395 } 20396 } 20397 } 20398 } 20399 } 20400 } 20401 20402 /** 20403 * Verify that given package is currently frozen. 20404 */ 20405 private void checkPackageFrozen(String packageName) { 20406 synchronized (mPackages) { 20407 if (!mFrozenPackages.contains(packageName)) { 20408 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20409 } 20410 } 20411 } 20412 20413 @Override 20414 public int movePackage(final String packageName, final String volumeUuid) { 20415 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20416 20417 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20418 final int moveId = mNextMoveId.getAndIncrement(); 20419 mHandler.post(new Runnable() { 20420 @Override 20421 public void run() { 20422 try { 20423 movePackageInternal(packageName, volumeUuid, moveId, user); 20424 } catch (PackageManagerException e) { 20425 Slog.w(TAG, "Failed to move " + packageName, e); 20426 mMoveCallbacks.notifyStatusChanged(moveId, 20427 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20428 } 20429 } 20430 }); 20431 return moveId; 20432 } 20433 20434 private void movePackageInternal(final String packageName, final String volumeUuid, 20435 final int moveId, UserHandle user) throws PackageManagerException { 20436 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20437 final PackageManager pm = mContext.getPackageManager(); 20438 20439 final boolean currentAsec; 20440 final String currentVolumeUuid; 20441 final File codeFile; 20442 final String installerPackageName; 20443 final String packageAbiOverride; 20444 final int appId; 20445 final String seinfo; 20446 final String label; 20447 final int targetSdkVersion; 20448 final PackageFreezer freezer; 20449 final int[] installedUserIds; 20450 20451 // reader 20452 synchronized (mPackages) { 20453 final PackageParser.Package pkg = mPackages.get(packageName); 20454 final PackageSetting ps = mSettings.mPackages.get(packageName); 20455 if (pkg == null || ps == null) { 20456 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20457 } 20458 20459 if (pkg.applicationInfo.isSystemApp()) { 20460 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20461 "Cannot move system application"); 20462 } 20463 20464 if (pkg.applicationInfo.isExternalAsec()) { 20465 currentAsec = true; 20466 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20467 } else if (pkg.applicationInfo.isForwardLocked()) { 20468 currentAsec = true; 20469 currentVolumeUuid = "forward_locked"; 20470 } else { 20471 currentAsec = false; 20472 currentVolumeUuid = ps.volumeUuid; 20473 20474 final File probe = new File(pkg.codePath); 20475 final File probeOat = new File(probe, "oat"); 20476 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20477 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20478 "Move only supported for modern cluster style installs"); 20479 } 20480 } 20481 20482 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20483 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20484 "Package already moved to " + volumeUuid); 20485 } 20486 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20487 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20488 "Device admin cannot be moved"); 20489 } 20490 20491 if (mFrozenPackages.contains(packageName)) { 20492 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20493 "Failed to move already frozen package"); 20494 } 20495 20496 codeFile = new File(pkg.codePath); 20497 installerPackageName = ps.installerPackageName; 20498 packageAbiOverride = ps.cpuAbiOverrideString; 20499 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20500 seinfo = pkg.applicationInfo.seinfo; 20501 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20502 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20503 freezer = freezePackage(packageName, "movePackageInternal"); 20504 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20505 } 20506 20507 final Bundle extras = new Bundle(); 20508 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20509 extras.putString(Intent.EXTRA_TITLE, label); 20510 mMoveCallbacks.notifyCreated(moveId, extras); 20511 20512 int installFlags; 20513 final boolean moveCompleteApp; 20514 final File measurePath; 20515 20516 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20517 installFlags = INSTALL_INTERNAL; 20518 moveCompleteApp = !currentAsec; 20519 measurePath = Environment.getDataAppDirectory(volumeUuid); 20520 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20521 installFlags = INSTALL_EXTERNAL; 20522 moveCompleteApp = false; 20523 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20524 } else { 20525 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20526 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20527 || !volume.isMountedWritable()) { 20528 freezer.close(); 20529 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20530 "Move location not mounted private volume"); 20531 } 20532 20533 Preconditions.checkState(!currentAsec); 20534 20535 installFlags = INSTALL_INTERNAL; 20536 moveCompleteApp = true; 20537 measurePath = Environment.getDataAppDirectory(volumeUuid); 20538 } 20539 20540 final PackageStats stats = new PackageStats(null, -1); 20541 synchronized (mInstaller) { 20542 for (int userId : installedUserIds) { 20543 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20544 freezer.close(); 20545 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20546 "Failed to measure package size"); 20547 } 20548 } 20549 } 20550 20551 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20552 + stats.dataSize); 20553 20554 final long startFreeBytes = measurePath.getFreeSpace(); 20555 final long sizeBytes; 20556 if (moveCompleteApp) { 20557 sizeBytes = stats.codeSize + stats.dataSize; 20558 } else { 20559 sizeBytes = stats.codeSize; 20560 } 20561 20562 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20563 freezer.close(); 20564 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20565 "Not enough free space to move"); 20566 } 20567 20568 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20569 20570 final CountDownLatch installedLatch = new CountDownLatch(1); 20571 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20572 @Override 20573 public void onUserActionRequired(Intent intent) throws RemoteException { 20574 throw new IllegalStateException(); 20575 } 20576 20577 @Override 20578 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20579 Bundle extras) throws RemoteException { 20580 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20581 + PackageManager.installStatusToString(returnCode, msg)); 20582 20583 installedLatch.countDown(); 20584 freezer.close(); 20585 20586 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20587 switch (status) { 20588 case PackageInstaller.STATUS_SUCCESS: 20589 mMoveCallbacks.notifyStatusChanged(moveId, 20590 PackageManager.MOVE_SUCCEEDED); 20591 break; 20592 case PackageInstaller.STATUS_FAILURE_STORAGE: 20593 mMoveCallbacks.notifyStatusChanged(moveId, 20594 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20595 break; 20596 default: 20597 mMoveCallbacks.notifyStatusChanged(moveId, 20598 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20599 break; 20600 } 20601 } 20602 }; 20603 20604 final MoveInfo move; 20605 if (moveCompleteApp) { 20606 // Kick off a thread to report progress estimates 20607 new Thread() { 20608 @Override 20609 public void run() { 20610 while (true) { 20611 try { 20612 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20613 break; 20614 } 20615 } catch (InterruptedException ignored) { 20616 } 20617 20618 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20619 final int progress = 10 + (int) MathUtils.constrain( 20620 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20621 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20622 } 20623 } 20624 }.start(); 20625 20626 final String dataAppName = codeFile.getName(); 20627 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20628 dataAppName, appId, seinfo, targetSdkVersion); 20629 } else { 20630 move = null; 20631 } 20632 20633 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20634 20635 final Message msg = mHandler.obtainMessage(INIT_COPY); 20636 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20637 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20638 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20639 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20640 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20641 msg.obj = params; 20642 20643 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20644 System.identityHashCode(msg.obj)); 20645 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20646 System.identityHashCode(msg.obj)); 20647 20648 mHandler.sendMessage(msg); 20649 } 20650 20651 @Override 20652 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20653 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20654 20655 final int realMoveId = mNextMoveId.getAndIncrement(); 20656 final Bundle extras = new Bundle(); 20657 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20658 mMoveCallbacks.notifyCreated(realMoveId, extras); 20659 20660 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20661 @Override 20662 public void onCreated(int moveId, Bundle extras) { 20663 // Ignored 20664 } 20665 20666 @Override 20667 public void onStatusChanged(int moveId, int status, long estMillis) { 20668 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20669 } 20670 }; 20671 20672 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20673 storage.setPrimaryStorageUuid(volumeUuid, callback); 20674 return realMoveId; 20675 } 20676 20677 @Override 20678 public int getMoveStatus(int moveId) { 20679 mContext.enforceCallingOrSelfPermission( 20680 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20681 return mMoveCallbacks.mLastStatus.get(moveId); 20682 } 20683 20684 @Override 20685 public void registerMoveCallback(IPackageMoveObserver callback) { 20686 mContext.enforceCallingOrSelfPermission( 20687 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20688 mMoveCallbacks.register(callback); 20689 } 20690 20691 @Override 20692 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20693 mContext.enforceCallingOrSelfPermission( 20694 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20695 mMoveCallbacks.unregister(callback); 20696 } 20697 20698 @Override 20699 public boolean setInstallLocation(int loc) { 20700 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20701 null); 20702 if (getInstallLocation() == loc) { 20703 return true; 20704 } 20705 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20706 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20707 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20708 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20709 return true; 20710 } 20711 return false; 20712 } 20713 20714 @Override 20715 public int getInstallLocation() { 20716 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20717 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20718 PackageHelper.APP_INSTALL_AUTO); 20719 } 20720 20721 /** Called by UserManagerService */ 20722 void cleanUpUser(UserManagerService userManager, int userHandle) { 20723 synchronized (mPackages) { 20724 mDirtyUsers.remove(userHandle); 20725 mUserNeedsBadging.delete(userHandle); 20726 mSettings.removeUserLPw(userHandle); 20727 mPendingBroadcasts.remove(userHandle); 20728 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20729 removeUnusedPackagesLPw(userManager, userHandle); 20730 } 20731 } 20732 20733 /** 20734 * We're removing userHandle and would like to remove any downloaded packages 20735 * that are no longer in use by any other user. 20736 * @param userHandle the user being removed 20737 */ 20738 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20739 final boolean DEBUG_CLEAN_APKS = false; 20740 int [] users = userManager.getUserIds(); 20741 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20742 while (psit.hasNext()) { 20743 PackageSetting ps = psit.next(); 20744 if (ps.pkg == null) { 20745 continue; 20746 } 20747 final String packageName = ps.pkg.packageName; 20748 // Skip over if system app 20749 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20750 continue; 20751 } 20752 if (DEBUG_CLEAN_APKS) { 20753 Slog.i(TAG, "Checking package " + packageName); 20754 } 20755 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20756 if (keep) { 20757 if (DEBUG_CLEAN_APKS) { 20758 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20759 } 20760 } else { 20761 for (int i = 0; i < users.length; i++) { 20762 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20763 keep = true; 20764 if (DEBUG_CLEAN_APKS) { 20765 Slog.i(TAG, " Keeping package " + packageName + " for user " 20766 + users[i]); 20767 } 20768 break; 20769 } 20770 } 20771 } 20772 if (!keep) { 20773 if (DEBUG_CLEAN_APKS) { 20774 Slog.i(TAG, " Removing package " + packageName); 20775 } 20776 mHandler.post(new Runnable() { 20777 public void run() { 20778 deletePackageX(packageName, userHandle, 0); 20779 } //end run 20780 }); 20781 } 20782 } 20783 } 20784 20785 /** Called by UserManagerService */ 20786 void createNewUser(int userId, String[] disallowedPackages) { 20787 synchronized (mInstallLock) { 20788 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 20789 } 20790 synchronized (mPackages) { 20791 scheduleWritePackageRestrictionsLocked(userId); 20792 scheduleWritePackageListLocked(userId); 20793 applyFactoryDefaultBrowserLPw(userId); 20794 primeDomainVerificationsLPw(userId); 20795 } 20796 } 20797 20798 void onNewUserCreated(final int userId) { 20799 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20800 // If permission review for legacy apps is required, we represent 20801 // dagerous permissions for such apps as always granted runtime 20802 // permissions to keep per user flag state whether review is needed. 20803 // Hence, if a new user is added we have to propagate dangerous 20804 // permission grants for these legacy apps. 20805 if (mPermissionReviewRequired) { 20806 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20807 | UPDATE_PERMISSIONS_REPLACE_ALL); 20808 } 20809 } 20810 20811 @Override 20812 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20813 mContext.enforceCallingOrSelfPermission( 20814 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20815 "Only package verification agents can read the verifier device identity"); 20816 20817 synchronized (mPackages) { 20818 return mSettings.getVerifierDeviceIdentityLPw(); 20819 } 20820 } 20821 20822 @Override 20823 public void setPermissionEnforced(String permission, boolean enforced) { 20824 // TODO: Now that we no longer change GID for storage, this should to away. 20825 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20826 "setPermissionEnforced"); 20827 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20828 synchronized (mPackages) { 20829 if (mSettings.mReadExternalStorageEnforced == null 20830 || mSettings.mReadExternalStorageEnforced != enforced) { 20831 mSettings.mReadExternalStorageEnforced = enforced; 20832 mSettings.writeLPr(); 20833 } 20834 } 20835 // kill any non-foreground processes so we restart them and 20836 // grant/revoke the GID. 20837 final IActivityManager am = ActivityManager.getService(); 20838 if (am != null) { 20839 final long token = Binder.clearCallingIdentity(); 20840 try { 20841 am.killProcessesBelowForeground("setPermissionEnforcement"); 20842 } catch (RemoteException e) { 20843 } finally { 20844 Binder.restoreCallingIdentity(token); 20845 } 20846 } 20847 } else { 20848 throw new IllegalArgumentException("No selective enforcement for " + permission); 20849 } 20850 } 20851 20852 @Override 20853 @Deprecated 20854 public boolean isPermissionEnforced(String permission) { 20855 return true; 20856 } 20857 20858 @Override 20859 public boolean isStorageLow() { 20860 final long token = Binder.clearCallingIdentity(); 20861 try { 20862 final DeviceStorageMonitorInternal 20863 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20864 if (dsm != null) { 20865 return dsm.isMemoryLow(); 20866 } else { 20867 return false; 20868 } 20869 } finally { 20870 Binder.restoreCallingIdentity(token); 20871 } 20872 } 20873 20874 @Override 20875 public IPackageInstaller getPackageInstaller() { 20876 return mInstallerService; 20877 } 20878 20879 private boolean userNeedsBadging(int userId) { 20880 int index = mUserNeedsBadging.indexOfKey(userId); 20881 if (index < 0) { 20882 final UserInfo userInfo; 20883 final long token = Binder.clearCallingIdentity(); 20884 try { 20885 userInfo = sUserManager.getUserInfo(userId); 20886 } finally { 20887 Binder.restoreCallingIdentity(token); 20888 } 20889 final boolean b; 20890 if (userInfo != null && userInfo.isManagedProfile()) { 20891 b = true; 20892 } else { 20893 b = false; 20894 } 20895 mUserNeedsBadging.put(userId, b); 20896 return b; 20897 } 20898 return mUserNeedsBadging.valueAt(index); 20899 } 20900 20901 @Override 20902 public KeySet getKeySetByAlias(String packageName, String alias) { 20903 if (packageName == null || alias == null) { 20904 return null; 20905 } 20906 synchronized(mPackages) { 20907 final PackageParser.Package pkg = mPackages.get(packageName); 20908 if (pkg == null) { 20909 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20910 throw new IllegalArgumentException("Unknown package: " + packageName); 20911 } 20912 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20913 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20914 } 20915 } 20916 20917 @Override 20918 public KeySet getSigningKeySet(String packageName) { 20919 if (packageName == null) { 20920 return null; 20921 } 20922 synchronized(mPackages) { 20923 final PackageParser.Package pkg = mPackages.get(packageName); 20924 if (pkg == null) { 20925 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20926 throw new IllegalArgumentException("Unknown package: " + packageName); 20927 } 20928 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20929 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20930 throw new SecurityException("May not access signing KeySet of other apps."); 20931 } 20932 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20933 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20934 } 20935 } 20936 20937 @Override 20938 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20939 if (packageName == null || ks == null) { 20940 return false; 20941 } 20942 synchronized(mPackages) { 20943 final PackageParser.Package pkg = mPackages.get(packageName); 20944 if (pkg == null) { 20945 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20946 throw new IllegalArgumentException("Unknown package: " + packageName); 20947 } 20948 IBinder ksh = ks.getToken(); 20949 if (ksh instanceof KeySetHandle) { 20950 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20951 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20952 } 20953 return false; 20954 } 20955 } 20956 20957 @Override 20958 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20959 if (packageName == null || ks == null) { 20960 return false; 20961 } 20962 synchronized(mPackages) { 20963 final PackageParser.Package pkg = mPackages.get(packageName); 20964 if (pkg == null) { 20965 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20966 throw new IllegalArgumentException("Unknown package: " + packageName); 20967 } 20968 IBinder ksh = ks.getToken(); 20969 if (ksh instanceof KeySetHandle) { 20970 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20971 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20972 } 20973 return false; 20974 } 20975 } 20976 20977 private void deletePackageIfUnusedLPr(final String packageName) { 20978 PackageSetting ps = mSettings.mPackages.get(packageName); 20979 if (ps == null) { 20980 return; 20981 } 20982 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20983 // TODO Implement atomic delete if package is unused 20984 // It is currently possible that the package will be deleted even if it is installed 20985 // after this method returns. 20986 mHandler.post(new Runnable() { 20987 public void run() { 20988 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20989 } 20990 }); 20991 } 20992 } 20993 20994 /** 20995 * Check and throw if the given before/after packages would be considered a 20996 * downgrade. 20997 */ 20998 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20999 throws PackageManagerException { 21000 if (after.versionCode < before.mVersionCode) { 21001 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21002 "Update version code " + after.versionCode + " is older than current " 21003 + before.mVersionCode); 21004 } else if (after.versionCode == before.mVersionCode) { 21005 if (after.baseRevisionCode < before.baseRevisionCode) { 21006 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21007 "Update base revision code " + after.baseRevisionCode 21008 + " is older than current " + before.baseRevisionCode); 21009 } 21010 21011 if (!ArrayUtils.isEmpty(after.splitNames)) { 21012 for (int i = 0; i < after.splitNames.length; i++) { 21013 final String splitName = after.splitNames[i]; 21014 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 21015 if (j != -1) { 21016 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 21017 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21018 "Update split " + splitName + " revision code " 21019 + after.splitRevisionCodes[i] + " is older than current " 21020 + before.splitRevisionCodes[j]); 21021 } 21022 } 21023 } 21024 } 21025 } 21026 } 21027 21028 private static class MoveCallbacks extends Handler { 21029 private static final int MSG_CREATED = 1; 21030 private static final int MSG_STATUS_CHANGED = 2; 21031 21032 private final RemoteCallbackList<IPackageMoveObserver> 21033 mCallbacks = new RemoteCallbackList<>(); 21034 21035 private final SparseIntArray mLastStatus = new SparseIntArray(); 21036 21037 public MoveCallbacks(Looper looper) { 21038 super(looper); 21039 } 21040 21041 public void register(IPackageMoveObserver callback) { 21042 mCallbacks.register(callback); 21043 } 21044 21045 public void unregister(IPackageMoveObserver callback) { 21046 mCallbacks.unregister(callback); 21047 } 21048 21049 @Override 21050 public void handleMessage(Message msg) { 21051 final SomeArgs args = (SomeArgs) msg.obj; 21052 final int n = mCallbacks.beginBroadcast(); 21053 for (int i = 0; i < n; i++) { 21054 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 21055 try { 21056 invokeCallback(callback, msg.what, args); 21057 } catch (RemoteException ignored) { 21058 } 21059 } 21060 mCallbacks.finishBroadcast(); 21061 args.recycle(); 21062 } 21063 21064 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 21065 throws RemoteException { 21066 switch (what) { 21067 case MSG_CREATED: { 21068 callback.onCreated(args.argi1, (Bundle) args.arg2); 21069 break; 21070 } 21071 case MSG_STATUS_CHANGED: { 21072 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 21073 break; 21074 } 21075 } 21076 } 21077 21078 private void notifyCreated(int moveId, Bundle extras) { 21079 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 21080 21081 final SomeArgs args = SomeArgs.obtain(); 21082 args.argi1 = moveId; 21083 args.arg2 = extras; 21084 obtainMessage(MSG_CREATED, args).sendToTarget(); 21085 } 21086 21087 private void notifyStatusChanged(int moveId, int status) { 21088 notifyStatusChanged(moveId, status, -1); 21089 } 21090 21091 private void notifyStatusChanged(int moveId, int status, long estMillis) { 21092 Slog.v(TAG, "Move " + moveId + " status " + status); 21093 21094 final SomeArgs args = SomeArgs.obtain(); 21095 args.argi1 = moveId; 21096 args.argi2 = status; 21097 args.arg3 = estMillis; 21098 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 21099 21100 synchronized (mLastStatus) { 21101 mLastStatus.put(moveId, status); 21102 } 21103 } 21104 } 21105 21106 private final static class OnPermissionChangeListeners extends Handler { 21107 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 21108 21109 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 21110 new RemoteCallbackList<>(); 21111 21112 public OnPermissionChangeListeners(Looper looper) { 21113 super(looper); 21114 } 21115 21116 @Override 21117 public void handleMessage(Message msg) { 21118 switch (msg.what) { 21119 case MSG_ON_PERMISSIONS_CHANGED: { 21120 final int uid = msg.arg1; 21121 handleOnPermissionsChanged(uid); 21122 } break; 21123 } 21124 } 21125 21126 public void addListenerLocked(IOnPermissionsChangeListener listener) { 21127 mPermissionListeners.register(listener); 21128 21129 } 21130 21131 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 21132 mPermissionListeners.unregister(listener); 21133 } 21134 21135 public void onPermissionsChanged(int uid) { 21136 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 21137 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 21138 } 21139 } 21140 21141 private void handleOnPermissionsChanged(int uid) { 21142 final int count = mPermissionListeners.beginBroadcast(); 21143 try { 21144 for (int i = 0; i < count; i++) { 21145 IOnPermissionsChangeListener callback = mPermissionListeners 21146 .getBroadcastItem(i); 21147 try { 21148 callback.onPermissionsChanged(uid); 21149 } catch (RemoteException e) { 21150 Log.e(TAG, "Permission listener is dead", e); 21151 } 21152 } 21153 } finally { 21154 mPermissionListeners.finishBroadcast(); 21155 } 21156 } 21157 } 21158 21159 private class PackageManagerInternalImpl extends PackageManagerInternal { 21160 @Override 21161 public void setLocationPackagesProvider(PackagesProvider provider) { 21162 synchronized (mPackages) { 21163 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 21164 } 21165 } 21166 21167 @Override 21168 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 21169 synchronized (mPackages) { 21170 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 21171 } 21172 } 21173 21174 @Override 21175 public void setSmsAppPackagesProvider(PackagesProvider provider) { 21176 synchronized (mPackages) { 21177 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 21178 } 21179 } 21180 21181 @Override 21182 public void setDialerAppPackagesProvider(PackagesProvider provider) { 21183 synchronized (mPackages) { 21184 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 21185 } 21186 } 21187 21188 @Override 21189 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 21190 synchronized (mPackages) { 21191 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 21192 } 21193 } 21194 21195 @Override 21196 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 21197 synchronized (mPackages) { 21198 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 21199 } 21200 } 21201 21202 @Override 21203 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 21204 synchronized (mPackages) { 21205 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 21206 packageName, userId); 21207 } 21208 } 21209 21210 @Override 21211 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 21212 synchronized (mPackages) { 21213 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 21214 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 21215 packageName, userId); 21216 } 21217 } 21218 21219 @Override 21220 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 21221 synchronized (mPackages) { 21222 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 21223 packageName, userId); 21224 } 21225 } 21226 21227 @Override 21228 public void setKeepUninstalledPackages(final List<String> packageList) { 21229 Preconditions.checkNotNull(packageList); 21230 List<String> removedFromList = null; 21231 synchronized (mPackages) { 21232 if (mKeepUninstalledPackages != null) { 21233 final int packagesCount = mKeepUninstalledPackages.size(); 21234 for (int i = 0; i < packagesCount; i++) { 21235 String oldPackage = mKeepUninstalledPackages.get(i); 21236 if (packageList != null && packageList.contains(oldPackage)) { 21237 continue; 21238 } 21239 if (removedFromList == null) { 21240 removedFromList = new ArrayList<>(); 21241 } 21242 removedFromList.add(oldPackage); 21243 } 21244 } 21245 mKeepUninstalledPackages = new ArrayList<>(packageList); 21246 if (removedFromList != null) { 21247 final int removedCount = removedFromList.size(); 21248 for (int i = 0; i < removedCount; i++) { 21249 deletePackageIfUnusedLPr(removedFromList.get(i)); 21250 } 21251 } 21252 } 21253 } 21254 21255 @Override 21256 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21257 synchronized (mPackages) { 21258 // If we do not support permission review, done. 21259 if (!mPermissionReviewRequired) { 21260 return false; 21261 } 21262 21263 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21264 if (packageSetting == null) { 21265 return false; 21266 } 21267 21268 // Permission review applies only to apps not supporting the new permission model. 21269 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21270 return false; 21271 } 21272 21273 // Legacy apps have the permission and get user consent on launch. 21274 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21275 return permissionsState.isPermissionReviewRequired(userId); 21276 } 21277 } 21278 21279 @Override 21280 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21281 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21282 } 21283 21284 @Override 21285 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21286 int userId) { 21287 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21288 } 21289 21290 @Override 21291 public void setDeviceAndProfileOwnerPackages( 21292 int deviceOwnerUserId, String deviceOwnerPackage, 21293 SparseArray<String> profileOwnerPackages) { 21294 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21295 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21296 } 21297 21298 @Override 21299 public boolean isPackageDataProtected(int userId, String packageName) { 21300 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21301 } 21302 21303 @Override 21304 public boolean isPackageEphemeral(int userId, String packageName) { 21305 synchronized (mPackages) { 21306 PackageParser.Package p = mPackages.get(packageName); 21307 return p != null ? p.applicationInfo.isEphemeralApp() : false; 21308 } 21309 } 21310 21311 @Override 21312 public boolean wasPackageEverLaunched(String packageName, int userId) { 21313 synchronized (mPackages) { 21314 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21315 } 21316 } 21317 21318 @Override 21319 public void grantRuntimePermission(String packageName, String name, int userId, 21320 boolean overridePolicy) { 21321 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 21322 overridePolicy); 21323 } 21324 21325 @Override 21326 public void revokeRuntimePermission(String packageName, String name, int userId, 21327 boolean overridePolicy) { 21328 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 21329 overridePolicy); 21330 } 21331 21332 @Override 21333 public String getNameForUid(int uid) { 21334 return PackageManagerService.this.getNameForUid(uid); 21335 } 21336 21337 @Override 21338 public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 21339 Intent origIntent, String resolvedType, Intent launchIntent, 21340 String callingPackage, int userId) { 21341 PackageManagerService.this.requestEphemeralResolutionPhaseTwo( 21342 responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId); 21343 } 21344 } 21345 21346 @Override 21347 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21348 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21349 synchronized (mPackages) { 21350 final long identity = Binder.clearCallingIdentity(); 21351 try { 21352 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21353 packageNames, userId); 21354 } finally { 21355 Binder.restoreCallingIdentity(identity); 21356 } 21357 } 21358 } 21359 21360 private static void enforceSystemOrPhoneCaller(String tag) { 21361 int callingUid = Binder.getCallingUid(); 21362 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21363 throw new SecurityException( 21364 "Cannot call " + tag + " from UID " + callingUid); 21365 } 21366 } 21367 21368 boolean isHistoricalPackageUsageAvailable() { 21369 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21370 } 21371 21372 /** 21373 * Return a <b>copy</b> of the collection of packages known to the package manager. 21374 * @return A copy of the values of mPackages. 21375 */ 21376 Collection<PackageParser.Package> getPackages() { 21377 synchronized (mPackages) { 21378 return new ArrayList<>(mPackages.values()); 21379 } 21380 } 21381 21382 /** 21383 * Logs process start information (including base APK hash) to the security log. 21384 * @hide 21385 */ 21386 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21387 String apkFile, int pid) { 21388 if (!SecurityLog.isLoggingEnabled()) { 21389 return; 21390 } 21391 Bundle data = new Bundle(); 21392 data.putLong("startTimestamp", System.currentTimeMillis()); 21393 data.putString("processName", processName); 21394 data.putInt("uid", uid); 21395 data.putString("seinfo", seinfo); 21396 data.putString("apkFile", apkFile); 21397 data.putInt("pid", pid); 21398 Message msg = mProcessLoggingHandler.obtainMessage( 21399 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21400 msg.setData(data); 21401 mProcessLoggingHandler.sendMessage(msg); 21402 } 21403 21404 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21405 return mCompilerStats.getPackageStats(pkgName); 21406 } 21407 21408 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21409 return getOrCreateCompilerPackageStats(pkg.packageName); 21410 } 21411 21412 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21413 return mCompilerStats.getOrCreatePackageStats(pkgName); 21414 } 21415 21416 public void deleteCompilerPackageStats(String pkgName) { 21417 mCompilerStats.deletePackageStats(pkgName); 21418 } 21419} 21420