PackageManagerService.java revision 01ad0c7e403794b272494f187d91f57bdfa07c9d
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 61import static android.content.pm.PackageManager.MATCH_ALL; 62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 63import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 65import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 66import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 74import static android.content.pm.PackageManager.PERMISSION_DENIED; 75import static android.content.pm.PackageManager.PERMISSION_GRANTED; 76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 77import static android.content.pm.PackageParser.isApkFile; 78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 79import static android.system.OsConstants.O_CREAT; 80import static android.system.OsConstants.O_RDWR; 81 82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 86import static com.android.internal.util.ArrayUtils.appendInt; 87import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 93import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 99 100import android.Manifest; 101import android.annotation.NonNull; 102import android.annotation.Nullable; 103import android.app.ActivityManager; 104import android.app.ActivityManagerNative; 105import android.app.IActivityManager; 106import android.app.ResourcesManager; 107import android.app.admin.IDevicePolicyManager; 108import android.app.admin.SecurityLog; 109import android.app.backup.IBackupManager; 110import android.content.BroadcastReceiver; 111import android.content.ComponentName; 112import android.content.ContentResolver; 113import android.content.Context; 114import android.content.IIntentReceiver; 115import android.content.Intent; 116import android.content.IntentFilter; 117import android.content.IntentSender; 118import android.content.IntentSender.SendIntentException; 119import android.content.ServiceConnection; 120import android.content.pm.ActivityInfo; 121import android.content.pm.ApplicationInfo; 122import android.content.pm.AppsQueryHelper; 123import android.content.pm.ComponentInfo; 124import android.content.pm.EphemeralApplicationInfo; 125import android.content.pm.EphemeralRequest; 126import android.content.pm.EphemeralResolveInfo; 127import android.content.pm.EphemeralResponse; 128import android.content.pm.FeatureInfo; 129import android.content.pm.IOnPermissionsChangeListener; 130import android.content.pm.IPackageDataObserver; 131import android.content.pm.IPackageDeleteObserver; 132import android.content.pm.IPackageDeleteObserver2; 133import android.content.pm.IPackageInstallObserver2; 134import android.content.pm.IPackageInstaller; 135import android.content.pm.IPackageManager; 136import android.content.pm.IPackageMoveObserver; 137import android.content.pm.IPackageStatsObserver; 138import android.content.pm.InstrumentationInfo; 139import android.content.pm.IntentFilterVerificationInfo; 140import android.content.pm.KeySet; 141import android.content.pm.PackageCleanItem; 142import android.content.pm.PackageInfo; 143import android.content.pm.PackageInfoLite; 144import android.content.pm.PackageInstaller; 145import android.content.pm.PackageManager; 146import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 147import android.content.pm.PackageManagerInternal; 148import android.content.pm.PackageParser; 149import android.content.pm.PackageParser.ActivityIntentInfo; 150import android.content.pm.PackageParser.PackageLite; 151import android.content.pm.PackageParser.PackageParserException; 152import android.content.pm.PackageStats; 153import android.content.pm.PackageUserState; 154import android.content.pm.ParceledListSlice; 155import android.content.pm.PermissionGroupInfo; 156import android.content.pm.PermissionInfo; 157import android.content.pm.ProviderInfo; 158import android.content.pm.ResolveInfo; 159import android.content.pm.ServiceInfo; 160import android.content.pm.Signature; 161import android.content.pm.UserInfo; 162import android.content.pm.VerifierDeviceIdentity; 163import android.content.pm.VerifierInfo; 164import android.content.res.Resources; 165import android.graphics.Bitmap; 166import android.hardware.display.DisplayManager; 167import android.net.Uri; 168import android.os.Binder; 169import android.os.Build; 170import android.os.Bundle; 171import android.os.Debug; 172import android.os.Environment; 173import android.os.Environment.UserEnvironment; 174import android.os.FileUtils; 175import android.os.Handler; 176import android.os.IBinder; 177import android.os.Looper; 178import android.os.Message; 179import android.os.Parcel; 180import android.os.ParcelFileDescriptor; 181import android.os.PatternMatcher; 182import android.os.Process; 183import android.os.RemoteCallbackList; 184import android.os.RemoteException; 185import android.os.ResultReceiver; 186import android.os.SELinux; 187import android.os.ServiceManager; 188import android.os.ShellCallback; 189import android.os.SystemClock; 190import android.os.SystemProperties; 191import android.os.Trace; 192import android.os.UserHandle; 193import android.os.UserManager; 194import android.os.UserManagerInternal; 195import android.os.storage.IMountService; 196import android.os.storage.MountServiceInternal; 197import android.os.storage.StorageEventListener; 198import android.os.storage.StorageManager; 199import android.os.storage.VolumeInfo; 200import android.os.storage.VolumeRecord; 201import android.provider.Settings.Global; 202import android.provider.Settings.Secure; 203import android.security.KeyStore; 204import android.security.SystemKeyStore; 205import android.system.ErrnoException; 206import android.system.Os; 207import android.text.TextUtils; 208import android.text.format.DateUtils; 209import android.util.ArrayMap; 210import android.util.ArraySet; 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.SomeArgs; 237import com.android.internal.os.Zygote; 238import com.android.internal.telephony.CarrierAppUtils; 239import com.android.internal.util.ArrayUtils; 240import com.android.internal.util.FastPrintWriter; 241import com.android.internal.util.FastXmlSerializer; 242import com.android.internal.util.IndentingPrintWriter; 243import com.android.internal.util.Preconditions; 244import com.android.internal.util.XmlUtils; 245import com.android.server.AttributeCache; 246import com.android.server.EventLogTags; 247import com.android.server.FgThread; 248import com.android.server.IntentResolver; 249import com.android.server.LocalServices; 250import com.android.server.ServiceThread; 251import com.android.server.SystemConfig; 252import com.android.server.Watchdog; 253import com.android.server.net.NetworkPolicyManagerInternal; 254import com.android.server.pm.PermissionsState.PermissionState; 255import com.android.server.pm.Settings.DatabaseVersion; 256import com.android.server.pm.Settings.VersionInfo; 257import com.android.server.storage.DeviceStorageMonitorInternal; 258 259import dalvik.system.CloseGuard; 260import dalvik.system.DexFile; 261import dalvik.system.VMRuntime; 262 263import libcore.io.IoUtils; 264import libcore.util.EmptyArray; 265 266import org.xmlpull.v1.XmlPullParser; 267import org.xmlpull.v1.XmlPullParserException; 268import org.xmlpull.v1.XmlSerializer; 269 270import java.io.BufferedOutputStream; 271import java.io.BufferedReader; 272import java.io.ByteArrayInputStream; 273import java.io.ByteArrayOutputStream; 274import java.io.File; 275import java.io.FileDescriptor; 276import java.io.FileInputStream; 277import java.io.FileNotFoundException; 278import java.io.FileOutputStream; 279import java.io.FileReader; 280import java.io.FilenameFilter; 281import java.io.IOException; 282import java.io.PrintWriter; 283import java.nio.charset.StandardCharsets; 284import java.security.DigestInputStream; 285import java.security.MessageDigest; 286import java.security.NoSuchAlgorithmException; 287import java.security.PublicKey; 288import java.security.cert.Certificate; 289import java.security.cert.CertificateEncodingException; 290import java.security.cert.CertificateException; 291import java.text.SimpleDateFormat; 292import java.util.ArrayList; 293import java.util.Arrays; 294import java.util.Collection; 295import java.util.Collections; 296import java.util.Comparator; 297import java.util.Date; 298import java.util.HashSet; 299import java.util.Iterator; 300import java.util.List; 301import java.util.Map; 302import java.util.Objects; 303import java.util.Set; 304import java.util.concurrent.CountDownLatch; 305import java.util.concurrent.TimeUnit; 306import java.util.concurrent.atomic.AtomicBoolean; 307import java.util.concurrent.atomic.AtomicInteger; 308 309/** 310 * Keep track of all those APKs everywhere. 311 * <p> 312 * Internally there are two important locks: 313 * <ul> 314 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 315 * and other related state. It is a fine-grained lock that should only be held 316 * momentarily, as it's one of the most contended locks in the system. 317 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 318 * operations typically involve heavy lifting of application data on disk. Since 319 * {@code installd} is single-threaded, and it's operations can often be slow, 320 * this lock should never be acquired while already holding {@link #mPackages}. 321 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 322 * holding {@link #mInstallLock}. 323 * </ul> 324 * Many internal methods rely on the caller to hold the appropriate locks, and 325 * this contract is expressed through method name suffixes: 326 * <ul> 327 * <li>fooLI(): the caller must hold {@link #mInstallLock} 328 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 329 * being modified must be frozen 330 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 331 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 332 * </ul> 333 * <p> 334 * Because this class is very central to the platform's security; please run all 335 * CTS and unit tests whenever making modifications: 336 * 337 * <pre> 338 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 339 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 340 * </pre> 341 */ 342public class PackageManagerService extends IPackageManager.Stub { 343 static final String TAG = "PackageManager"; 344 static final boolean DEBUG_SETTINGS = false; 345 static final boolean DEBUG_PREFERRED = false; 346 static final boolean DEBUG_UPGRADE = false; 347 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 348 private static final boolean DEBUG_BACKUP = false; 349 private static final boolean DEBUG_INSTALL = false; 350 private static final boolean DEBUG_REMOVE = false; 351 private static final boolean DEBUG_BROADCASTS = false; 352 private static final boolean DEBUG_SHOW_INFO = false; 353 private static final boolean DEBUG_PACKAGE_INFO = false; 354 private static final boolean DEBUG_INTENT_MATCHING = false; 355 private static final boolean DEBUG_PACKAGE_SCANNING = false; 356 private static final boolean DEBUG_VERIFY = false; 357 private static final boolean DEBUG_FILTERS = false; 358 359 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 360 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 361 // user, but by default initialize to this. 362 static final boolean DEBUG_DEXOPT = false; 363 364 private static final boolean DEBUG_ABI_SELECTION = false; 365 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 366 private static final boolean DEBUG_TRIAGED_MISSING = false; 367 private static final boolean DEBUG_APP_DATA = false; 368 369 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 370 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 371 372 private static final boolean DISABLE_EPHEMERAL_APPS = false; 373 private static final boolean HIDE_EPHEMERAL_APIS = true; 374 375 private static final int RADIO_UID = Process.PHONE_UID; 376 private static final int LOG_UID = Process.LOG_UID; 377 private static final int NFC_UID = Process.NFC_UID; 378 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 379 private static final int SHELL_UID = Process.SHELL_UID; 380 381 // Cap the size of permission trees that 3rd party apps can define 382 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 383 384 // Suffix used during package installation when copying/moving 385 // package apks to install directory. 386 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 387 388 static final int SCAN_NO_DEX = 1<<1; 389 static final int SCAN_FORCE_DEX = 1<<2; 390 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 391 static final int SCAN_NEW_INSTALL = 1<<4; 392 static final int SCAN_NO_PATHS = 1<<5; 393 static final int SCAN_UPDATE_TIME = 1<<6; 394 static final int SCAN_DEFER_DEX = 1<<7; 395 static final int SCAN_BOOTING = 1<<8; 396 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 397 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 398 static final int SCAN_REPLACING = 1<<11; 399 static final int SCAN_REQUIRE_KNOWN = 1<<12; 400 static final int SCAN_MOVE = 1<<13; 401 static final int SCAN_INITIAL = 1<<14; 402 static final int SCAN_CHECK_ONLY = 1<<15; 403 static final int SCAN_DONT_KILL_APP = 1<<17; 404 static final int SCAN_IGNORE_FROZEN = 1<<18; 405 406 static final int REMOVE_CHATTY = 1<<16; 407 408 private static final int[] EMPTY_INT_ARRAY = new int[0]; 409 410 /** 411 * Timeout (in milliseconds) after which the watchdog should declare that 412 * our handler thread is wedged. The usual default for such things is one 413 * minute but we sometimes do very lengthy I/O operations on this thread, 414 * such as installing multi-gigabyte applications, so ours needs to be longer. 415 */ 416 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 417 418 /** 419 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 420 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 421 * settings entry if available, otherwise we use the hardcoded default. If it's been 422 * more than this long since the last fstrim, we force one during the boot sequence. 423 * 424 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 425 * one gets run at the next available charging+idle time. This final mandatory 426 * no-fstrim check kicks in only of the other scheduling criteria is never met. 427 */ 428 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 429 430 /** 431 * Whether verification is enabled by default. 432 */ 433 private static final boolean DEFAULT_VERIFY_ENABLE = true; 434 435 /** 436 * The default maximum time to wait for the verification agent to return in 437 * milliseconds. 438 */ 439 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 440 441 /** 442 * The default response for package verification timeout. 443 * 444 * This can be either PackageManager.VERIFICATION_ALLOW or 445 * PackageManager.VERIFICATION_REJECT. 446 */ 447 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 448 449 static final String PLATFORM_PACKAGE_NAME = "android"; 450 451 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 452 453 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 454 DEFAULT_CONTAINER_PACKAGE, 455 "com.android.defcontainer.DefaultContainerService"); 456 457 private static final String KILL_APP_REASON_GIDS_CHANGED = 458 "permission grant or revoke changed gids"; 459 460 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 461 "permissions revoked"; 462 463 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 464 465 private static final String PACKAGE_SCHEME = "package"; 466 467 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 468 /** 469 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 470 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 471 * VENDOR_OVERLAY_DIR. 472 */ 473 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 474 /** 475 * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever 476 * is in VENDOR_OVERLAY_THEME_PROPERTY. 477 */ 478 private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY 479 = "persist.vendor.overlay.theme"; 480 481 /** Permission grant: not grant the permission. */ 482 private static final int GRANT_DENIED = 1; 483 484 /** Permission grant: grant the permission as an install permission. */ 485 private static final int GRANT_INSTALL = 2; 486 487 /** Permission grant: grant the permission as a runtime one. */ 488 private static final int GRANT_RUNTIME = 3; 489 490 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 491 private static final int GRANT_UPGRADE = 4; 492 493 /** Canonical intent used to identify what counts as a "web browser" app */ 494 private static final Intent sBrowserIntent; 495 static { 496 sBrowserIntent = new Intent(); 497 sBrowserIntent.setAction(Intent.ACTION_VIEW); 498 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 499 sBrowserIntent.setData(Uri.parse("http:")); 500 } 501 502 /** 503 * The set of all protected actions [i.e. those actions for which a high priority 504 * intent filter is disallowed]. 505 */ 506 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 507 static { 508 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 509 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 510 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 511 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 512 } 513 514 // Compilation reasons. 515 public static final int REASON_FIRST_BOOT = 0; 516 public static final int REASON_BOOT = 1; 517 public static final int REASON_INSTALL = 2; 518 public static final int REASON_BACKGROUND_DEXOPT = 3; 519 public static final int REASON_AB_OTA = 4; 520 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 521 public static final int REASON_SHARED_APK = 6; 522 public static final int REASON_FORCED_DEXOPT = 7; 523 public static final int REASON_CORE_APP = 8; 524 525 public static final int REASON_LAST = REASON_CORE_APP; 526 527 /** Special library name that skips shared libraries check during compilation. */ 528 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 529 530 final ServiceThread mHandlerThread; 531 532 final PackageHandler mHandler; 533 534 private final ProcessLoggingHandler mProcessLoggingHandler; 535 536 /** 537 * Messages for {@link #mHandler} that need to wait for system ready before 538 * being dispatched. 539 */ 540 private ArrayList<Message> mPostSystemReadyMessages; 541 542 final int mSdkVersion = Build.VERSION.SDK_INT; 543 544 final Context mContext; 545 final boolean mFactoryTest; 546 final boolean mOnlyCore; 547 final DisplayMetrics mMetrics; 548 final int mDefParseFlags; 549 final String[] mSeparateProcesses; 550 final boolean mIsUpgrade; 551 final boolean mIsPreNUpgrade; 552 final boolean mIsPreNMR1Upgrade; 553 554 @GuardedBy("mPackages") 555 private boolean mDexOptDialogShown; 556 557 /** The location for ASEC container files on internal storage. */ 558 final String mAsecInternalPath; 559 560 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 561 // LOCK HELD. Can be called with mInstallLock held. 562 @GuardedBy("mInstallLock") 563 final Installer mInstaller; 564 565 /** Directory where installed third-party apps stored */ 566 final File mAppInstallDir; 567 final File mEphemeralInstallDir; 568 569 /** 570 * Directory to which applications installed internally have their 571 * 32 bit native libraries copied. 572 */ 573 private File mAppLib32InstallDir; 574 575 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 576 // apps. 577 final File mDrmAppPrivateInstallDir; 578 579 // ---------------------------------------------------------------- 580 581 // Lock for state used when installing and doing other long running 582 // operations. Methods that must be called with this lock held have 583 // the suffix "LI". 584 final Object mInstallLock = new Object(); 585 586 // ---------------------------------------------------------------- 587 588 // Keys are String (package name), values are Package. This also serves 589 // as the lock for the global state. Methods that must be called with 590 // this lock held have the prefix "LP". 591 @GuardedBy("mPackages") 592 final ArrayMap<String, PackageParser.Package> mPackages = 593 new ArrayMap<String, PackageParser.Package>(); 594 595 final ArrayMap<String, Set<String>> mKnownCodebase = 596 new ArrayMap<String, Set<String>>(); 597 598 // Tracks available target package names -> overlay package paths. 599 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 600 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 601 602 /** 603 * Tracks new system packages [received in an OTA] that we expect to 604 * find updated user-installed versions. Keys are package name, values 605 * are package location. 606 */ 607 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 608 /** 609 * Tracks high priority intent filters for protected actions. During boot, certain 610 * filter actions are protected and should never be allowed to have a high priority 611 * intent filter for them. However, there is one, and only one exception -- the 612 * setup wizard. It must be able to define a high priority intent filter for these 613 * actions to ensure there are no escapes from the wizard. We need to delay processing 614 * of these during boot as we need to look at all of the system packages in order 615 * to know which component is the setup wizard. 616 */ 617 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 618 /** 619 * Whether or not processing protected filters should be deferred. 620 */ 621 private boolean mDeferProtectedFilters = true; 622 623 /** 624 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 625 */ 626 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 627 /** 628 * Whether or not system app permissions should be promoted from install to runtime. 629 */ 630 boolean mPromoteSystemApps; 631 632 @GuardedBy("mPackages") 633 final Settings mSettings; 634 635 /** 636 * Set of package names that are currently "frozen", which means active 637 * surgery is being done on the code/data for that package. The platform 638 * will refuse to launch frozen packages to avoid race conditions. 639 * 640 * @see PackageFreezer 641 */ 642 @GuardedBy("mPackages") 643 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 644 645 final ProtectedPackages mProtectedPackages; 646 647 boolean mFirstBoot; 648 649 // System configuration read by SystemConfig. 650 final int[] mGlobalGids; 651 final SparseArray<ArraySet<String>> mSystemPermissions; 652 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 653 654 // If mac_permissions.xml was found for seinfo labeling. 655 boolean mFoundPolicyFile; 656 657 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 658 659 public static final class SharedLibraryEntry { 660 public final String path; 661 public final String apk; 662 663 SharedLibraryEntry(String _path, String _apk) { 664 path = _path; 665 apk = _apk; 666 } 667 } 668 669 // Currently known shared libraries. 670 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 671 new ArrayMap<String, SharedLibraryEntry>(); 672 673 // All available activities, for your resolving pleasure. 674 final ActivityIntentResolver mActivities = 675 new ActivityIntentResolver(); 676 677 // All available receivers, for your resolving pleasure. 678 final ActivityIntentResolver mReceivers = 679 new ActivityIntentResolver(); 680 681 // All available services, for your resolving pleasure. 682 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 683 684 // All available providers, for your resolving pleasure. 685 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 686 687 // Mapping from provider base names (first directory in content URI codePath) 688 // to the provider information. 689 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 690 new ArrayMap<String, PackageParser.Provider>(); 691 692 // Mapping from instrumentation class names to info about them. 693 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 694 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 695 696 // Mapping from permission names to info about them. 697 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 698 new ArrayMap<String, PackageParser.PermissionGroup>(); 699 700 // Packages whose data we have transfered into another package, thus 701 // should no longer exist. 702 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 703 704 // Broadcast actions that are only available to the system. 705 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 706 707 /** List of packages waiting for verification. */ 708 final SparseArray<PackageVerificationState> mPendingVerification 709 = new SparseArray<PackageVerificationState>(); 710 711 /** Set of packages associated with each app op permission. */ 712 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 713 714 final PackageInstallerService mInstallerService; 715 716 private final PackageDexOptimizer mPackageDexOptimizer; 717 718 private AtomicInteger mNextMoveId = new AtomicInteger(); 719 private final MoveCallbacks mMoveCallbacks; 720 721 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 722 723 // Cache of users who need badging. 724 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 725 726 /** Token for keys in mPendingVerification. */ 727 private int mPendingVerificationToken = 0; 728 729 volatile boolean mSystemReady; 730 volatile boolean mSafeMode; 731 volatile boolean mHasSystemUidErrors; 732 733 ApplicationInfo mAndroidApplication; 734 final ActivityInfo mResolveActivity = new ActivityInfo(); 735 final ResolveInfo mResolveInfo = new ResolveInfo(); 736 ComponentName mResolveComponentName; 737 PackageParser.Package mPlatformPackage; 738 ComponentName mCustomResolverComponentName; 739 740 boolean mResolverReplaced = false; 741 742 private final @Nullable ComponentName mIntentFilterVerifierComponent; 743 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 744 745 private int mIntentFilterVerificationToken = 0; 746 747 /** Component that knows whether or not an ephemeral application exists */ 748 final ComponentName mEphemeralResolverComponent; 749 /** The service connection to the ephemeral resolver */ 750 final EphemeralResolverConnection mEphemeralResolverConnection; 751 752 /** Component used to install ephemeral applications */ 753 final ComponentName mEphemeralInstallerComponent; 754 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 755 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 756 757 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 758 = new SparseArray<IntentFilterVerificationState>(); 759 760 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 761 762 // List of packages names to keep cached, even if they are uninstalled for all users 763 private List<String> mKeepUninstalledPackages; 764 765 private UserManagerInternal mUserManagerInternal; 766 767 private static class IFVerificationParams { 768 PackageParser.Package pkg; 769 boolean replacing; 770 int userId; 771 int verifierUid; 772 773 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 774 int _userId, int _verifierUid) { 775 pkg = _pkg; 776 replacing = _replacing; 777 userId = _userId; 778 replacing = _replacing; 779 verifierUid = _verifierUid; 780 } 781 } 782 783 private interface IntentFilterVerifier<T extends IntentFilter> { 784 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 785 T filter, String packageName); 786 void startVerifications(int userId); 787 void receiveVerificationResponse(int verificationId); 788 } 789 790 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 791 private Context mContext; 792 private ComponentName mIntentFilterVerifierComponent; 793 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 794 795 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 796 mContext = context; 797 mIntentFilterVerifierComponent = verifierComponent; 798 } 799 800 private String getDefaultScheme() { 801 return IntentFilter.SCHEME_HTTPS; 802 } 803 804 @Override 805 public void startVerifications(int userId) { 806 // Launch verifications requests 807 int count = mCurrentIntentFilterVerifications.size(); 808 for (int n=0; n<count; n++) { 809 int verificationId = mCurrentIntentFilterVerifications.get(n); 810 final IntentFilterVerificationState ivs = 811 mIntentFilterVerificationStates.get(verificationId); 812 813 String packageName = ivs.getPackageName(); 814 815 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 816 final int filterCount = filters.size(); 817 ArraySet<String> domainsSet = new ArraySet<>(); 818 for (int m=0; m<filterCount; m++) { 819 PackageParser.ActivityIntentInfo filter = filters.get(m); 820 domainsSet.addAll(filter.getHostsList()); 821 } 822 synchronized (mPackages) { 823 if (mSettings.createIntentFilterVerificationIfNeededLPw( 824 packageName, domainsSet) != null) { 825 scheduleWriteSettingsLocked(); 826 } 827 } 828 sendVerificationRequest(userId, verificationId, ivs); 829 } 830 mCurrentIntentFilterVerifications.clear(); 831 } 832 833 private void sendVerificationRequest(int userId, int verificationId, 834 IntentFilterVerificationState ivs) { 835 836 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 837 verificationIntent.putExtra( 838 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 839 verificationId); 840 verificationIntent.putExtra( 841 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 842 getDefaultScheme()); 843 verificationIntent.putExtra( 844 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 845 ivs.getHostsString()); 846 verificationIntent.putExtra( 847 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 848 ivs.getPackageName()); 849 verificationIntent.setComponent(mIntentFilterVerifierComponent); 850 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 851 852 UserHandle user = new UserHandle(userId); 853 mContext.sendBroadcastAsUser(verificationIntent, user); 854 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 855 "Sending IntentFilter verification broadcast"); 856 } 857 858 public void receiveVerificationResponse(int verificationId) { 859 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 860 861 final boolean verified = ivs.isVerified(); 862 863 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 864 final int count = filters.size(); 865 if (DEBUG_DOMAIN_VERIFICATION) { 866 Slog.i(TAG, "Received verification response " + verificationId 867 + " for " + count + " filters, verified=" + verified); 868 } 869 for (int n=0; n<count; n++) { 870 PackageParser.ActivityIntentInfo filter = filters.get(n); 871 filter.setVerified(verified); 872 873 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 874 + " verified with result:" + verified + " and hosts:" 875 + ivs.getHostsString()); 876 } 877 878 mIntentFilterVerificationStates.remove(verificationId); 879 880 final String packageName = ivs.getPackageName(); 881 IntentFilterVerificationInfo ivi = null; 882 883 synchronized (mPackages) { 884 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 885 } 886 if (ivi == null) { 887 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 888 + verificationId + " packageName:" + packageName); 889 return; 890 } 891 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 892 "Updating IntentFilterVerificationInfo for package " + packageName 893 +" verificationId:" + verificationId); 894 895 synchronized (mPackages) { 896 if (verified) { 897 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 898 } else { 899 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 900 } 901 scheduleWriteSettingsLocked(); 902 903 final int userId = ivs.getUserId(); 904 if (userId != UserHandle.USER_ALL) { 905 final int userStatus = 906 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 907 908 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 909 boolean needUpdate = false; 910 911 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 912 // already been set by the User thru the Disambiguation dialog 913 switch (userStatus) { 914 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 915 if (verified) { 916 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 917 } else { 918 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 919 } 920 needUpdate = true; 921 break; 922 923 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 924 if (verified) { 925 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 926 needUpdate = true; 927 } 928 break; 929 930 default: 931 // Nothing to do 932 } 933 934 if (needUpdate) { 935 mSettings.updateIntentFilterVerificationStatusLPw( 936 packageName, updatedStatus, userId); 937 scheduleWritePackageRestrictionsLocked(userId); 938 } 939 } 940 } 941 } 942 943 @Override 944 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 945 ActivityIntentInfo filter, String packageName) { 946 if (!hasValidDomains(filter)) { 947 return false; 948 } 949 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 950 if (ivs == null) { 951 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 952 packageName); 953 } 954 if (DEBUG_DOMAIN_VERIFICATION) { 955 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 956 } 957 ivs.addFilter(filter); 958 return true; 959 } 960 961 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 962 int userId, int verificationId, String packageName) { 963 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 964 verifierUid, userId, packageName); 965 ivs.setPendingState(); 966 synchronized (mPackages) { 967 mIntentFilterVerificationStates.append(verificationId, ivs); 968 mCurrentIntentFilterVerifications.add(verificationId); 969 } 970 return ivs; 971 } 972 } 973 974 private static boolean hasValidDomains(ActivityIntentInfo filter) { 975 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 976 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 977 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 978 } 979 980 // Set of pending broadcasts for aggregating enable/disable of components. 981 static class PendingPackageBroadcasts { 982 // for each user id, a map of <package name -> components within that package> 983 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 984 985 public PendingPackageBroadcasts() { 986 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 987 } 988 989 public ArrayList<String> get(int userId, String packageName) { 990 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 991 return packages.get(packageName); 992 } 993 994 public void put(int userId, String packageName, ArrayList<String> components) { 995 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 996 packages.put(packageName, components); 997 } 998 999 public void remove(int userId, String packageName) { 1000 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1001 if (packages != null) { 1002 packages.remove(packageName); 1003 } 1004 } 1005 1006 public void remove(int userId) { 1007 mUidMap.remove(userId); 1008 } 1009 1010 public int userIdCount() { 1011 return mUidMap.size(); 1012 } 1013 1014 public int userIdAt(int n) { 1015 return mUidMap.keyAt(n); 1016 } 1017 1018 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1019 return mUidMap.get(userId); 1020 } 1021 1022 public int size() { 1023 // total number of pending broadcast entries across all userIds 1024 int num = 0; 1025 for (int i = 0; i< mUidMap.size(); i++) { 1026 num += mUidMap.valueAt(i).size(); 1027 } 1028 return num; 1029 } 1030 1031 public void clear() { 1032 mUidMap.clear(); 1033 } 1034 1035 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1036 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1037 if (map == null) { 1038 map = new ArrayMap<String, ArrayList<String>>(); 1039 mUidMap.put(userId, map); 1040 } 1041 return map; 1042 } 1043 } 1044 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1045 1046 // Service Connection to remote media container service to copy 1047 // package uri's from external media onto secure containers 1048 // or internal storage. 1049 private IMediaContainerService mContainerService = null; 1050 1051 static final int SEND_PENDING_BROADCAST = 1; 1052 static final int MCS_BOUND = 3; 1053 static final int END_COPY = 4; 1054 static final int INIT_COPY = 5; 1055 static final int MCS_UNBIND = 6; 1056 static final int START_CLEANING_PACKAGE = 7; 1057 static final int FIND_INSTALL_LOC = 8; 1058 static final int POST_INSTALL = 9; 1059 static final int MCS_RECONNECT = 10; 1060 static final int MCS_GIVE_UP = 11; 1061 static final int UPDATED_MEDIA_STATUS = 12; 1062 static final int WRITE_SETTINGS = 13; 1063 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1064 static final int PACKAGE_VERIFIED = 15; 1065 static final int CHECK_PENDING_VERIFICATION = 16; 1066 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1067 static final int INTENT_FILTER_VERIFIED = 18; 1068 static final int WRITE_PACKAGE_LIST = 19; 1069 static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20; 1070 1071 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1072 1073 // Delay time in millisecs 1074 static final int BROADCAST_DELAY = 10 * 1000; 1075 1076 static UserManagerService sUserManager; 1077 1078 // Stores a list of users whose package restrictions file needs to be updated 1079 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1080 1081 final private DefaultContainerConnection mDefContainerConn = 1082 new DefaultContainerConnection(); 1083 class DefaultContainerConnection implements ServiceConnection { 1084 public void onServiceConnected(ComponentName name, IBinder service) { 1085 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1086 IMediaContainerService imcs = 1087 IMediaContainerService.Stub.asInterface(service); 1088 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1089 } 1090 1091 public void onServiceDisconnected(ComponentName name) { 1092 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1093 } 1094 } 1095 1096 // Recordkeeping of restore-after-install operations that are currently in flight 1097 // between the Package Manager and the Backup Manager 1098 static class PostInstallData { 1099 public InstallArgs args; 1100 public PackageInstalledInfo res; 1101 1102 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1103 args = _a; 1104 res = _r; 1105 } 1106 } 1107 1108 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1109 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1110 1111 // XML tags for backup/restore of various bits of state 1112 private static final String TAG_PREFERRED_BACKUP = "pa"; 1113 private static final String TAG_DEFAULT_APPS = "da"; 1114 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1115 1116 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1117 private static final String TAG_ALL_GRANTS = "rt-grants"; 1118 private static final String TAG_GRANT = "grant"; 1119 private static final String ATTR_PACKAGE_NAME = "pkg"; 1120 1121 private static final String TAG_PERMISSION = "perm"; 1122 private static final String ATTR_PERMISSION_NAME = "name"; 1123 private static final String ATTR_IS_GRANTED = "g"; 1124 private static final String ATTR_USER_SET = "set"; 1125 private static final String ATTR_USER_FIXED = "fixed"; 1126 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1127 1128 // System/policy permission grants are not backed up 1129 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1130 FLAG_PERMISSION_POLICY_FIXED 1131 | FLAG_PERMISSION_SYSTEM_FIXED 1132 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1133 1134 // And we back up these user-adjusted states 1135 private static final int USER_RUNTIME_GRANT_MASK = 1136 FLAG_PERMISSION_USER_SET 1137 | FLAG_PERMISSION_USER_FIXED 1138 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1139 1140 final @Nullable String mRequiredVerifierPackage; 1141 final @NonNull String mRequiredInstallerPackage; 1142 final @NonNull String mRequiredUninstallerPackage; 1143 final @Nullable String mSetupWizardPackage; 1144 final @Nullable String mStorageManagerPackage; 1145 final @NonNull String mServicesSystemSharedLibraryPackageName; 1146 final @NonNull String mSharedSystemSharedLibraryPackageName; 1147 1148 final boolean mPermissionReviewRequired; 1149 1150 private final PackageUsage mPackageUsage = new PackageUsage(); 1151 private final CompilerStats mCompilerStats = new CompilerStats(); 1152 1153 class PackageHandler extends Handler { 1154 private boolean mBound = false; 1155 final ArrayList<HandlerParams> mPendingInstalls = 1156 new ArrayList<HandlerParams>(); 1157 1158 private boolean connectToService() { 1159 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1160 " DefaultContainerService"); 1161 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1162 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1163 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1164 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1165 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1166 mBound = true; 1167 return true; 1168 } 1169 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1170 return false; 1171 } 1172 1173 private void disconnectService() { 1174 mContainerService = null; 1175 mBound = false; 1176 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1177 mContext.unbindService(mDefContainerConn); 1178 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1179 } 1180 1181 PackageHandler(Looper looper) { 1182 super(looper); 1183 } 1184 1185 public void handleMessage(Message msg) { 1186 try { 1187 doHandleMessage(msg); 1188 } finally { 1189 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1190 } 1191 } 1192 1193 void doHandleMessage(Message msg) { 1194 switch (msg.what) { 1195 case INIT_COPY: { 1196 HandlerParams params = (HandlerParams) msg.obj; 1197 int idx = mPendingInstalls.size(); 1198 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1199 // If a bind was already initiated we dont really 1200 // need to do anything. The pending install 1201 // will be processed later on. 1202 if (!mBound) { 1203 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1204 System.identityHashCode(mHandler)); 1205 // If this is the only one pending we might 1206 // have to bind to the service again. 1207 if (!connectToService()) { 1208 Slog.e(TAG, "Failed to bind to media container service"); 1209 params.serviceError(); 1210 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1211 System.identityHashCode(mHandler)); 1212 if (params.traceMethod != null) { 1213 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1214 params.traceCookie); 1215 } 1216 return; 1217 } else { 1218 // Once we bind to the service, the first 1219 // pending request will be processed. 1220 mPendingInstalls.add(idx, params); 1221 } 1222 } else { 1223 mPendingInstalls.add(idx, params); 1224 // Already bound to the service. Just make 1225 // sure we trigger off processing the first request. 1226 if (idx == 0) { 1227 mHandler.sendEmptyMessage(MCS_BOUND); 1228 } 1229 } 1230 break; 1231 } 1232 case MCS_BOUND: { 1233 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1234 if (msg.obj != null) { 1235 mContainerService = (IMediaContainerService) msg.obj; 1236 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1237 System.identityHashCode(mHandler)); 1238 } 1239 if (mContainerService == null) { 1240 if (!mBound) { 1241 // Something seriously wrong since we are not bound and we are not 1242 // waiting for connection. Bail out. 1243 Slog.e(TAG, "Cannot bind to media container service"); 1244 for (HandlerParams params : mPendingInstalls) { 1245 // Indicate service bind error 1246 params.serviceError(); 1247 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1248 System.identityHashCode(params)); 1249 if (params.traceMethod != null) { 1250 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1251 params.traceMethod, params.traceCookie); 1252 } 1253 return; 1254 } 1255 mPendingInstalls.clear(); 1256 } else { 1257 Slog.w(TAG, "Waiting to connect to media container service"); 1258 } 1259 } else if (mPendingInstalls.size() > 0) { 1260 HandlerParams params = mPendingInstalls.get(0); 1261 if (params != null) { 1262 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1263 System.identityHashCode(params)); 1264 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1265 if (params.startCopy()) { 1266 // We are done... look for more work or to 1267 // go idle. 1268 if (DEBUG_SD_INSTALL) Log.i(TAG, 1269 "Checking for more work or unbind..."); 1270 // Delete pending install 1271 if (mPendingInstalls.size() > 0) { 1272 mPendingInstalls.remove(0); 1273 } 1274 if (mPendingInstalls.size() == 0) { 1275 if (mBound) { 1276 if (DEBUG_SD_INSTALL) Log.i(TAG, 1277 "Posting delayed MCS_UNBIND"); 1278 removeMessages(MCS_UNBIND); 1279 Message ubmsg = obtainMessage(MCS_UNBIND); 1280 // Unbind after a little delay, to avoid 1281 // continual thrashing. 1282 sendMessageDelayed(ubmsg, 10000); 1283 } 1284 } else { 1285 // There are more pending requests in queue. 1286 // Just post MCS_BOUND message to trigger processing 1287 // of next pending install. 1288 if (DEBUG_SD_INSTALL) Log.i(TAG, 1289 "Posting MCS_BOUND for next work"); 1290 mHandler.sendEmptyMessage(MCS_BOUND); 1291 } 1292 } 1293 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1294 } 1295 } else { 1296 // Should never happen ideally. 1297 Slog.w(TAG, "Empty queue"); 1298 } 1299 break; 1300 } 1301 case MCS_RECONNECT: { 1302 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1303 if (mPendingInstalls.size() > 0) { 1304 if (mBound) { 1305 disconnectService(); 1306 } 1307 if (!connectToService()) { 1308 Slog.e(TAG, "Failed to bind to media container service"); 1309 for (HandlerParams params : mPendingInstalls) { 1310 // Indicate service bind error 1311 params.serviceError(); 1312 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1313 System.identityHashCode(params)); 1314 } 1315 mPendingInstalls.clear(); 1316 } 1317 } 1318 break; 1319 } 1320 case MCS_UNBIND: { 1321 // If there is no actual work left, then time to unbind. 1322 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1323 1324 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1325 if (mBound) { 1326 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1327 1328 disconnectService(); 1329 } 1330 } else if (mPendingInstalls.size() > 0) { 1331 // There are more pending requests in queue. 1332 // Just post MCS_BOUND message to trigger processing 1333 // of next pending install. 1334 mHandler.sendEmptyMessage(MCS_BOUND); 1335 } 1336 1337 break; 1338 } 1339 case MCS_GIVE_UP: { 1340 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1341 HandlerParams params = mPendingInstalls.remove(0); 1342 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1343 System.identityHashCode(params)); 1344 break; 1345 } 1346 case SEND_PENDING_BROADCAST: { 1347 String packages[]; 1348 ArrayList<String> components[]; 1349 int size = 0; 1350 int uids[]; 1351 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1352 synchronized (mPackages) { 1353 if (mPendingBroadcasts == null) { 1354 return; 1355 } 1356 size = mPendingBroadcasts.size(); 1357 if (size <= 0) { 1358 // Nothing to be done. Just return 1359 return; 1360 } 1361 packages = new String[size]; 1362 components = new ArrayList[size]; 1363 uids = new int[size]; 1364 int i = 0; // filling out the above arrays 1365 1366 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1367 int packageUserId = mPendingBroadcasts.userIdAt(n); 1368 Iterator<Map.Entry<String, ArrayList<String>>> it 1369 = mPendingBroadcasts.packagesForUserId(packageUserId) 1370 .entrySet().iterator(); 1371 while (it.hasNext() && i < size) { 1372 Map.Entry<String, ArrayList<String>> ent = it.next(); 1373 packages[i] = ent.getKey(); 1374 components[i] = ent.getValue(); 1375 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1376 uids[i] = (ps != null) 1377 ? UserHandle.getUid(packageUserId, ps.appId) 1378 : -1; 1379 i++; 1380 } 1381 } 1382 size = i; 1383 mPendingBroadcasts.clear(); 1384 } 1385 // Send broadcasts 1386 for (int i = 0; i < size; i++) { 1387 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1388 } 1389 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1390 break; 1391 } 1392 case START_CLEANING_PACKAGE: { 1393 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1394 final String packageName = (String)msg.obj; 1395 final int userId = msg.arg1; 1396 final boolean andCode = msg.arg2 != 0; 1397 synchronized (mPackages) { 1398 if (userId == UserHandle.USER_ALL) { 1399 int[] users = sUserManager.getUserIds(); 1400 for (int user : users) { 1401 mSettings.addPackageToCleanLPw( 1402 new PackageCleanItem(user, packageName, andCode)); 1403 } 1404 } else { 1405 mSettings.addPackageToCleanLPw( 1406 new PackageCleanItem(userId, packageName, andCode)); 1407 } 1408 } 1409 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1410 startCleaningPackages(); 1411 } break; 1412 case POST_INSTALL: { 1413 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1414 1415 PostInstallData data = mRunningInstalls.get(msg.arg1); 1416 final boolean didRestore = (msg.arg2 != 0); 1417 mRunningInstalls.delete(msg.arg1); 1418 1419 if (data != null) { 1420 InstallArgs args = data.args; 1421 PackageInstalledInfo parentRes = data.res; 1422 1423 final boolean grantPermissions = (args.installFlags 1424 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1425 final boolean killApp = (args.installFlags 1426 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1427 final String[] grantedPermissions = args.installGrantPermissions; 1428 1429 // Handle the parent package 1430 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1431 grantedPermissions, didRestore, args.installerPackageName, 1432 args.observer); 1433 1434 // Handle the child packages 1435 final int childCount = (parentRes.addedChildPackages != null) 1436 ? parentRes.addedChildPackages.size() : 0; 1437 for (int i = 0; i < childCount; i++) { 1438 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1439 handlePackagePostInstall(childRes, grantPermissions, killApp, 1440 grantedPermissions, false, args.installerPackageName, 1441 args.observer); 1442 } 1443 1444 // Log tracing if needed 1445 if (args.traceMethod != null) { 1446 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1447 args.traceCookie); 1448 } 1449 } else { 1450 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1451 } 1452 1453 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1454 } break; 1455 case UPDATED_MEDIA_STATUS: { 1456 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1457 boolean reportStatus = msg.arg1 == 1; 1458 boolean doGc = msg.arg2 == 1; 1459 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1460 if (doGc) { 1461 // Force a gc to clear up stale containers. 1462 Runtime.getRuntime().gc(); 1463 } 1464 if (msg.obj != null) { 1465 @SuppressWarnings("unchecked") 1466 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1467 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1468 // Unload containers 1469 unloadAllContainers(args); 1470 } 1471 if (reportStatus) { 1472 try { 1473 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1474 PackageHelper.getMountService().finishMediaUpdate(); 1475 } catch (RemoteException e) { 1476 Log.e(TAG, "MountService not running?"); 1477 } 1478 } 1479 } break; 1480 case WRITE_SETTINGS: { 1481 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1482 synchronized (mPackages) { 1483 removeMessages(WRITE_SETTINGS); 1484 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1485 mSettings.writeLPr(); 1486 mDirtyUsers.clear(); 1487 } 1488 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1489 } break; 1490 case WRITE_PACKAGE_RESTRICTIONS: { 1491 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1492 synchronized (mPackages) { 1493 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1494 for (int userId : mDirtyUsers) { 1495 mSettings.writePackageRestrictionsLPr(userId); 1496 } 1497 mDirtyUsers.clear(); 1498 } 1499 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1500 } break; 1501 case WRITE_PACKAGE_LIST: { 1502 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1503 synchronized (mPackages) { 1504 removeMessages(WRITE_PACKAGE_LIST); 1505 mSettings.writePackageListLPr(msg.arg1); 1506 } 1507 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1508 } break; 1509 case CHECK_PENDING_VERIFICATION: { 1510 final int verificationId = msg.arg1; 1511 final PackageVerificationState state = mPendingVerification.get(verificationId); 1512 1513 if ((state != null) && !state.timeoutExtended()) { 1514 final InstallArgs args = state.getInstallArgs(); 1515 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1516 1517 Slog.i(TAG, "Verification timed out for " + originUri); 1518 mPendingVerification.remove(verificationId); 1519 1520 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1521 1522 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1523 Slog.i(TAG, "Continuing with installation of " + originUri); 1524 state.setVerifierResponse(Binder.getCallingUid(), 1525 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1526 broadcastPackageVerified(verificationId, originUri, 1527 PackageManager.VERIFICATION_ALLOW, 1528 state.getInstallArgs().getUser()); 1529 try { 1530 ret = args.copyApk(mContainerService, true); 1531 } catch (RemoteException e) { 1532 Slog.e(TAG, "Could not contact the ContainerService"); 1533 } 1534 } else { 1535 broadcastPackageVerified(verificationId, originUri, 1536 PackageManager.VERIFICATION_REJECT, 1537 state.getInstallArgs().getUser()); 1538 } 1539 1540 Trace.asyncTraceEnd( 1541 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1542 1543 processPendingInstall(args, ret); 1544 mHandler.sendEmptyMessage(MCS_UNBIND); 1545 } 1546 break; 1547 } 1548 case PACKAGE_VERIFIED: { 1549 final int verificationId = msg.arg1; 1550 1551 final PackageVerificationState state = mPendingVerification.get(verificationId); 1552 if (state == null) { 1553 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1554 break; 1555 } 1556 1557 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1558 1559 state.setVerifierResponse(response.callerUid, response.code); 1560 1561 if (state.isVerificationComplete()) { 1562 mPendingVerification.remove(verificationId); 1563 1564 final InstallArgs args = state.getInstallArgs(); 1565 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1566 1567 int ret; 1568 if (state.isInstallAllowed()) { 1569 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1570 broadcastPackageVerified(verificationId, originUri, 1571 response.code, state.getInstallArgs().getUser()); 1572 try { 1573 ret = args.copyApk(mContainerService, true); 1574 } catch (RemoteException e) { 1575 Slog.e(TAG, "Could not contact the ContainerService"); 1576 } 1577 } else { 1578 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1579 } 1580 1581 Trace.asyncTraceEnd( 1582 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1583 1584 processPendingInstall(args, ret); 1585 mHandler.sendEmptyMessage(MCS_UNBIND); 1586 } 1587 1588 break; 1589 } 1590 case START_INTENT_FILTER_VERIFICATIONS: { 1591 IFVerificationParams params = (IFVerificationParams) msg.obj; 1592 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1593 params.replacing, params.pkg); 1594 break; 1595 } 1596 case INTENT_FILTER_VERIFIED: { 1597 final int verificationId = msg.arg1; 1598 1599 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1600 verificationId); 1601 if (state == null) { 1602 Slog.w(TAG, "Invalid IntentFilter verification token " 1603 + verificationId + " received"); 1604 break; 1605 } 1606 1607 final int userId = state.getUserId(); 1608 1609 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1610 "Processing IntentFilter verification with token:" 1611 + verificationId + " and userId:" + userId); 1612 1613 final IntentFilterVerificationResponse response = 1614 (IntentFilterVerificationResponse) msg.obj; 1615 1616 state.setVerifierResponse(response.callerUid, response.code); 1617 1618 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1619 "IntentFilter verification with token:" + verificationId 1620 + " and userId:" + userId 1621 + " is settings verifier response with response code:" 1622 + response.code); 1623 1624 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1625 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1626 + response.getFailedDomainsString()); 1627 } 1628 1629 if (state.isVerificationComplete()) { 1630 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1631 } else { 1632 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1633 "IntentFilter verification with token:" + verificationId 1634 + " was not said to be complete"); 1635 } 1636 1637 break; 1638 } 1639 case EPHEMERAL_RESOLUTION_PHASE_TWO: { 1640 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1641 mEphemeralResolverConnection, 1642 (EphemeralRequest) msg.obj, 1643 mEphemeralInstallerActivity, 1644 mHandler); 1645 } 1646 } 1647 } 1648 } 1649 1650 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1651 boolean killApp, String[] grantedPermissions, 1652 boolean launchedForRestore, String installerPackage, 1653 IPackageInstallObserver2 installObserver) { 1654 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1655 // Send the removed broadcasts 1656 if (res.removedInfo != null) { 1657 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1658 } 1659 1660 // Now that we successfully installed the package, grant runtime 1661 // permissions if requested before broadcasting the install. 1662 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1663 >= Build.VERSION_CODES.M) { 1664 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1665 } 1666 1667 final boolean update = res.removedInfo != null 1668 && res.removedInfo.removedPackage != null; 1669 1670 // If this is the first time we have child packages for a disabled privileged 1671 // app that had no children, we grant requested runtime permissions to the new 1672 // children if the parent on the system image had them already granted. 1673 if (res.pkg.parentPackage != null) { 1674 synchronized (mPackages) { 1675 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1676 } 1677 } 1678 1679 synchronized (mPackages) { 1680 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1681 } 1682 1683 final String packageName = res.pkg.applicationInfo.packageName; 1684 1685 // Determine the set of users who are adding this package for 1686 // the first time vs. those who are seeing an update. 1687 int[] firstUsers = EMPTY_INT_ARRAY; 1688 int[] updateUsers = EMPTY_INT_ARRAY; 1689 if (res.origUsers == null || res.origUsers.length == 0) { 1690 firstUsers = res.newUsers; 1691 } else { 1692 for (int newUser : res.newUsers) { 1693 boolean isNew = true; 1694 for (int origUser : res.origUsers) { 1695 if (origUser == newUser) { 1696 isNew = false; 1697 break; 1698 } 1699 } 1700 if (isNew) { 1701 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1702 } else { 1703 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1704 } 1705 } 1706 } 1707 1708 // Send installed broadcasts if the install/update is not ephemeral 1709 if (!isEphemeral(res.pkg)) { 1710 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1711 1712 // Send added for users that see the package for the first time 1713 // sendPackageAddedForNewUsers also deals with system apps 1714 int appId = UserHandle.getAppId(res.uid); 1715 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1716 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1717 1718 // Send added for users that don't see the package for the first time 1719 Bundle extras = new Bundle(1); 1720 extras.putInt(Intent.EXTRA_UID, res.uid); 1721 if (update) { 1722 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1723 } 1724 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1725 extras, 0 /*flags*/, null /*targetPackage*/, 1726 null /*finishedReceiver*/, updateUsers); 1727 1728 // Send replaced for users that don't see the package for the first time 1729 if (update) { 1730 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1731 packageName, extras, 0 /*flags*/, 1732 null /*targetPackage*/, null /*finishedReceiver*/, 1733 updateUsers); 1734 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1735 null /*package*/, null /*extras*/, 0 /*flags*/, 1736 packageName /*targetPackage*/, 1737 null /*finishedReceiver*/, updateUsers); 1738 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1739 // First-install and we did a restore, so we're responsible for the 1740 // first-launch broadcast. 1741 if (DEBUG_BACKUP) { 1742 Slog.i(TAG, "Post-restore of " + packageName 1743 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1744 } 1745 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1746 } 1747 1748 // Send broadcast package appeared if forward locked/external for all users 1749 // treat asec-hosted packages like removable media on upgrade 1750 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1751 if (DEBUG_INSTALL) { 1752 Slog.i(TAG, "upgrading pkg " + res.pkg 1753 + " is ASEC-hosted -> AVAILABLE"); 1754 } 1755 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1756 ArrayList<String> pkgList = new ArrayList<>(1); 1757 pkgList.add(packageName); 1758 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1759 } 1760 } 1761 1762 // Work that needs to happen on first install within each user 1763 if (firstUsers != null && firstUsers.length > 0) { 1764 synchronized (mPackages) { 1765 for (int userId : firstUsers) { 1766 // If this app is a browser and it's newly-installed for some 1767 // users, clear any default-browser state in those users. The 1768 // app's nature doesn't depend on the user, so we can just check 1769 // its browser nature in any user and generalize. 1770 if (packageIsBrowser(packageName, userId)) { 1771 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1772 } 1773 1774 // We may also need to apply pending (restored) runtime 1775 // permission grants within these users. 1776 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1777 } 1778 } 1779 } 1780 1781 // Log current value of "unknown sources" setting 1782 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1783 getUnknownSourcesSettings()); 1784 1785 // Force a gc to clear up things 1786 Runtime.getRuntime().gc(); 1787 1788 // Remove the replaced package's older resources safely now 1789 // We delete after a gc for applications on sdcard. 1790 if (res.removedInfo != null && res.removedInfo.args != null) { 1791 synchronized (mInstallLock) { 1792 res.removedInfo.args.doPostDeleteLI(true); 1793 } 1794 } 1795 } 1796 1797 // If someone is watching installs - notify them 1798 if (installObserver != null) { 1799 try { 1800 Bundle extras = extrasForInstallResult(res); 1801 installObserver.onPackageInstalled(res.name, res.returnCode, 1802 res.returnMsg, extras); 1803 } catch (RemoteException e) { 1804 Slog.i(TAG, "Observer no longer exists."); 1805 } 1806 } 1807 } 1808 1809 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1810 PackageParser.Package pkg) { 1811 if (pkg.parentPackage == null) { 1812 return; 1813 } 1814 if (pkg.requestedPermissions == null) { 1815 return; 1816 } 1817 final PackageSetting disabledSysParentPs = mSettings 1818 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1819 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1820 || !disabledSysParentPs.isPrivileged() 1821 || (disabledSysParentPs.childPackageNames != null 1822 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1823 return; 1824 } 1825 final int[] allUserIds = sUserManager.getUserIds(); 1826 final int permCount = pkg.requestedPermissions.size(); 1827 for (int i = 0; i < permCount; i++) { 1828 String permission = pkg.requestedPermissions.get(i); 1829 BasePermission bp = mSettings.mPermissions.get(permission); 1830 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1831 continue; 1832 } 1833 for (int userId : allUserIds) { 1834 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1835 permission, userId)) { 1836 grantRuntimePermission(pkg.packageName, permission, userId); 1837 } 1838 } 1839 } 1840 } 1841 1842 private StorageEventListener mStorageListener = new StorageEventListener() { 1843 @Override 1844 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1845 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1846 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1847 final String volumeUuid = vol.getFsUuid(); 1848 1849 // Clean up any users or apps that were removed or recreated 1850 // while this volume was missing 1851 reconcileUsers(volumeUuid); 1852 reconcileApps(volumeUuid); 1853 1854 // Clean up any install sessions that expired or were 1855 // cancelled while this volume was missing 1856 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1857 1858 loadPrivatePackages(vol); 1859 1860 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1861 unloadPrivatePackages(vol); 1862 } 1863 } 1864 1865 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1866 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1867 updateExternalMediaStatus(true, false); 1868 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1869 updateExternalMediaStatus(false, false); 1870 } 1871 } 1872 } 1873 1874 @Override 1875 public void onVolumeForgotten(String fsUuid) { 1876 if (TextUtils.isEmpty(fsUuid)) { 1877 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1878 return; 1879 } 1880 1881 // Remove any apps installed on the forgotten volume 1882 synchronized (mPackages) { 1883 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1884 for (PackageSetting ps : packages) { 1885 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1886 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1887 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1888 } 1889 1890 mSettings.onVolumeForgotten(fsUuid); 1891 mSettings.writeLPr(); 1892 } 1893 } 1894 }; 1895 1896 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1897 String[] grantedPermissions) { 1898 for (int userId : userIds) { 1899 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1900 } 1901 1902 // We could have touched GID membership, so flush out packages.list 1903 synchronized (mPackages) { 1904 mSettings.writePackageListLPr(); 1905 } 1906 } 1907 1908 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1909 String[] grantedPermissions) { 1910 SettingBase sb = (SettingBase) pkg.mExtras; 1911 if (sb == null) { 1912 return; 1913 } 1914 1915 PermissionsState permissionsState = sb.getPermissionsState(); 1916 1917 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1918 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1919 1920 for (String permission : pkg.requestedPermissions) { 1921 final BasePermission bp; 1922 synchronized (mPackages) { 1923 bp = mSettings.mPermissions.get(permission); 1924 } 1925 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1926 && (grantedPermissions == null 1927 || ArrayUtils.contains(grantedPermissions, permission))) { 1928 final int flags = permissionsState.getPermissionFlags(permission, userId); 1929 // Installer cannot change immutable permissions. 1930 if ((flags & immutableFlags) == 0) { 1931 grantRuntimePermission(pkg.packageName, permission, userId); 1932 } 1933 } 1934 } 1935 } 1936 1937 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1938 Bundle extras = null; 1939 switch (res.returnCode) { 1940 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1941 extras = new Bundle(); 1942 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1943 res.origPermission); 1944 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1945 res.origPackage); 1946 break; 1947 } 1948 case PackageManager.INSTALL_SUCCEEDED: { 1949 extras = new Bundle(); 1950 extras.putBoolean(Intent.EXTRA_REPLACING, 1951 res.removedInfo != null && res.removedInfo.removedPackage != null); 1952 break; 1953 } 1954 } 1955 return extras; 1956 } 1957 1958 void scheduleWriteSettingsLocked() { 1959 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1960 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1961 } 1962 } 1963 1964 void scheduleWritePackageListLocked(int userId) { 1965 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 1966 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 1967 msg.arg1 = userId; 1968 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 1969 } 1970 } 1971 1972 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1973 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1974 scheduleWritePackageRestrictionsLocked(userId); 1975 } 1976 1977 void scheduleWritePackageRestrictionsLocked(int userId) { 1978 final int[] userIds = (userId == UserHandle.USER_ALL) 1979 ? sUserManager.getUserIds() : new int[]{userId}; 1980 for (int nextUserId : userIds) { 1981 if (!sUserManager.exists(nextUserId)) return; 1982 mDirtyUsers.add(nextUserId); 1983 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1984 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1985 } 1986 } 1987 } 1988 1989 public static PackageManagerService main(Context context, Installer installer, 1990 boolean factoryTest, boolean onlyCore) { 1991 // Self-check for initial settings. 1992 PackageManagerServiceCompilerMapping.checkProperties(); 1993 1994 PackageManagerService m = new PackageManagerService(context, installer, 1995 factoryTest, onlyCore); 1996 m.enableSystemUserPackages(); 1997 ServiceManager.addService("package", m); 1998 return m; 1999 } 2000 2001 private void enableSystemUserPackages() { 2002 if (!UserManager.isSplitSystemUser()) { 2003 return; 2004 } 2005 // For system user, enable apps based on the following conditions: 2006 // - app is whitelisted or belong to one of these groups: 2007 // -- system app which has no launcher icons 2008 // -- system app which has INTERACT_ACROSS_USERS permission 2009 // -- system IME app 2010 // - app is not in the blacklist 2011 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2012 Set<String> enableApps = new ArraySet<>(); 2013 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2014 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2015 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2016 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2017 enableApps.addAll(wlApps); 2018 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2019 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2020 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2021 enableApps.removeAll(blApps); 2022 Log.i(TAG, "Applications installed for system user: " + enableApps); 2023 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2024 UserHandle.SYSTEM); 2025 final int allAppsSize = allAps.size(); 2026 synchronized (mPackages) { 2027 for (int i = 0; i < allAppsSize; i++) { 2028 String pName = allAps.get(i); 2029 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2030 // Should not happen, but we shouldn't be failing if it does 2031 if (pkgSetting == null) { 2032 continue; 2033 } 2034 boolean install = enableApps.contains(pName); 2035 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2036 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2037 + " for system user"); 2038 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2039 } 2040 } 2041 } 2042 } 2043 2044 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2045 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2046 Context.DISPLAY_SERVICE); 2047 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2048 } 2049 2050 /** 2051 * Requests that files preopted on a secondary system partition be copied to the data partition 2052 * if possible. Note that the actual copying of the files is accomplished by init for security 2053 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2054 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2055 */ 2056 private static void requestCopyPreoptedFiles() { 2057 final int WAIT_TIME_MS = 100; 2058 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2059 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2060 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2061 // We will wait for up to 100 seconds. 2062 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2063 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2064 try { 2065 Thread.sleep(WAIT_TIME_MS); 2066 } catch (InterruptedException e) { 2067 // Do nothing 2068 } 2069 if (SystemClock.uptimeMillis() > timeEnd) { 2070 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2071 Slog.wtf(TAG, "cppreopt did not finish!"); 2072 break; 2073 } 2074 } 2075 } 2076 } 2077 2078 public PackageManagerService(Context context, Installer installer, 2079 boolean factoryTest, boolean onlyCore) { 2080 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2081 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2082 SystemClock.uptimeMillis()); 2083 2084 if (mSdkVersion <= 0) { 2085 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2086 } 2087 2088 mContext = context; 2089 2090 mPermissionReviewRequired = context.getResources().getBoolean( 2091 R.bool.config_permissionReviewRequired); 2092 2093 mFactoryTest = factoryTest; 2094 mOnlyCore = onlyCore; 2095 mMetrics = new DisplayMetrics(); 2096 mSettings = new Settings(mPackages); 2097 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2098 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2099 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2100 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2101 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2102 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2103 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2104 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2105 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2106 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2107 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2108 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2109 2110 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2111 if (separateProcesses != null && separateProcesses.length() > 0) { 2112 if ("*".equals(separateProcesses)) { 2113 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2114 mSeparateProcesses = null; 2115 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2116 } else { 2117 mDefParseFlags = 0; 2118 mSeparateProcesses = separateProcesses.split(","); 2119 Slog.w(TAG, "Running with debug.separate_processes: " 2120 + separateProcesses); 2121 } 2122 } else { 2123 mDefParseFlags = 0; 2124 mSeparateProcesses = null; 2125 } 2126 2127 mInstaller = installer; 2128 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2129 "*dexopt*"); 2130 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2131 2132 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2133 FgThread.get().getLooper()); 2134 2135 getDefaultDisplayMetrics(context, mMetrics); 2136 2137 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2138 SystemConfig systemConfig = SystemConfig.getInstance(); 2139 mGlobalGids = systemConfig.getGlobalGids(); 2140 mSystemPermissions = systemConfig.getSystemPermissions(); 2141 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2142 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2143 2144 mProtectedPackages = new ProtectedPackages(mContext); 2145 2146 synchronized (mInstallLock) { 2147 // writer 2148 synchronized (mPackages) { 2149 mHandlerThread = new ServiceThread(TAG, 2150 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2151 mHandlerThread.start(); 2152 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2153 mProcessLoggingHandler = new ProcessLoggingHandler(); 2154 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2155 2156 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2157 2158 File dataDir = Environment.getDataDirectory(); 2159 mAppInstallDir = new File(dataDir, "app"); 2160 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2161 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2162 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2163 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2164 2165 sUserManager = new UserManagerService(context, this, mPackages); 2166 2167 // Propagate permission configuration in to package manager. 2168 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2169 = systemConfig.getPermissions(); 2170 for (int i=0; i<permConfig.size(); i++) { 2171 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2172 BasePermission bp = mSettings.mPermissions.get(perm.name); 2173 if (bp == null) { 2174 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2175 mSettings.mPermissions.put(perm.name, bp); 2176 } 2177 if (perm.gids != null) { 2178 bp.setGids(perm.gids, perm.perUser); 2179 } 2180 } 2181 2182 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2183 for (int i=0; i<libConfig.size(); i++) { 2184 mSharedLibraries.put(libConfig.keyAt(i), 2185 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2186 } 2187 2188 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2189 2190 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2191 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2192 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2193 2194 if (mFirstBoot) { 2195 requestCopyPreoptedFiles(); 2196 } 2197 2198 String customResolverActivity = Resources.getSystem().getString( 2199 R.string.config_customResolverActivity); 2200 if (TextUtils.isEmpty(customResolverActivity)) { 2201 customResolverActivity = null; 2202 } else { 2203 mCustomResolverComponentName = ComponentName.unflattenFromString( 2204 customResolverActivity); 2205 } 2206 2207 long startTime = SystemClock.uptimeMillis(); 2208 2209 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2210 startTime); 2211 2212 // Set flag to monitor and not change apk file paths when 2213 // scanning install directories. 2214 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2215 2216 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2217 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2218 2219 if (bootClassPath == null) { 2220 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2221 } 2222 2223 if (systemServerClassPath == null) { 2224 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2225 } 2226 2227 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2228 final String[] dexCodeInstructionSets = 2229 getDexCodeInstructionSets( 2230 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2231 2232 /** 2233 * Ensure all external libraries have had dexopt run on them. 2234 */ 2235 if (mSharedLibraries.size() > 0) { 2236 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2237 // NOTE: For now, we're compiling these system "shared libraries" 2238 // (and framework jars) into all available architectures. It's possible 2239 // to compile them only when we come across an app that uses them (there's 2240 // already logic for that in scanPackageLI) but that adds some complexity. 2241 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2242 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2243 final String lib = libEntry.path; 2244 if (lib == null) { 2245 continue; 2246 } 2247 2248 try { 2249 // Shared libraries do not have profiles so we perform a full 2250 // AOT compilation (if needed). 2251 int dexoptNeeded = DexFile.getDexOptNeeded( 2252 lib, dexCodeInstructionSet, 2253 getCompilerFilterForReason(REASON_SHARED_APK), 2254 false /* newProfile */); 2255 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2256 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2257 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2258 getCompilerFilterForReason(REASON_SHARED_APK), 2259 StorageManager.UUID_PRIVATE_INTERNAL, 2260 SKIP_SHARED_LIBRARY_CHECK); 2261 } 2262 } catch (FileNotFoundException e) { 2263 Slog.w(TAG, "Library not found: " + lib); 2264 } catch (IOException | InstallerException e) { 2265 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2266 + e.getMessage()); 2267 } 2268 } 2269 } 2270 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2271 } 2272 2273 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2274 2275 final VersionInfo ver = mSettings.getInternalVersion(); 2276 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2277 2278 // when upgrading from pre-M, promote system app permissions from install to runtime 2279 mPromoteSystemApps = 2280 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2281 2282 // When upgrading from pre-N, we need to handle package extraction like first boot, 2283 // as there is no profiling data available. 2284 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2285 2286 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2287 2288 // save off the names of pre-existing system packages prior to scanning; we don't 2289 // want to automatically grant runtime permissions for new system apps 2290 if (mPromoteSystemApps) { 2291 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2292 while (pkgSettingIter.hasNext()) { 2293 PackageSetting ps = pkgSettingIter.next(); 2294 if (isSystemApp(ps)) { 2295 mExistingSystemPackages.add(ps.name); 2296 } 2297 } 2298 } 2299 2300 // Collect vendor overlay packages. (Do this before scanning any apps.) 2301 // For security and version matching reason, only consider 2302 // overlay packages if they reside in the right directory. 2303 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2304 if (overlayThemeDir.isEmpty()) { 2305 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2306 } 2307 if (!overlayThemeDir.isEmpty()) { 2308 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2309 | PackageParser.PARSE_IS_SYSTEM 2310 | PackageParser.PARSE_IS_SYSTEM_DIR 2311 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2312 } 2313 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2314 | PackageParser.PARSE_IS_SYSTEM 2315 | PackageParser.PARSE_IS_SYSTEM_DIR 2316 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2317 2318 // Find base frameworks (resource packages without code). 2319 scanDirTracedLI(frameworkDir, mDefParseFlags 2320 | PackageParser.PARSE_IS_SYSTEM 2321 | PackageParser.PARSE_IS_SYSTEM_DIR 2322 | PackageParser.PARSE_IS_PRIVILEGED, 2323 scanFlags | SCAN_NO_DEX, 0); 2324 2325 // Collected privileged system packages. 2326 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2327 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2328 | PackageParser.PARSE_IS_SYSTEM 2329 | PackageParser.PARSE_IS_SYSTEM_DIR 2330 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2331 2332 // Collect ordinary system packages. 2333 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2334 scanDirTracedLI(systemAppDir, mDefParseFlags 2335 | PackageParser.PARSE_IS_SYSTEM 2336 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2337 2338 // Collect all vendor packages. 2339 File vendorAppDir = new File("/vendor/app"); 2340 try { 2341 vendorAppDir = vendorAppDir.getCanonicalFile(); 2342 } catch (IOException e) { 2343 // failed to look up canonical path, continue with original one 2344 } 2345 scanDirTracedLI(vendorAppDir, mDefParseFlags 2346 | PackageParser.PARSE_IS_SYSTEM 2347 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2348 2349 // Collect all OEM packages. 2350 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2351 scanDirTracedLI(oemAppDir, mDefParseFlags 2352 | PackageParser.PARSE_IS_SYSTEM 2353 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2354 2355 // Prune any system packages that no longer exist. 2356 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2357 if (!mOnlyCore) { 2358 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2359 while (psit.hasNext()) { 2360 PackageSetting ps = psit.next(); 2361 2362 /* 2363 * If this is not a system app, it can't be a 2364 * disable system app. 2365 */ 2366 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2367 continue; 2368 } 2369 2370 /* 2371 * If the package is scanned, it's not erased. 2372 */ 2373 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2374 if (scannedPkg != null) { 2375 /* 2376 * If the system app is both scanned and in the 2377 * disabled packages list, then it must have been 2378 * added via OTA. Remove it from the currently 2379 * scanned package so the previously user-installed 2380 * application can be scanned. 2381 */ 2382 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2383 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2384 + ps.name + "; removing system app. Last known codePath=" 2385 + ps.codePathString + ", installStatus=" + ps.installStatus 2386 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2387 + scannedPkg.mVersionCode); 2388 removePackageLI(scannedPkg, true); 2389 mExpectingBetter.put(ps.name, ps.codePath); 2390 } 2391 2392 continue; 2393 } 2394 2395 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2396 psit.remove(); 2397 logCriticalInfo(Log.WARN, "System package " + ps.name 2398 + " no longer exists; it's data will be wiped"); 2399 // Actual deletion of code and data will be handled by later 2400 // reconciliation step 2401 } else { 2402 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2403 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2404 possiblyDeletedUpdatedSystemApps.add(ps.name); 2405 } 2406 } 2407 } 2408 } 2409 2410 //look for any incomplete package installations 2411 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2412 for (int i = 0; i < deletePkgsList.size(); i++) { 2413 // Actual deletion of code and data will be handled by later 2414 // reconciliation step 2415 final String packageName = deletePkgsList.get(i).name; 2416 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2417 synchronized (mPackages) { 2418 mSettings.removePackageLPw(packageName); 2419 } 2420 } 2421 2422 //delete tmp files 2423 deleteTempPackageFiles(); 2424 2425 // Remove any shared userIDs that have no associated packages 2426 mSettings.pruneSharedUsersLPw(); 2427 2428 if (!mOnlyCore) { 2429 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2430 SystemClock.uptimeMillis()); 2431 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2432 2433 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2434 | PackageParser.PARSE_FORWARD_LOCK, 2435 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2436 2437 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2438 | PackageParser.PARSE_IS_EPHEMERAL, 2439 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2440 2441 /** 2442 * Remove disable package settings for any updated system 2443 * apps that were removed via an OTA. If they're not a 2444 * previously-updated app, remove them completely. 2445 * Otherwise, just revoke their system-level permissions. 2446 */ 2447 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2448 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2449 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2450 2451 String msg; 2452 if (deletedPkg == null) { 2453 msg = "Updated system package " + deletedAppName 2454 + " no longer exists; it's data will be wiped"; 2455 // Actual deletion of code and data will be handled by later 2456 // reconciliation step 2457 } else { 2458 msg = "Updated system app + " + deletedAppName 2459 + " no longer present; removing system privileges for " 2460 + deletedAppName; 2461 2462 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2463 2464 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2465 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2466 } 2467 logCriticalInfo(Log.WARN, msg); 2468 } 2469 2470 /** 2471 * Make sure all system apps that we expected to appear on 2472 * the userdata partition actually showed up. If they never 2473 * appeared, crawl back and revive the system version. 2474 */ 2475 for (int i = 0; i < mExpectingBetter.size(); i++) { 2476 final String packageName = mExpectingBetter.keyAt(i); 2477 if (!mPackages.containsKey(packageName)) { 2478 final File scanFile = mExpectingBetter.valueAt(i); 2479 2480 logCriticalInfo(Log.WARN, "Expected better " + packageName 2481 + " but never showed up; reverting to system"); 2482 2483 int reparseFlags = mDefParseFlags; 2484 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2485 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2486 | PackageParser.PARSE_IS_SYSTEM_DIR 2487 | PackageParser.PARSE_IS_PRIVILEGED; 2488 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2489 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2490 | PackageParser.PARSE_IS_SYSTEM_DIR; 2491 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2492 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2493 | PackageParser.PARSE_IS_SYSTEM_DIR; 2494 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2495 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2496 | PackageParser.PARSE_IS_SYSTEM_DIR; 2497 } else { 2498 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2499 continue; 2500 } 2501 2502 mSettings.enableSystemPackageLPw(packageName); 2503 2504 try { 2505 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2506 } catch (PackageManagerException e) { 2507 Slog.e(TAG, "Failed to parse original system package: " 2508 + e.getMessage()); 2509 } 2510 } 2511 } 2512 } 2513 mExpectingBetter.clear(); 2514 2515 // Resolve the storage manager. 2516 mStorageManagerPackage = getStorageManagerPackageName(); 2517 2518 // Resolve protected action filters. Only the setup wizard is allowed to 2519 // have a high priority filter for these actions. 2520 mSetupWizardPackage = getSetupWizardPackageName(); 2521 if (mProtectedFilters.size() > 0) { 2522 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2523 Slog.i(TAG, "No setup wizard;" 2524 + " All protected intents capped to priority 0"); 2525 } 2526 for (ActivityIntentInfo filter : mProtectedFilters) { 2527 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2528 if (DEBUG_FILTERS) { 2529 Slog.i(TAG, "Found setup wizard;" 2530 + " allow priority " + filter.getPriority() + ";" 2531 + " package: " + filter.activity.info.packageName 2532 + " activity: " + filter.activity.className 2533 + " priority: " + filter.getPriority()); 2534 } 2535 // skip setup wizard; allow it to keep the high priority filter 2536 continue; 2537 } 2538 Slog.w(TAG, "Protected action; cap priority to 0;" 2539 + " package: " + filter.activity.info.packageName 2540 + " activity: " + filter.activity.className 2541 + " origPrio: " + filter.getPriority()); 2542 filter.setPriority(0); 2543 } 2544 } 2545 mDeferProtectedFilters = false; 2546 mProtectedFilters.clear(); 2547 2548 // Now that we know all of the shared libraries, update all clients to have 2549 // the correct library paths. 2550 updateAllSharedLibrariesLPw(); 2551 2552 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2553 // NOTE: We ignore potential failures here during a system scan (like 2554 // the rest of the commands above) because there's precious little we 2555 // can do about it. A settings error is reported, though. 2556 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2557 } 2558 2559 // Now that we know all the packages we are keeping, 2560 // read and update their last usage times. 2561 mPackageUsage.read(mPackages); 2562 mCompilerStats.read(); 2563 2564 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2565 SystemClock.uptimeMillis()); 2566 Slog.i(TAG, "Time to scan packages: " 2567 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2568 + " seconds"); 2569 2570 // If the platform SDK has changed since the last time we booted, 2571 // we need to re-grant app permission to catch any new ones that 2572 // appear. This is really a hack, and means that apps can in some 2573 // cases get permissions that the user didn't initially explicitly 2574 // allow... it would be nice to have some better way to handle 2575 // this situation. 2576 int updateFlags = UPDATE_PERMISSIONS_ALL; 2577 if (ver.sdkVersion != mSdkVersion) { 2578 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2579 + mSdkVersion + "; regranting permissions for internal storage"); 2580 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2581 } 2582 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2583 ver.sdkVersion = mSdkVersion; 2584 2585 // If this is the first boot or an update from pre-M, and it is a normal 2586 // boot, then we need to initialize the default preferred apps across 2587 // all defined users. 2588 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2589 for (UserInfo user : sUserManager.getUsers(true)) { 2590 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2591 applyFactoryDefaultBrowserLPw(user.id); 2592 primeDomainVerificationsLPw(user.id); 2593 } 2594 } 2595 2596 // Prepare storage for system user really early during boot, 2597 // since core system apps like SettingsProvider and SystemUI 2598 // can't wait for user to start 2599 final int storageFlags; 2600 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2601 storageFlags = StorageManager.FLAG_STORAGE_DE; 2602 } else { 2603 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2604 } 2605 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2606 storageFlags, true /* migrateAppData */); 2607 2608 // If this is first boot after an OTA, and a normal boot, then 2609 // we need to clear code cache directories. 2610 // Note that we do *not* clear the application profiles. These remain valid 2611 // across OTAs and are used to drive profile verification (post OTA) and 2612 // profile compilation (without waiting to collect a fresh set of profiles). 2613 if (mIsUpgrade && !onlyCore) { 2614 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2615 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2616 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2617 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2618 // No apps are running this early, so no need to freeze 2619 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2620 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2621 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2622 } 2623 } 2624 ver.fingerprint = Build.FINGERPRINT; 2625 } 2626 2627 checkDefaultBrowser(); 2628 2629 // clear only after permissions and other defaults have been updated 2630 mExistingSystemPackages.clear(); 2631 mPromoteSystemApps = false; 2632 2633 // All the changes are done during package scanning. 2634 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2635 2636 // can downgrade to reader 2637 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2638 mSettings.writeLPr(); 2639 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2640 2641 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2642 // early on (before the package manager declares itself as early) because other 2643 // components in the system server might ask for package contexts for these apps. 2644 // 2645 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2646 // (i.e, that the data partition is unavailable). 2647 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2648 long start = System.nanoTime(); 2649 List<PackageParser.Package> coreApps = new ArrayList<>(); 2650 for (PackageParser.Package pkg : mPackages.values()) { 2651 if (pkg.coreApp) { 2652 coreApps.add(pkg); 2653 } 2654 } 2655 2656 int[] stats = performDexOptUpgrade(coreApps, false, 2657 getCompilerFilterForReason(REASON_CORE_APP)); 2658 2659 final int elapsedTimeSeconds = 2660 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2661 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2662 2663 if (DEBUG_DEXOPT) { 2664 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2665 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2666 } 2667 2668 2669 // TODO: Should we log these stats to tron too ? 2670 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2671 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2672 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2673 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2674 } 2675 2676 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2677 SystemClock.uptimeMillis()); 2678 2679 if (!mOnlyCore) { 2680 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2681 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2682 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2683 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2684 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2685 mIntentFilterVerifierComponent); 2686 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2687 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2688 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2689 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2690 } else { 2691 mRequiredVerifierPackage = null; 2692 mRequiredInstallerPackage = null; 2693 mRequiredUninstallerPackage = null; 2694 mIntentFilterVerifierComponent = null; 2695 mIntentFilterVerifier = null; 2696 mServicesSystemSharedLibraryPackageName = null; 2697 mSharedSystemSharedLibraryPackageName = null; 2698 } 2699 2700 mInstallerService = new PackageInstallerService(context, this); 2701 2702 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2703 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2704 // both the installer and resolver must be present to enable ephemeral 2705 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2706 if (DEBUG_EPHEMERAL) { 2707 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2708 + " installer:" + ephemeralInstallerComponent); 2709 } 2710 mEphemeralResolverComponent = ephemeralResolverComponent; 2711 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2712 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2713 mEphemeralResolverConnection = 2714 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2715 } else { 2716 if (DEBUG_EPHEMERAL) { 2717 final String missingComponent = 2718 (ephemeralResolverComponent == null) 2719 ? (ephemeralInstallerComponent == null) 2720 ? "resolver and installer" 2721 : "resolver" 2722 : "installer"; 2723 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2724 } 2725 mEphemeralResolverComponent = null; 2726 mEphemeralInstallerComponent = null; 2727 mEphemeralResolverConnection = null; 2728 } 2729 2730 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2731 } // synchronized (mPackages) 2732 } // synchronized (mInstallLock) 2733 2734 // Now after opening every single application zip, make sure they 2735 // are all flushed. Not really needed, but keeps things nice and 2736 // tidy. 2737 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2738 Runtime.getRuntime().gc(); 2739 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2740 2741 // The initial scanning above does many calls into installd while 2742 // holding the mPackages lock, but we're mostly interested in yelling 2743 // once we have a booted system. 2744 mInstaller.setWarnIfHeld(mPackages); 2745 2746 // Expose private service for system components to use. 2747 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2748 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2749 } 2750 2751 @Override 2752 public boolean isFirstBoot() { 2753 return mFirstBoot; 2754 } 2755 2756 @Override 2757 public boolean isOnlyCoreApps() { 2758 return mOnlyCore; 2759 } 2760 2761 @Override 2762 public boolean isUpgrade() { 2763 return mIsUpgrade; 2764 } 2765 2766 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2767 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2768 2769 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2770 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2771 UserHandle.USER_SYSTEM); 2772 if (matches.size() == 1) { 2773 return matches.get(0).getComponentInfo().packageName; 2774 } else if (matches.size() == 0) { 2775 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2776 return null; 2777 } 2778 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2779 } 2780 2781 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2782 synchronized (mPackages) { 2783 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2784 if (libraryEntry == null) { 2785 throw new IllegalStateException("Missing required shared library:" + libraryName); 2786 } 2787 return libraryEntry.apk; 2788 } 2789 } 2790 2791 private @NonNull String getRequiredInstallerLPr() { 2792 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2793 intent.addCategory(Intent.CATEGORY_DEFAULT); 2794 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2795 2796 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2797 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2798 UserHandle.USER_SYSTEM); 2799 if (matches.size() == 1) { 2800 ResolveInfo resolveInfo = matches.get(0); 2801 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2802 throw new RuntimeException("The installer must be a privileged app"); 2803 } 2804 return matches.get(0).getComponentInfo().packageName; 2805 } else { 2806 throw new RuntimeException("There must be exactly one installer; found " + matches); 2807 } 2808 } 2809 2810 private @NonNull String getRequiredUninstallerLPr() { 2811 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2812 intent.addCategory(Intent.CATEGORY_DEFAULT); 2813 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2814 2815 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2816 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2817 UserHandle.USER_SYSTEM); 2818 if (resolveInfo == null || 2819 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2820 throw new RuntimeException("There must be exactly one uninstaller; found " 2821 + resolveInfo); 2822 } 2823 return resolveInfo.getComponentInfo().packageName; 2824 } 2825 2826 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2827 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2828 2829 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2830 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2831 UserHandle.USER_SYSTEM); 2832 ResolveInfo best = null; 2833 final int N = matches.size(); 2834 for (int i = 0; i < N; i++) { 2835 final ResolveInfo cur = matches.get(i); 2836 final String packageName = cur.getComponentInfo().packageName; 2837 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2838 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2839 continue; 2840 } 2841 2842 if (best == null || cur.priority > best.priority) { 2843 best = cur; 2844 } 2845 } 2846 2847 if (best != null) { 2848 return best.getComponentInfo().getComponentName(); 2849 } else { 2850 throw new RuntimeException("There must be at least one intent filter verifier"); 2851 } 2852 } 2853 2854 private @Nullable ComponentName getEphemeralResolverLPr() { 2855 final String[] packageArray = 2856 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2857 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2858 if (DEBUG_EPHEMERAL) { 2859 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2860 } 2861 return null; 2862 } 2863 2864 final int resolveFlags = 2865 MATCH_DIRECT_BOOT_AWARE 2866 | MATCH_DIRECT_BOOT_UNAWARE 2867 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2868 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2869 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2870 resolveFlags, UserHandle.USER_SYSTEM); 2871 2872 final int N = resolvers.size(); 2873 if (N == 0) { 2874 if (DEBUG_EPHEMERAL) { 2875 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2876 } 2877 return null; 2878 } 2879 2880 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2881 for (int i = 0; i < N; i++) { 2882 final ResolveInfo info = resolvers.get(i); 2883 2884 if (info.serviceInfo == null) { 2885 continue; 2886 } 2887 2888 final String packageName = info.serviceInfo.packageName; 2889 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2890 if (DEBUG_EPHEMERAL) { 2891 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2892 + " pkg: " + packageName + ", info:" + info); 2893 } 2894 continue; 2895 } 2896 2897 if (DEBUG_EPHEMERAL) { 2898 Slog.v(TAG, "Ephemeral resolver found;" 2899 + " pkg: " + packageName + ", info:" + info); 2900 } 2901 return new ComponentName(packageName, info.serviceInfo.name); 2902 } 2903 if (DEBUG_EPHEMERAL) { 2904 Slog.v(TAG, "Ephemeral resolver NOT found"); 2905 } 2906 return null; 2907 } 2908 2909 private @Nullable ComponentName getEphemeralInstallerLPr() { 2910 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2911 intent.addCategory(Intent.CATEGORY_DEFAULT); 2912 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2913 2914 final int resolveFlags = 2915 MATCH_DIRECT_BOOT_AWARE 2916 | MATCH_DIRECT_BOOT_UNAWARE 2917 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2918 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2919 resolveFlags, UserHandle.USER_SYSTEM); 2920 if (matches.size() == 0) { 2921 return null; 2922 } else if (matches.size() == 1) { 2923 return matches.get(0).getComponentInfo().getComponentName(); 2924 } else { 2925 throw new RuntimeException( 2926 "There must be at most one ephemeral installer; found " + matches); 2927 } 2928 } 2929 2930 private void primeDomainVerificationsLPw(int userId) { 2931 if (DEBUG_DOMAIN_VERIFICATION) { 2932 Slog.d(TAG, "Priming domain verifications in user " + userId); 2933 } 2934 2935 SystemConfig systemConfig = SystemConfig.getInstance(); 2936 ArraySet<String> packages = systemConfig.getLinkedApps(); 2937 2938 for (String packageName : packages) { 2939 PackageParser.Package pkg = mPackages.get(packageName); 2940 if (pkg != null) { 2941 if (!pkg.isSystemApp()) { 2942 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2943 continue; 2944 } 2945 2946 ArraySet<String> domains = null; 2947 for (PackageParser.Activity a : pkg.activities) { 2948 for (ActivityIntentInfo filter : a.intents) { 2949 if (hasValidDomains(filter)) { 2950 if (domains == null) { 2951 domains = new ArraySet<String>(); 2952 } 2953 domains.addAll(filter.getHostsList()); 2954 } 2955 } 2956 } 2957 2958 if (domains != null && domains.size() > 0) { 2959 if (DEBUG_DOMAIN_VERIFICATION) { 2960 Slog.v(TAG, " + " + packageName); 2961 } 2962 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2963 // state w.r.t. the formal app-linkage "no verification attempted" state; 2964 // and then 'always' in the per-user state actually used for intent resolution. 2965 final IntentFilterVerificationInfo ivi; 2966 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 2967 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2968 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2969 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2970 } else { 2971 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2972 + "' does not handle web links"); 2973 } 2974 } else { 2975 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2976 } 2977 } 2978 2979 scheduleWritePackageRestrictionsLocked(userId); 2980 scheduleWriteSettingsLocked(); 2981 } 2982 2983 private void applyFactoryDefaultBrowserLPw(int userId) { 2984 // The default browser app's package name is stored in a string resource, 2985 // with a product-specific overlay used for vendor customization. 2986 String browserPkg = mContext.getResources().getString( 2987 com.android.internal.R.string.default_browser); 2988 if (!TextUtils.isEmpty(browserPkg)) { 2989 // non-empty string => required to be a known package 2990 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2991 if (ps == null) { 2992 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2993 browserPkg = null; 2994 } else { 2995 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2996 } 2997 } 2998 2999 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3000 // default. If there's more than one, just leave everything alone. 3001 if (browserPkg == null) { 3002 calculateDefaultBrowserLPw(userId); 3003 } 3004 } 3005 3006 private void calculateDefaultBrowserLPw(int userId) { 3007 List<String> allBrowsers = resolveAllBrowserApps(userId); 3008 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3009 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3010 } 3011 3012 private List<String> resolveAllBrowserApps(int userId) { 3013 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3014 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3015 PackageManager.MATCH_ALL, userId); 3016 3017 final int count = list.size(); 3018 List<String> result = new ArrayList<String>(count); 3019 for (int i=0; i<count; i++) { 3020 ResolveInfo info = list.get(i); 3021 if (info.activityInfo == null 3022 || !info.handleAllWebDataURI 3023 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3024 || result.contains(info.activityInfo.packageName)) { 3025 continue; 3026 } 3027 result.add(info.activityInfo.packageName); 3028 } 3029 3030 return result; 3031 } 3032 3033 private boolean packageIsBrowser(String packageName, int userId) { 3034 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3035 PackageManager.MATCH_ALL, userId); 3036 final int N = list.size(); 3037 for (int i = 0; i < N; i++) { 3038 ResolveInfo info = list.get(i); 3039 if (packageName.equals(info.activityInfo.packageName)) { 3040 return true; 3041 } 3042 } 3043 return false; 3044 } 3045 3046 private void checkDefaultBrowser() { 3047 final int myUserId = UserHandle.myUserId(); 3048 final String packageName = getDefaultBrowserPackageName(myUserId); 3049 if (packageName != null) { 3050 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3051 if (info == null) { 3052 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3053 synchronized (mPackages) { 3054 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3055 } 3056 } 3057 } 3058 } 3059 3060 @Override 3061 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3062 throws RemoteException { 3063 try { 3064 return super.onTransact(code, data, reply, flags); 3065 } catch (RuntimeException e) { 3066 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3067 Slog.wtf(TAG, "Package Manager Crash", e); 3068 } 3069 throw e; 3070 } 3071 } 3072 3073 static int[] appendInts(int[] cur, int[] add) { 3074 if (add == null) return cur; 3075 if (cur == null) return add; 3076 final int N = add.length; 3077 for (int i=0; i<N; i++) { 3078 cur = appendInt(cur, add[i]); 3079 } 3080 return cur; 3081 } 3082 3083 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3084 if (!sUserManager.exists(userId)) return null; 3085 if (ps == null) { 3086 return null; 3087 } 3088 final PackageParser.Package p = ps.pkg; 3089 if (p == null) { 3090 return null; 3091 } 3092 3093 final PermissionsState permissionsState = ps.getPermissionsState(); 3094 3095 // Compute GIDs only if requested 3096 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3097 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3098 // Compute granted permissions only if package has requested permissions 3099 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3100 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3101 final PackageUserState state = ps.readUserState(userId); 3102 3103 return PackageParser.generatePackageInfo(p, gids, flags, 3104 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3105 } 3106 3107 @Override 3108 public void checkPackageStartable(String packageName, int userId) { 3109 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3110 3111 synchronized (mPackages) { 3112 final PackageSetting ps = mSettings.mPackages.get(packageName); 3113 if (ps == null) { 3114 throw new SecurityException("Package " + packageName + " was not found!"); 3115 } 3116 3117 if (!ps.getInstalled(userId)) { 3118 throw new SecurityException( 3119 "Package " + packageName + " was not installed for user " + userId + "!"); 3120 } 3121 3122 if (mSafeMode && !ps.isSystem()) { 3123 throw new SecurityException("Package " + packageName + " not a system app!"); 3124 } 3125 3126 if (mFrozenPackages.contains(packageName)) { 3127 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3128 } 3129 3130 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3131 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3132 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3133 } 3134 } 3135 } 3136 3137 @Override 3138 public boolean isPackageAvailable(String packageName, int userId) { 3139 if (!sUserManager.exists(userId)) return false; 3140 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3141 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3142 synchronized (mPackages) { 3143 PackageParser.Package p = mPackages.get(packageName); 3144 if (p != null) { 3145 final PackageSetting ps = (PackageSetting) p.mExtras; 3146 if (ps != null) { 3147 final PackageUserState state = ps.readUserState(userId); 3148 if (state != null) { 3149 return PackageParser.isAvailable(state); 3150 } 3151 } 3152 } 3153 } 3154 return false; 3155 } 3156 3157 @Override 3158 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3159 if (!sUserManager.exists(userId)) return null; 3160 flags = updateFlagsForPackage(flags, userId, packageName); 3161 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3162 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3163 // reader 3164 synchronized (mPackages) { 3165 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3166 PackageParser.Package p = null; 3167 if (matchFactoryOnly) { 3168 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3169 if (ps != null) { 3170 return generatePackageInfo(ps, flags, userId); 3171 } 3172 } 3173 if (p == null) { 3174 p = mPackages.get(packageName); 3175 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3176 return null; 3177 } 3178 } 3179 if (DEBUG_PACKAGE_INFO) 3180 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3181 if (p != null) { 3182 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3183 } 3184 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3185 final PackageSetting ps = mSettings.mPackages.get(packageName); 3186 return generatePackageInfo(ps, flags, userId); 3187 } 3188 } 3189 return null; 3190 } 3191 3192 @Override 3193 public String[] currentToCanonicalPackageNames(String[] names) { 3194 String[] out = new String[names.length]; 3195 // reader 3196 synchronized (mPackages) { 3197 for (int i=names.length-1; i>=0; i--) { 3198 PackageSetting ps = mSettings.mPackages.get(names[i]); 3199 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3200 } 3201 } 3202 return out; 3203 } 3204 3205 @Override 3206 public String[] canonicalToCurrentPackageNames(String[] names) { 3207 String[] out = new String[names.length]; 3208 // reader 3209 synchronized (mPackages) { 3210 for (int i=names.length-1; i>=0; i--) { 3211 String cur = mSettings.getRenamedPackageLPr(names[i]); 3212 out[i] = cur != null ? cur : names[i]; 3213 } 3214 } 3215 return out; 3216 } 3217 3218 @Override 3219 public int getPackageUid(String packageName, int flags, int userId) { 3220 if (!sUserManager.exists(userId)) return -1; 3221 flags = updateFlagsForPackage(flags, userId, packageName); 3222 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3223 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3224 3225 // reader 3226 synchronized (mPackages) { 3227 final PackageParser.Package p = mPackages.get(packageName); 3228 if (p != null && p.isMatch(flags)) { 3229 return UserHandle.getUid(userId, p.applicationInfo.uid); 3230 } 3231 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3232 final PackageSetting ps = mSettings.mPackages.get(packageName); 3233 if (ps != null && ps.isMatch(flags)) { 3234 return UserHandle.getUid(userId, ps.appId); 3235 } 3236 } 3237 } 3238 3239 return -1; 3240 } 3241 3242 @Override 3243 public int[] getPackageGids(String packageName, int flags, int userId) { 3244 if (!sUserManager.exists(userId)) return null; 3245 flags = updateFlagsForPackage(flags, userId, packageName); 3246 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3247 false /* requireFullPermission */, false /* checkShell */, 3248 "getPackageGids"); 3249 3250 // reader 3251 synchronized (mPackages) { 3252 final PackageParser.Package p = mPackages.get(packageName); 3253 if (p != null && p.isMatch(flags)) { 3254 PackageSetting ps = (PackageSetting) p.mExtras; 3255 return ps.getPermissionsState().computeGids(userId); 3256 } 3257 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3258 final PackageSetting ps = mSettings.mPackages.get(packageName); 3259 if (ps != null && ps.isMatch(flags)) { 3260 return ps.getPermissionsState().computeGids(userId); 3261 } 3262 } 3263 } 3264 3265 return null; 3266 } 3267 3268 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3269 if (bp.perm != null) { 3270 return PackageParser.generatePermissionInfo(bp.perm, flags); 3271 } 3272 PermissionInfo pi = new PermissionInfo(); 3273 pi.name = bp.name; 3274 pi.packageName = bp.sourcePackage; 3275 pi.nonLocalizedLabel = bp.name; 3276 pi.protectionLevel = bp.protectionLevel; 3277 return pi; 3278 } 3279 3280 @Override 3281 public PermissionInfo getPermissionInfo(String name, int flags) { 3282 // reader 3283 synchronized (mPackages) { 3284 final BasePermission p = mSettings.mPermissions.get(name); 3285 if (p != null) { 3286 return generatePermissionInfo(p, flags); 3287 } 3288 return null; 3289 } 3290 } 3291 3292 @Override 3293 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3294 int flags) { 3295 // reader 3296 synchronized (mPackages) { 3297 if (group != null && !mPermissionGroups.containsKey(group)) { 3298 // This is thrown as NameNotFoundException 3299 return null; 3300 } 3301 3302 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3303 for (BasePermission p : mSettings.mPermissions.values()) { 3304 if (group == null) { 3305 if (p.perm == null || p.perm.info.group == null) { 3306 out.add(generatePermissionInfo(p, flags)); 3307 } 3308 } else { 3309 if (p.perm != null && group.equals(p.perm.info.group)) { 3310 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3311 } 3312 } 3313 } 3314 return new ParceledListSlice<>(out); 3315 } 3316 } 3317 3318 @Override 3319 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3320 // reader 3321 synchronized (mPackages) { 3322 return PackageParser.generatePermissionGroupInfo( 3323 mPermissionGroups.get(name), flags); 3324 } 3325 } 3326 3327 @Override 3328 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3329 // reader 3330 synchronized (mPackages) { 3331 final int N = mPermissionGroups.size(); 3332 ArrayList<PermissionGroupInfo> out 3333 = new ArrayList<PermissionGroupInfo>(N); 3334 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3335 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3336 } 3337 return new ParceledListSlice<>(out); 3338 } 3339 } 3340 3341 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3342 int userId) { 3343 if (!sUserManager.exists(userId)) return null; 3344 PackageSetting ps = mSettings.mPackages.get(packageName); 3345 if (ps != null) { 3346 if (ps.pkg == null) { 3347 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3348 if (pInfo != null) { 3349 return pInfo.applicationInfo; 3350 } 3351 return null; 3352 } 3353 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3354 ps.readUserState(userId), userId); 3355 } 3356 return null; 3357 } 3358 3359 @Override 3360 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3361 if (!sUserManager.exists(userId)) return null; 3362 flags = updateFlagsForApplication(flags, userId, packageName); 3363 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3364 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3365 // writer 3366 synchronized (mPackages) { 3367 PackageParser.Package p = mPackages.get(packageName); 3368 if (DEBUG_PACKAGE_INFO) Log.v( 3369 TAG, "getApplicationInfo " + packageName 3370 + ": " + p); 3371 if (p != null) { 3372 PackageSetting ps = mSettings.mPackages.get(packageName); 3373 if (ps == null) return null; 3374 // Note: isEnabledLP() does not apply here - always return info 3375 return PackageParser.generateApplicationInfo( 3376 p, flags, ps.readUserState(userId), userId); 3377 } 3378 if ("android".equals(packageName)||"system".equals(packageName)) { 3379 return mAndroidApplication; 3380 } 3381 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3382 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3383 } 3384 } 3385 return null; 3386 } 3387 3388 @Override 3389 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3390 final IPackageDataObserver observer) { 3391 mContext.enforceCallingOrSelfPermission( 3392 android.Manifest.permission.CLEAR_APP_CACHE, null); 3393 // Queue up an async operation since clearing cache may take a little while. 3394 mHandler.post(new Runnable() { 3395 public void run() { 3396 mHandler.removeCallbacks(this); 3397 boolean success = true; 3398 synchronized (mInstallLock) { 3399 try { 3400 mInstaller.freeCache(volumeUuid, freeStorageSize); 3401 } catch (InstallerException e) { 3402 Slog.w(TAG, "Couldn't clear application caches: " + e); 3403 success = false; 3404 } 3405 } 3406 if (observer != null) { 3407 try { 3408 observer.onRemoveCompleted(null, success); 3409 } catch (RemoteException e) { 3410 Slog.w(TAG, "RemoveException when invoking call back"); 3411 } 3412 } 3413 } 3414 }); 3415 } 3416 3417 @Override 3418 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3419 final IntentSender pi) { 3420 mContext.enforceCallingOrSelfPermission( 3421 android.Manifest.permission.CLEAR_APP_CACHE, null); 3422 // Queue up an async operation since clearing cache may take a little while. 3423 mHandler.post(new Runnable() { 3424 public void run() { 3425 mHandler.removeCallbacks(this); 3426 boolean success = true; 3427 synchronized (mInstallLock) { 3428 try { 3429 mInstaller.freeCache(volumeUuid, freeStorageSize); 3430 } catch (InstallerException e) { 3431 Slog.w(TAG, "Couldn't clear application caches: " + e); 3432 success = false; 3433 } 3434 } 3435 if(pi != null) { 3436 try { 3437 // Callback via pending intent 3438 int code = success ? 1 : 0; 3439 pi.sendIntent(null, code, null, 3440 null, null); 3441 } catch (SendIntentException e1) { 3442 Slog.i(TAG, "Failed to send pending intent"); 3443 } 3444 } 3445 } 3446 }); 3447 } 3448 3449 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3450 synchronized (mInstallLock) { 3451 try { 3452 mInstaller.freeCache(volumeUuid, freeStorageSize); 3453 } catch (InstallerException e) { 3454 throw new IOException("Failed to free enough space", e); 3455 } 3456 } 3457 } 3458 3459 /** 3460 * Update given flags based on encryption status of current user. 3461 */ 3462 private int updateFlags(int flags, int userId) { 3463 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3464 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3465 // Caller expressed an explicit opinion about what encryption 3466 // aware/unaware components they want to see, so fall through and 3467 // give them what they want 3468 } else { 3469 // Caller expressed no opinion, so match based on user state 3470 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3471 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3472 } else { 3473 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3474 } 3475 } 3476 return flags; 3477 } 3478 3479 private UserManagerInternal getUserManagerInternal() { 3480 if (mUserManagerInternal == null) { 3481 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3482 } 3483 return mUserManagerInternal; 3484 } 3485 3486 /** 3487 * Update given flags when being used to request {@link PackageInfo}. 3488 */ 3489 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3490 boolean triaged = true; 3491 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3492 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3493 // Caller is asking for component details, so they'd better be 3494 // asking for specific encryption matching behavior, or be triaged 3495 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3496 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3497 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3498 triaged = false; 3499 } 3500 } 3501 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3502 | PackageManager.MATCH_SYSTEM_ONLY 3503 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3504 triaged = false; 3505 } 3506 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3507 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3508 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3509 } 3510 return updateFlags(flags, userId); 3511 } 3512 3513 /** 3514 * Update given flags when being used to request {@link ApplicationInfo}. 3515 */ 3516 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3517 return updateFlagsForPackage(flags, userId, cookie); 3518 } 3519 3520 /** 3521 * Update given flags when being used to request {@link ComponentInfo}. 3522 */ 3523 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3524 if (cookie instanceof Intent) { 3525 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3526 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3527 } 3528 } 3529 3530 boolean triaged = true; 3531 // Caller is asking for component details, so they'd better be 3532 // asking for specific encryption matching behavior, or be triaged 3533 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3534 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3535 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3536 triaged = false; 3537 } 3538 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3539 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3540 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3541 } 3542 3543 return updateFlags(flags, userId); 3544 } 3545 3546 /** 3547 * Update given flags when being used to request {@link ResolveInfo}. 3548 */ 3549 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3550 // Safe mode means we shouldn't match any third-party components 3551 if (mSafeMode) { 3552 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3553 } 3554 3555 return updateFlagsForComponent(flags, userId, cookie); 3556 } 3557 3558 @Override 3559 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3560 if (!sUserManager.exists(userId)) return null; 3561 flags = updateFlagsForComponent(flags, userId, component); 3562 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3563 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3564 synchronized (mPackages) { 3565 PackageParser.Activity a = mActivities.mActivities.get(component); 3566 3567 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3568 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3569 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3570 if (ps == null) return null; 3571 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3572 userId); 3573 } 3574 if (mResolveComponentName.equals(component)) { 3575 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3576 new PackageUserState(), userId); 3577 } 3578 } 3579 return null; 3580 } 3581 3582 @Override 3583 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3584 String resolvedType) { 3585 synchronized (mPackages) { 3586 if (component.equals(mResolveComponentName)) { 3587 // The resolver supports EVERYTHING! 3588 return true; 3589 } 3590 PackageParser.Activity a = mActivities.mActivities.get(component); 3591 if (a == null) { 3592 return false; 3593 } 3594 for (int i=0; i<a.intents.size(); i++) { 3595 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3596 intent.getData(), intent.getCategories(), TAG) >= 0) { 3597 return true; 3598 } 3599 } 3600 return false; 3601 } 3602 } 3603 3604 @Override 3605 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3606 if (!sUserManager.exists(userId)) return null; 3607 flags = updateFlagsForComponent(flags, userId, component); 3608 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3609 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3610 synchronized (mPackages) { 3611 PackageParser.Activity a = mReceivers.mActivities.get(component); 3612 if (DEBUG_PACKAGE_INFO) Log.v( 3613 TAG, "getReceiverInfo " + component + ": " + a); 3614 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3615 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3616 if (ps == null) return null; 3617 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3618 userId); 3619 } 3620 } 3621 return null; 3622 } 3623 3624 @Override 3625 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3626 if (!sUserManager.exists(userId)) return null; 3627 flags = updateFlagsForComponent(flags, userId, component); 3628 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3629 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3630 synchronized (mPackages) { 3631 PackageParser.Service s = mServices.mServices.get(component); 3632 if (DEBUG_PACKAGE_INFO) Log.v( 3633 TAG, "getServiceInfo " + component + ": " + s); 3634 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3635 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3636 if (ps == null) return null; 3637 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3638 userId); 3639 } 3640 } 3641 return null; 3642 } 3643 3644 @Override 3645 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3646 if (!sUserManager.exists(userId)) return null; 3647 flags = updateFlagsForComponent(flags, userId, component); 3648 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3649 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3650 synchronized (mPackages) { 3651 PackageParser.Provider p = mProviders.mProviders.get(component); 3652 if (DEBUG_PACKAGE_INFO) Log.v( 3653 TAG, "getProviderInfo " + component + ": " + p); 3654 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3655 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3656 if (ps == null) return null; 3657 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3658 userId); 3659 } 3660 } 3661 return null; 3662 } 3663 3664 @Override 3665 public String[] getSystemSharedLibraryNames() { 3666 Set<String> libSet; 3667 synchronized (mPackages) { 3668 libSet = mSharedLibraries.keySet(); 3669 int size = libSet.size(); 3670 if (size > 0) { 3671 String[] libs = new String[size]; 3672 libSet.toArray(libs); 3673 return libs; 3674 } 3675 } 3676 return null; 3677 } 3678 3679 @Override 3680 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3681 synchronized (mPackages) { 3682 return mServicesSystemSharedLibraryPackageName; 3683 } 3684 } 3685 3686 @Override 3687 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3688 synchronized (mPackages) { 3689 return mSharedSystemSharedLibraryPackageName; 3690 } 3691 } 3692 3693 @Override 3694 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3695 synchronized (mPackages) { 3696 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3697 3698 final FeatureInfo fi = new FeatureInfo(); 3699 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3700 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3701 res.add(fi); 3702 3703 return new ParceledListSlice<>(res); 3704 } 3705 } 3706 3707 @Override 3708 public boolean hasSystemFeature(String name, int version) { 3709 synchronized (mPackages) { 3710 final FeatureInfo feat = mAvailableFeatures.get(name); 3711 if (feat == null) { 3712 return false; 3713 } else { 3714 return feat.version >= version; 3715 } 3716 } 3717 } 3718 3719 @Override 3720 public int checkPermission(String permName, String pkgName, int userId) { 3721 if (!sUserManager.exists(userId)) { 3722 return PackageManager.PERMISSION_DENIED; 3723 } 3724 3725 synchronized (mPackages) { 3726 final PackageParser.Package p = mPackages.get(pkgName); 3727 if (p != null && p.mExtras != null) { 3728 final PackageSetting ps = (PackageSetting) p.mExtras; 3729 final PermissionsState permissionsState = ps.getPermissionsState(); 3730 if (permissionsState.hasPermission(permName, userId)) { 3731 return PackageManager.PERMISSION_GRANTED; 3732 } 3733 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3734 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3735 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3736 return PackageManager.PERMISSION_GRANTED; 3737 } 3738 } 3739 } 3740 3741 return PackageManager.PERMISSION_DENIED; 3742 } 3743 3744 @Override 3745 public int checkUidPermission(String permName, int uid) { 3746 final int userId = UserHandle.getUserId(uid); 3747 3748 if (!sUserManager.exists(userId)) { 3749 return PackageManager.PERMISSION_DENIED; 3750 } 3751 3752 synchronized (mPackages) { 3753 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3754 if (obj != null) { 3755 final SettingBase ps = (SettingBase) obj; 3756 final PermissionsState permissionsState = ps.getPermissionsState(); 3757 if (permissionsState.hasPermission(permName, userId)) { 3758 return PackageManager.PERMISSION_GRANTED; 3759 } 3760 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3761 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3762 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3763 return PackageManager.PERMISSION_GRANTED; 3764 } 3765 } else { 3766 ArraySet<String> perms = mSystemPermissions.get(uid); 3767 if (perms != null) { 3768 if (perms.contains(permName)) { 3769 return PackageManager.PERMISSION_GRANTED; 3770 } 3771 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3772 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3773 return PackageManager.PERMISSION_GRANTED; 3774 } 3775 } 3776 } 3777 } 3778 3779 return PackageManager.PERMISSION_DENIED; 3780 } 3781 3782 @Override 3783 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3784 if (UserHandle.getCallingUserId() != userId) { 3785 mContext.enforceCallingPermission( 3786 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3787 "isPermissionRevokedByPolicy for user " + userId); 3788 } 3789 3790 if (checkPermission(permission, packageName, userId) 3791 == PackageManager.PERMISSION_GRANTED) { 3792 return false; 3793 } 3794 3795 final long identity = Binder.clearCallingIdentity(); 3796 try { 3797 final int flags = getPermissionFlags(permission, packageName, userId); 3798 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3799 } finally { 3800 Binder.restoreCallingIdentity(identity); 3801 } 3802 } 3803 3804 @Override 3805 public String getPermissionControllerPackageName() { 3806 synchronized (mPackages) { 3807 return mRequiredInstallerPackage; 3808 } 3809 } 3810 3811 /** 3812 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3813 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3814 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3815 * @param message the message to log on security exception 3816 */ 3817 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3818 boolean checkShell, String message) { 3819 if (userId < 0) { 3820 throw new IllegalArgumentException("Invalid userId " + userId); 3821 } 3822 if (checkShell) { 3823 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3824 } 3825 if (userId == UserHandle.getUserId(callingUid)) return; 3826 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3827 if (requireFullPermission) { 3828 mContext.enforceCallingOrSelfPermission( 3829 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3830 } else { 3831 try { 3832 mContext.enforceCallingOrSelfPermission( 3833 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3834 } catch (SecurityException se) { 3835 mContext.enforceCallingOrSelfPermission( 3836 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3837 } 3838 } 3839 } 3840 } 3841 3842 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3843 if (callingUid == Process.SHELL_UID) { 3844 if (userHandle >= 0 3845 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3846 throw new SecurityException("Shell does not have permission to access user " 3847 + userHandle); 3848 } else if (userHandle < 0) { 3849 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3850 + Debug.getCallers(3)); 3851 } 3852 } 3853 } 3854 3855 private BasePermission findPermissionTreeLP(String permName) { 3856 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3857 if (permName.startsWith(bp.name) && 3858 permName.length() > bp.name.length() && 3859 permName.charAt(bp.name.length()) == '.') { 3860 return bp; 3861 } 3862 } 3863 return null; 3864 } 3865 3866 private BasePermission checkPermissionTreeLP(String permName) { 3867 if (permName != null) { 3868 BasePermission bp = findPermissionTreeLP(permName); 3869 if (bp != null) { 3870 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3871 return bp; 3872 } 3873 throw new SecurityException("Calling uid " 3874 + Binder.getCallingUid() 3875 + " is not allowed to add to permission tree " 3876 + bp.name + " owned by uid " + bp.uid); 3877 } 3878 } 3879 throw new SecurityException("No permission tree found for " + permName); 3880 } 3881 3882 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3883 if (s1 == null) { 3884 return s2 == null; 3885 } 3886 if (s2 == null) { 3887 return false; 3888 } 3889 if (s1.getClass() != s2.getClass()) { 3890 return false; 3891 } 3892 return s1.equals(s2); 3893 } 3894 3895 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3896 if (pi1.icon != pi2.icon) return false; 3897 if (pi1.logo != pi2.logo) return false; 3898 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3899 if (!compareStrings(pi1.name, pi2.name)) return false; 3900 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3901 // We'll take care of setting this one. 3902 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3903 // These are not currently stored in settings. 3904 //if (!compareStrings(pi1.group, pi2.group)) return false; 3905 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3906 //if (pi1.labelRes != pi2.labelRes) return false; 3907 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3908 return true; 3909 } 3910 3911 int permissionInfoFootprint(PermissionInfo info) { 3912 int size = info.name.length(); 3913 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3914 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3915 return size; 3916 } 3917 3918 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3919 int size = 0; 3920 for (BasePermission perm : mSettings.mPermissions.values()) { 3921 if (perm.uid == tree.uid) { 3922 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3923 } 3924 } 3925 return size; 3926 } 3927 3928 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3929 // We calculate the max size of permissions defined by this uid and throw 3930 // if that plus the size of 'info' would exceed our stated maximum. 3931 if (tree.uid != Process.SYSTEM_UID) { 3932 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3933 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3934 throw new SecurityException("Permission tree size cap exceeded"); 3935 } 3936 } 3937 } 3938 3939 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3940 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3941 throw new SecurityException("Label must be specified in permission"); 3942 } 3943 BasePermission tree = checkPermissionTreeLP(info.name); 3944 BasePermission bp = mSettings.mPermissions.get(info.name); 3945 boolean added = bp == null; 3946 boolean changed = true; 3947 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3948 if (added) { 3949 enforcePermissionCapLocked(info, tree); 3950 bp = new BasePermission(info.name, tree.sourcePackage, 3951 BasePermission.TYPE_DYNAMIC); 3952 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3953 throw new SecurityException( 3954 "Not allowed to modify non-dynamic permission " 3955 + info.name); 3956 } else { 3957 if (bp.protectionLevel == fixedLevel 3958 && bp.perm.owner.equals(tree.perm.owner) 3959 && bp.uid == tree.uid 3960 && comparePermissionInfos(bp.perm.info, info)) { 3961 changed = false; 3962 } 3963 } 3964 bp.protectionLevel = fixedLevel; 3965 info = new PermissionInfo(info); 3966 info.protectionLevel = fixedLevel; 3967 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3968 bp.perm.info.packageName = tree.perm.info.packageName; 3969 bp.uid = tree.uid; 3970 if (added) { 3971 mSettings.mPermissions.put(info.name, bp); 3972 } 3973 if (changed) { 3974 if (!async) { 3975 mSettings.writeLPr(); 3976 } else { 3977 scheduleWriteSettingsLocked(); 3978 } 3979 } 3980 return added; 3981 } 3982 3983 @Override 3984 public boolean addPermission(PermissionInfo info) { 3985 synchronized (mPackages) { 3986 return addPermissionLocked(info, false); 3987 } 3988 } 3989 3990 @Override 3991 public boolean addPermissionAsync(PermissionInfo info) { 3992 synchronized (mPackages) { 3993 return addPermissionLocked(info, true); 3994 } 3995 } 3996 3997 @Override 3998 public void removePermission(String name) { 3999 synchronized (mPackages) { 4000 checkPermissionTreeLP(name); 4001 BasePermission bp = mSettings.mPermissions.get(name); 4002 if (bp != null) { 4003 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4004 throw new SecurityException( 4005 "Not allowed to modify non-dynamic permission " 4006 + name); 4007 } 4008 mSettings.mPermissions.remove(name); 4009 mSettings.writeLPr(); 4010 } 4011 } 4012 } 4013 4014 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4015 BasePermission bp) { 4016 int index = pkg.requestedPermissions.indexOf(bp.name); 4017 if (index == -1) { 4018 throw new SecurityException("Package " + pkg.packageName 4019 + " has not requested permission " + bp.name); 4020 } 4021 if (!bp.isRuntime() && !bp.isDevelopment()) { 4022 throw new SecurityException("Permission " + bp.name 4023 + " is not a changeable permission type"); 4024 } 4025 } 4026 4027 @Override 4028 public void grantRuntimePermission(String packageName, String name, final int userId) { 4029 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4030 } 4031 4032 private void grantRuntimePermission(String packageName, String name, final int userId, 4033 boolean overridePolicy) { 4034 if (!sUserManager.exists(userId)) { 4035 Log.e(TAG, "No such user:" + userId); 4036 return; 4037 } 4038 4039 mContext.enforceCallingOrSelfPermission( 4040 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4041 "grantRuntimePermission"); 4042 4043 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4044 true /* requireFullPermission */, true /* checkShell */, 4045 "grantRuntimePermission"); 4046 4047 final int uid; 4048 final SettingBase sb; 4049 4050 synchronized (mPackages) { 4051 final PackageParser.Package pkg = mPackages.get(packageName); 4052 if (pkg == null) { 4053 throw new IllegalArgumentException("Unknown package: " + packageName); 4054 } 4055 4056 final BasePermission bp = mSettings.mPermissions.get(name); 4057 if (bp == null) { 4058 throw new IllegalArgumentException("Unknown permission: " + name); 4059 } 4060 4061 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4062 4063 // If a permission review is required for legacy apps we represent 4064 // their permissions as always granted runtime ones since we need 4065 // to keep the review required permission flag per user while an 4066 // install permission's state is shared across all users. 4067 if (mPermissionReviewRequired 4068 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4069 && bp.isRuntime()) { 4070 return; 4071 } 4072 4073 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4074 sb = (SettingBase) pkg.mExtras; 4075 if (sb == null) { 4076 throw new IllegalArgumentException("Unknown package: " + packageName); 4077 } 4078 4079 final PermissionsState permissionsState = sb.getPermissionsState(); 4080 4081 final int flags = permissionsState.getPermissionFlags(name, userId); 4082 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4083 throw new SecurityException("Cannot grant system fixed permission " 4084 + name + " for package " + packageName); 4085 } 4086 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4087 throw new SecurityException("Cannot grant policy fixed permission " 4088 + name + " for package " + packageName); 4089 } 4090 4091 if (bp.isDevelopment()) { 4092 // Development permissions must be handled specially, since they are not 4093 // normal runtime permissions. For now they apply to all users. 4094 if (permissionsState.grantInstallPermission(bp) != 4095 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4096 scheduleWriteSettingsLocked(); 4097 } 4098 return; 4099 } 4100 4101 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 4102 throw new SecurityException("Cannot grant non-ephemeral permission" 4103 + name + " for package " + packageName); 4104 } 4105 4106 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4107 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4108 return; 4109 } 4110 4111 final int result = permissionsState.grantRuntimePermission(bp, userId); 4112 switch (result) { 4113 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4114 return; 4115 } 4116 4117 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4118 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4119 mHandler.post(new Runnable() { 4120 @Override 4121 public void run() { 4122 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4123 } 4124 }); 4125 } 4126 break; 4127 } 4128 4129 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4130 4131 // Not critical if that is lost - app has to request again. 4132 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4133 } 4134 4135 // Only need to do this if user is initialized. Otherwise it's a new user 4136 // and there are no processes running as the user yet and there's no need 4137 // to make an expensive call to remount processes for the changed permissions. 4138 if (READ_EXTERNAL_STORAGE.equals(name) 4139 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4140 final long token = Binder.clearCallingIdentity(); 4141 try { 4142 if (sUserManager.isInitialized(userId)) { 4143 MountServiceInternal mountServiceInternal = LocalServices.getService( 4144 MountServiceInternal.class); 4145 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4146 } 4147 } finally { 4148 Binder.restoreCallingIdentity(token); 4149 } 4150 } 4151 } 4152 4153 @Override 4154 public void revokeRuntimePermission(String packageName, String name, int userId) { 4155 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4156 } 4157 4158 private void revokeRuntimePermission(String packageName, String name, int userId, 4159 boolean overridePolicy) { 4160 if (!sUserManager.exists(userId)) { 4161 Log.e(TAG, "No such user:" + userId); 4162 return; 4163 } 4164 4165 mContext.enforceCallingOrSelfPermission( 4166 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4167 "revokeRuntimePermission"); 4168 4169 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4170 true /* requireFullPermission */, true /* checkShell */, 4171 "revokeRuntimePermission"); 4172 4173 final int appId; 4174 4175 synchronized (mPackages) { 4176 final PackageParser.Package pkg = mPackages.get(packageName); 4177 if (pkg == null) { 4178 throw new IllegalArgumentException("Unknown package: " + packageName); 4179 } 4180 4181 final BasePermission bp = mSettings.mPermissions.get(name); 4182 if (bp == null) { 4183 throw new IllegalArgumentException("Unknown permission: " + name); 4184 } 4185 4186 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4187 4188 // If a permission review is required for legacy apps we represent 4189 // their permissions as always granted runtime ones since we need 4190 // to keep the review required permission flag per user while an 4191 // install permission's state is shared across all users. 4192 if (mPermissionReviewRequired 4193 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4194 && bp.isRuntime()) { 4195 return; 4196 } 4197 4198 SettingBase sb = (SettingBase) pkg.mExtras; 4199 if (sb == null) { 4200 throw new IllegalArgumentException("Unknown package: " + packageName); 4201 } 4202 4203 final PermissionsState permissionsState = sb.getPermissionsState(); 4204 4205 final int flags = permissionsState.getPermissionFlags(name, userId); 4206 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4207 throw new SecurityException("Cannot revoke system fixed permission " 4208 + name + " for package " + packageName); 4209 } 4210 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4211 throw new SecurityException("Cannot revoke policy fixed permission " 4212 + name + " for package " + packageName); 4213 } 4214 4215 if (bp.isDevelopment()) { 4216 // Development permissions must be handled specially, since they are not 4217 // normal runtime permissions. For now they apply to all users. 4218 if (permissionsState.revokeInstallPermission(bp) != 4219 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4220 scheduleWriteSettingsLocked(); 4221 } 4222 return; 4223 } 4224 4225 if (permissionsState.revokeRuntimePermission(bp, userId) == 4226 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4227 return; 4228 } 4229 4230 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4231 4232 // Critical, after this call app should never have the permission. 4233 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4234 4235 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4236 } 4237 4238 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4239 } 4240 4241 @Override 4242 public void resetRuntimePermissions() { 4243 mContext.enforceCallingOrSelfPermission( 4244 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4245 "revokeRuntimePermission"); 4246 4247 int callingUid = Binder.getCallingUid(); 4248 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4249 mContext.enforceCallingOrSelfPermission( 4250 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4251 "resetRuntimePermissions"); 4252 } 4253 4254 synchronized (mPackages) { 4255 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4256 for (int userId : UserManagerService.getInstance().getUserIds()) { 4257 final int packageCount = mPackages.size(); 4258 for (int i = 0; i < packageCount; i++) { 4259 PackageParser.Package pkg = mPackages.valueAt(i); 4260 if (!(pkg.mExtras instanceof PackageSetting)) { 4261 continue; 4262 } 4263 PackageSetting ps = (PackageSetting) pkg.mExtras; 4264 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4265 } 4266 } 4267 } 4268 } 4269 4270 @Override 4271 public int getPermissionFlags(String name, String packageName, int userId) { 4272 if (!sUserManager.exists(userId)) { 4273 return 0; 4274 } 4275 4276 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4277 4278 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4279 true /* requireFullPermission */, false /* checkShell */, 4280 "getPermissionFlags"); 4281 4282 synchronized (mPackages) { 4283 final PackageParser.Package pkg = mPackages.get(packageName); 4284 if (pkg == null) { 4285 return 0; 4286 } 4287 4288 final BasePermission bp = mSettings.mPermissions.get(name); 4289 if (bp == null) { 4290 return 0; 4291 } 4292 4293 SettingBase sb = (SettingBase) pkg.mExtras; 4294 if (sb == null) { 4295 return 0; 4296 } 4297 4298 PermissionsState permissionsState = sb.getPermissionsState(); 4299 return permissionsState.getPermissionFlags(name, userId); 4300 } 4301 } 4302 4303 @Override 4304 public void updatePermissionFlags(String name, String packageName, int flagMask, 4305 int flagValues, int userId) { 4306 if (!sUserManager.exists(userId)) { 4307 return; 4308 } 4309 4310 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4311 4312 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4313 true /* requireFullPermission */, true /* checkShell */, 4314 "updatePermissionFlags"); 4315 4316 // Only the system can change these flags and nothing else. 4317 if (getCallingUid() != Process.SYSTEM_UID) { 4318 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4319 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4320 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4321 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4322 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4323 } 4324 4325 synchronized (mPackages) { 4326 final PackageParser.Package pkg = mPackages.get(packageName); 4327 if (pkg == null) { 4328 throw new IllegalArgumentException("Unknown package: " + packageName); 4329 } 4330 4331 final BasePermission bp = mSettings.mPermissions.get(name); 4332 if (bp == null) { 4333 throw new IllegalArgumentException("Unknown permission: " + name); 4334 } 4335 4336 SettingBase sb = (SettingBase) pkg.mExtras; 4337 if (sb == null) { 4338 throw new IllegalArgumentException("Unknown package: " + packageName); 4339 } 4340 4341 PermissionsState permissionsState = sb.getPermissionsState(); 4342 4343 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4344 4345 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4346 // Install and runtime permissions are stored in different places, 4347 // so figure out what permission changed and persist the change. 4348 if (permissionsState.getInstallPermissionState(name) != null) { 4349 scheduleWriteSettingsLocked(); 4350 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4351 || hadState) { 4352 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4353 } 4354 } 4355 } 4356 } 4357 4358 /** 4359 * Update the permission flags for all packages and runtime permissions of a user in order 4360 * to allow device or profile owner to remove POLICY_FIXED. 4361 */ 4362 @Override 4363 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4364 if (!sUserManager.exists(userId)) { 4365 return; 4366 } 4367 4368 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4369 4370 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4371 true /* requireFullPermission */, true /* checkShell */, 4372 "updatePermissionFlagsForAllApps"); 4373 4374 // Only the system can change system fixed flags. 4375 if (getCallingUid() != Process.SYSTEM_UID) { 4376 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4377 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4378 } 4379 4380 synchronized (mPackages) { 4381 boolean changed = false; 4382 final int packageCount = mPackages.size(); 4383 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4384 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4385 SettingBase sb = (SettingBase) pkg.mExtras; 4386 if (sb == null) { 4387 continue; 4388 } 4389 PermissionsState permissionsState = sb.getPermissionsState(); 4390 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4391 userId, flagMask, flagValues); 4392 } 4393 if (changed) { 4394 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4395 } 4396 } 4397 } 4398 4399 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4400 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4401 != PackageManager.PERMISSION_GRANTED 4402 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4403 != PackageManager.PERMISSION_GRANTED) { 4404 throw new SecurityException(message + " requires " 4405 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4406 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4407 } 4408 } 4409 4410 @Override 4411 public boolean shouldShowRequestPermissionRationale(String permissionName, 4412 String packageName, int userId) { 4413 if (UserHandle.getCallingUserId() != userId) { 4414 mContext.enforceCallingPermission( 4415 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4416 "canShowRequestPermissionRationale for user " + userId); 4417 } 4418 4419 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4420 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4421 return false; 4422 } 4423 4424 if (checkPermission(permissionName, packageName, userId) 4425 == PackageManager.PERMISSION_GRANTED) { 4426 return false; 4427 } 4428 4429 final int flags; 4430 4431 final long identity = Binder.clearCallingIdentity(); 4432 try { 4433 flags = getPermissionFlags(permissionName, 4434 packageName, userId); 4435 } finally { 4436 Binder.restoreCallingIdentity(identity); 4437 } 4438 4439 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4440 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4441 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4442 4443 if ((flags & fixedFlags) != 0) { 4444 return false; 4445 } 4446 4447 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4448 } 4449 4450 @Override 4451 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4452 mContext.enforceCallingOrSelfPermission( 4453 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4454 "addOnPermissionsChangeListener"); 4455 4456 synchronized (mPackages) { 4457 mOnPermissionChangeListeners.addListenerLocked(listener); 4458 } 4459 } 4460 4461 @Override 4462 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4463 synchronized (mPackages) { 4464 mOnPermissionChangeListeners.removeListenerLocked(listener); 4465 } 4466 } 4467 4468 @Override 4469 public boolean isProtectedBroadcast(String actionName) { 4470 synchronized (mPackages) { 4471 if (mProtectedBroadcasts.contains(actionName)) { 4472 return true; 4473 } else if (actionName != null) { 4474 // TODO: remove these terrible hacks 4475 if (actionName.startsWith("android.net.netmon.lingerExpired") 4476 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4477 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4478 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4479 return true; 4480 } 4481 } 4482 } 4483 return false; 4484 } 4485 4486 @Override 4487 public int checkSignatures(String pkg1, String pkg2) { 4488 synchronized (mPackages) { 4489 final PackageParser.Package p1 = mPackages.get(pkg1); 4490 final PackageParser.Package p2 = mPackages.get(pkg2); 4491 if (p1 == null || p1.mExtras == null 4492 || p2 == null || p2.mExtras == null) { 4493 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4494 } 4495 return compareSignatures(p1.mSignatures, p2.mSignatures); 4496 } 4497 } 4498 4499 @Override 4500 public int checkUidSignatures(int uid1, int uid2) { 4501 // Map to base uids. 4502 uid1 = UserHandle.getAppId(uid1); 4503 uid2 = UserHandle.getAppId(uid2); 4504 // reader 4505 synchronized (mPackages) { 4506 Signature[] s1; 4507 Signature[] s2; 4508 Object obj = mSettings.getUserIdLPr(uid1); 4509 if (obj != null) { 4510 if (obj instanceof SharedUserSetting) { 4511 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4512 } else if (obj instanceof PackageSetting) { 4513 s1 = ((PackageSetting)obj).signatures.mSignatures; 4514 } else { 4515 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4516 } 4517 } else { 4518 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4519 } 4520 obj = mSettings.getUserIdLPr(uid2); 4521 if (obj != null) { 4522 if (obj instanceof SharedUserSetting) { 4523 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4524 } else if (obj instanceof PackageSetting) { 4525 s2 = ((PackageSetting)obj).signatures.mSignatures; 4526 } else { 4527 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4528 } 4529 } else { 4530 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4531 } 4532 return compareSignatures(s1, s2); 4533 } 4534 } 4535 4536 /** 4537 * This method should typically only be used when granting or revoking 4538 * permissions, since the app may immediately restart after this call. 4539 * <p> 4540 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4541 * guard your work against the app being relaunched. 4542 */ 4543 private void killUid(int appId, int userId, String reason) { 4544 final long identity = Binder.clearCallingIdentity(); 4545 try { 4546 IActivityManager am = ActivityManagerNative.getDefault(); 4547 if (am != null) { 4548 try { 4549 am.killUid(appId, userId, reason); 4550 } catch (RemoteException e) { 4551 /* ignore - same process */ 4552 } 4553 } 4554 } finally { 4555 Binder.restoreCallingIdentity(identity); 4556 } 4557 } 4558 4559 /** 4560 * Compares two sets of signatures. Returns: 4561 * <br /> 4562 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4563 * <br /> 4564 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4565 * <br /> 4566 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4567 * <br /> 4568 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4569 * <br /> 4570 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4571 */ 4572 static int compareSignatures(Signature[] s1, Signature[] s2) { 4573 if (s1 == null) { 4574 return s2 == null 4575 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4576 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4577 } 4578 4579 if (s2 == null) { 4580 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4581 } 4582 4583 if (s1.length != s2.length) { 4584 return PackageManager.SIGNATURE_NO_MATCH; 4585 } 4586 4587 // Since both signature sets are of size 1, we can compare without HashSets. 4588 if (s1.length == 1) { 4589 return s1[0].equals(s2[0]) ? 4590 PackageManager.SIGNATURE_MATCH : 4591 PackageManager.SIGNATURE_NO_MATCH; 4592 } 4593 4594 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4595 for (Signature sig : s1) { 4596 set1.add(sig); 4597 } 4598 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4599 for (Signature sig : s2) { 4600 set2.add(sig); 4601 } 4602 // Make sure s2 contains all signatures in s1. 4603 if (set1.equals(set2)) { 4604 return PackageManager.SIGNATURE_MATCH; 4605 } 4606 return PackageManager.SIGNATURE_NO_MATCH; 4607 } 4608 4609 /** 4610 * If the database version for this type of package (internal storage or 4611 * external storage) is less than the version where package signatures 4612 * were updated, return true. 4613 */ 4614 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4615 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4616 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4617 } 4618 4619 /** 4620 * Used for backward compatibility to make sure any packages with 4621 * certificate chains get upgraded to the new style. {@code existingSigs} 4622 * will be in the old format (since they were stored on disk from before the 4623 * system upgrade) and {@code scannedSigs} will be in the newer format. 4624 */ 4625 private int compareSignaturesCompat(PackageSignatures existingSigs, 4626 PackageParser.Package scannedPkg) { 4627 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4628 return PackageManager.SIGNATURE_NO_MATCH; 4629 } 4630 4631 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4632 for (Signature sig : existingSigs.mSignatures) { 4633 existingSet.add(sig); 4634 } 4635 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4636 for (Signature sig : scannedPkg.mSignatures) { 4637 try { 4638 Signature[] chainSignatures = sig.getChainSignatures(); 4639 for (Signature chainSig : chainSignatures) { 4640 scannedCompatSet.add(chainSig); 4641 } 4642 } catch (CertificateEncodingException e) { 4643 scannedCompatSet.add(sig); 4644 } 4645 } 4646 /* 4647 * Make sure the expanded scanned set contains all signatures in the 4648 * existing one. 4649 */ 4650 if (scannedCompatSet.equals(existingSet)) { 4651 // Migrate the old signatures to the new scheme. 4652 existingSigs.assignSignatures(scannedPkg.mSignatures); 4653 // The new KeySets will be re-added later in the scanning process. 4654 synchronized (mPackages) { 4655 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4656 } 4657 return PackageManager.SIGNATURE_MATCH; 4658 } 4659 return PackageManager.SIGNATURE_NO_MATCH; 4660 } 4661 4662 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4663 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4664 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4665 } 4666 4667 private int compareSignaturesRecover(PackageSignatures existingSigs, 4668 PackageParser.Package scannedPkg) { 4669 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4670 return PackageManager.SIGNATURE_NO_MATCH; 4671 } 4672 4673 String msg = null; 4674 try { 4675 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4676 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4677 + scannedPkg.packageName); 4678 return PackageManager.SIGNATURE_MATCH; 4679 } 4680 } catch (CertificateException e) { 4681 msg = e.getMessage(); 4682 } 4683 4684 logCriticalInfo(Log.INFO, 4685 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4686 return PackageManager.SIGNATURE_NO_MATCH; 4687 } 4688 4689 @Override 4690 public List<String> getAllPackages() { 4691 synchronized (mPackages) { 4692 return new ArrayList<String>(mPackages.keySet()); 4693 } 4694 } 4695 4696 @Override 4697 public String[] getPackagesForUid(int uid) { 4698 final int userId = UserHandle.getUserId(uid); 4699 uid = UserHandle.getAppId(uid); 4700 // reader 4701 synchronized (mPackages) { 4702 Object obj = mSettings.getUserIdLPr(uid); 4703 if (obj instanceof SharedUserSetting) { 4704 final SharedUserSetting sus = (SharedUserSetting) obj; 4705 final int N = sus.packages.size(); 4706 String[] res = new String[N]; 4707 final Iterator<PackageSetting> it = sus.packages.iterator(); 4708 int i = 0; 4709 while (it.hasNext()) { 4710 PackageSetting ps = it.next(); 4711 if (ps.getInstalled(userId)) { 4712 res[i++] = ps.name; 4713 } else { 4714 res = ArrayUtils.removeElement(String.class, res, res[i]); 4715 } 4716 } 4717 return res; 4718 } else if (obj instanceof PackageSetting) { 4719 final PackageSetting ps = (PackageSetting) obj; 4720 return new String[] { ps.name }; 4721 } 4722 } 4723 return null; 4724 } 4725 4726 @Override 4727 public String getNameForUid(int uid) { 4728 // reader 4729 synchronized (mPackages) { 4730 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4731 if (obj instanceof SharedUserSetting) { 4732 final SharedUserSetting sus = (SharedUserSetting) obj; 4733 return sus.name + ":" + sus.userId; 4734 } else if (obj instanceof PackageSetting) { 4735 final PackageSetting ps = (PackageSetting) obj; 4736 return ps.name; 4737 } 4738 } 4739 return null; 4740 } 4741 4742 @Override 4743 public int getUidForSharedUser(String sharedUserName) { 4744 if(sharedUserName == null) { 4745 return -1; 4746 } 4747 // reader 4748 synchronized (mPackages) { 4749 SharedUserSetting suid; 4750 try { 4751 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4752 if (suid != null) { 4753 return suid.userId; 4754 } 4755 } catch (PackageManagerException ignore) { 4756 // can't happen, but, still need to catch it 4757 } 4758 return -1; 4759 } 4760 } 4761 4762 @Override 4763 public int getFlagsForUid(int uid) { 4764 synchronized (mPackages) { 4765 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4766 if (obj instanceof SharedUserSetting) { 4767 final SharedUserSetting sus = (SharedUserSetting) obj; 4768 return sus.pkgFlags; 4769 } else if (obj instanceof PackageSetting) { 4770 final PackageSetting ps = (PackageSetting) obj; 4771 return ps.pkgFlags; 4772 } 4773 } 4774 return 0; 4775 } 4776 4777 @Override 4778 public int getPrivateFlagsForUid(int uid) { 4779 synchronized (mPackages) { 4780 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4781 if (obj instanceof SharedUserSetting) { 4782 final SharedUserSetting sus = (SharedUserSetting) obj; 4783 return sus.pkgPrivateFlags; 4784 } else if (obj instanceof PackageSetting) { 4785 final PackageSetting ps = (PackageSetting) obj; 4786 return ps.pkgPrivateFlags; 4787 } 4788 } 4789 return 0; 4790 } 4791 4792 @Override 4793 public boolean isUidPrivileged(int uid) { 4794 uid = UserHandle.getAppId(uid); 4795 // reader 4796 synchronized (mPackages) { 4797 Object obj = mSettings.getUserIdLPr(uid); 4798 if (obj instanceof SharedUserSetting) { 4799 final SharedUserSetting sus = (SharedUserSetting) obj; 4800 final Iterator<PackageSetting> it = sus.packages.iterator(); 4801 while (it.hasNext()) { 4802 if (it.next().isPrivileged()) { 4803 return true; 4804 } 4805 } 4806 } else if (obj instanceof PackageSetting) { 4807 final PackageSetting ps = (PackageSetting) obj; 4808 return ps.isPrivileged(); 4809 } 4810 } 4811 return false; 4812 } 4813 4814 @Override 4815 public String[] getAppOpPermissionPackages(String permissionName) { 4816 synchronized (mPackages) { 4817 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4818 if (pkgs == null) { 4819 return null; 4820 } 4821 return pkgs.toArray(new String[pkgs.size()]); 4822 } 4823 } 4824 4825 @Override 4826 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4827 int flags, int userId) { 4828 try { 4829 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4830 4831 if (!sUserManager.exists(userId)) return null; 4832 flags = updateFlagsForResolve(flags, userId, intent); 4833 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4834 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4835 4836 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4837 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4838 flags, userId); 4839 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4840 4841 final ResolveInfo bestChoice = 4842 chooseBestActivity(intent, resolvedType, flags, query, userId); 4843 return bestChoice; 4844 } finally { 4845 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4846 } 4847 } 4848 4849 @Override 4850 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4851 IntentFilter filter, int match, ComponentName activity) { 4852 final int userId = UserHandle.getCallingUserId(); 4853 if (DEBUG_PREFERRED) { 4854 Log.v(TAG, "setLastChosenActivity intent=" + intent 4855 + " resolvedType=" + resolvedType 4856 + " flags=" + flags 4857 + " filter=" + filter 4858 + " match=" + match 4859 + " activity=" + activity); 4860 filter.dump(new PrintStreamPrinter(System.out), " "); 4861 } 4862 intent.setComponent(null); 4863 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4864 userId); 4865 // Find any earlier preferred or last chosen entries and nuke them 4866 findPreferredActivity(intent, resolvedType, 4867 flags, query, 0, false, true, false, userId); 4868 // Add the new activity as the last chosen for this filter 4869 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4870 "Setting last chosen"); 4871 } 4872 4873 @Override 4874 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4875 final int userId = UserHandle.getCallingUserId(); 4876 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4877 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4878 userId); 4879 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4880 false, false, false, userId); 4881 } 4882 4883 private boolean isEphemeralDisabled() { 4884 // ephemeral apps have been disabled across the board 4885 if (DISABLE_EPHEMERAL_APPS) { 4886 return true; 4887 } 4888 // system isn't up yet; can't read settings, so, assume no ephemeral apps 4889 if (!mSystemReady) { 4890 return true; 4891 } 4892 // we can't get a content resolver until the system is ready; these checks must happen last 4893 final ContentResolver resolver = mContext.getContentResolver(); 4894 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 4895 return true; 4896 } 4897 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 4898 } 4899 4900 private boolean isEphemeralAllowed( 4901 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 4902 boolean skipPackageCheck) { 4903 // Short circuit and return early if possible. 4904 if (isEphemeralDisabled()) { 4905 return false; 4906 } 4907 final int callingUser = UserHandle.getCallingUserId(); 4908 if (callingUser != UserHandle.USER_SYSTEM) { 4909 return false; 4910 } 4911 if (mEphemeralResolverConnection == null) { 4912 return false; 4913 } 4914 if (intent.getComponent() != null) { 4915 return false; 4916 } 4917 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 4918 return false; 4919 } 4920 if (!skipPackageCheck && intent.getPackage() != null) { 4921 return false; 4922 } 4923 final boolean isWebUri = hasWebURI(intent); 4924 if (!isWebUri || intent.getData().getHost() == null) { 4925 return false; 4926 } 4927 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4928 synchronized (mPackages) { 4929 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 4930 for (int n = 0; n < count; n++) { 4931 ResolveInfo info = resolvedActivities.get(n); 4932 String packageName = info.activityInfo.packageName; 4933 PackageSetting ps = mSettings.mPackages.get(packageName); 4934 if (ps != null) { 4935 // Try to get the status from User settings first 4936 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4937 int status = (int) (packedStatus >> 32); 4938 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4939 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4940 if (DEBUG_EPHEMERAL) { 4941 Slog.v(TAG, "DENY ephemeral apps;" 4942 + " pkg: " + packageName + ", status: " + status); 4943 } 4944 return false; 4945 } 4946 } 4947 } 4948 } 4949 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4950 return true; 4951 } 4952 4953 private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 4954 Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage, 4955 int userId) { 4956 final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO, 4957 new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent, 4958 callingPackage, userId)); 4959 mHandler.sendMessage(msg); 4960 } 4961 4962 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4963 int flags, List<ResolveInfo> query, int userId) { 4964 if (query != null) { 4965 final int N = query.size(); 4966 if (N == 1) { 4967 return query.get(0); 4968 } else if (N > 1) { 4969 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4970 // If there is more than one activity with the same priority, 4971 // then let the user decide between them. 4972 ResolveInfo r0 = query.get(0); 4973 ResolveInfo r1 = query.get(1); 4974 if (DEBUG_INTENT_MATCHING || debug) { 4975 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4976 + r1.activityInfo.name + "=" + r1.priority); 4977 } 4978 // If the first activity has a higher priority, or a different 4979 // default, then it is always desirable to pick it. 4980 if (r0.priority != r1.priority 4981 || r0.preferredOrder != r1.preferredOrder 4982 || r0.isDefault != r1.isDefault) { 4983 return query.get(0); 4984 } 4985 // If we have saved a preference for a preferred activity for 4986 // this Intent, use that. 4987 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4988 flags, query, r0.priority, true, false, debug, userId); 4989 if (ri != null) { 4990 return ri; 4991 } 4992 ri = new ResolveInfo(mResolveInfo); 4993 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4994 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 4995 // If all of the options come from the same package, show the application's 4996 // label and icon instead of the generic resolver's. 4997 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 4998 // and then throw away the ResolveInfo itself, meaning that the caller loses 4999 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5000 // a fallback for this case; we only set the target package's resources on 5001 // the ResolveInfo, not the ActivityInfo. 5002 final String intentPackage = intent.getPackage(); 5003 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5004 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5005 ri.resolvePackageName = intentPackage; 5006 if (userNeedsBadging(userId)) { 5007 ri.noResourceId = true; 5008 } else { 5009 ri.icon = appi.icon; 5010 } 5011 ri.iconResourceId = appi.icon; 5012 ri.labelRes = appi.labelRes; 5013 } 5014 ri.activityInfo.applicationInfo = new ApplicationInfo( 5015 ri.activityInfo.applicationInfo); 5016 if (userId != 0) { 5017 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5018 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5019 } 5020 // Make sure that the resolver is displayable in car mode 5021 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5022 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5023 return ri; 5024 } 5025 } 5026 return null; 5027 } 5028 5029 /** 5030 * Return true if the given list is not empty and all of its contents have 5031 * an activityInfo with the given package name. 5032 */ 5033 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5034 if (ArrayUtils.isEmpty(list)) { 5035 return false; 5036 } 5037 for (int i = 0, N = list.size(); i < N; i++) { 5038 final ResolveInfo ri = list.get(i); 5039 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5040 if (ai == null || !packageName.equals(ai.packageName)) { 5041 return false; 5042 } 5043 } 5044 return true; 5045 } 5046 5047 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5048 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5049 final int N = query.size(); 5050 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5051 .get(userId); 5052 // Get the list of persistent preferred activities that handle the intent 5053 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5054 List<PersistentPreferredActivity> pprefs = ppir != null 5055 ? ppir.queryIntent(intent, resolvedType, 5056 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5057 : null; 5058 if (pprefs != null && pprefs.size() > 0) { 5059 final int M = pprefs.size(); 5060 for (int i=0; i<M; i++) { 5061 final PersistentPreferredActivity ppa = pprefs.get(i); 5062 if (DEBUG_PREFERRED || debug) { 5063 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5064 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5065 + "\n component=" + ppa.mComponent); 5066 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5067 } 5068 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5069 flags | MATCH_DISABLED_COMPONENTS, userId); 5070 if (DEBUG_PREFERRED || debug) { 5071 Slog.v(TAG, "Found persistent preferred activity:"); 5072 if (ai != null) { 5073 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5074 } else { 5075 Slog.v(TAG, " null"); 5076 } 5077 } 5078 if (ai == null) { 5079 // This previously registered persistent preferred activity 5080 // component is no longer known. Ignore it and do NOT remove it. 5081 continue; 5082 } 5083 for (int j=0; j<N; j++) { 5084 final ResolveInfo ri = query.get(j); 5085 if (!ri.activityInfo.applicationInfo.packageName 5086 .equals(ai.applicationInfo.packageName)) { 5087 continue; 5088 } 5089 if (!ri.activityInfo.name.equals(ai.name)) { 5090 continue; 5091 } 5092 // Found a persistent preference that can handle the intent. 5093 if (DEBUG_PREFERRED || debug) { 5094 Slog.v(TAG, "Returning persistent preferred activity: " + 5095 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5096 } 5097 return ri; 5098 } 5099 } 5100 } 5101 return null; 5102 } 5103 5104 // TODO: handle preferred activities missing while user has amnesia 5105 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5106 List<ResolveInfo> query, int priority, boolean always, 5107 boolean removeMatches, boolean debug, int userId) { 5108 if (!sUserManager.exists(userId)) return null; 5109 flags = updateFlagsForResolve(flags, userId, intent); 5110 // writer 5111 synchronized (mPackages) { 5112 if (intent.getSelector() != null) { 5113 intent = intent.getSelector(); 5114 } 5115 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5116 5117 // Try to find a matching persistent preferred activity. 5118 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5119 debug, userId); 5120 5121 // If a persistent preferred activity matched, use it. 5122 if (pri != null) { 5123 return pri; 5124 } 5125 5126 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5127 // Get the list of preferred activities that handle the intent 5128 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5129 List<PreferredActivity> prefs = pir != null 5130 ? pir.queryIntent(intent, resolvedType, 5131 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5132 : null; 5133 if (prefs != null && prefs.size() > 0) { 5134 boolean changed = false; 5135 try { 5136 // First figure out how good the original match set is. 5137 // We will only allow preferred activities that came 5138 // from the same match quality. 5139 int match = 0; 5140 5141 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5142 5143 final int N = query.size(); 5144 for (int j=0; j<N; j++) { 5145 final ResolveInfo ri = query.get(j); 5146 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5147 + ": 0x" + Integer.toHexString(match)); 5148 if (ri.match > match) { 5149 match = ri.match; 5150 } 5151 } 5152 5153 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5154 + Integer.toHexString(match)); 5155 5156 match &= IntentFilter.MATCH_CATEGORY_MASK; 5157 final int M = prefs.size(); 5158 for (int i=0; i<M; i++) { 5159 final PreferredActivity pa = prefs.get(i); 5160 if (DEBUG_PREFERRED || debug) { 5161 Slog.v(TAG, "Checking PreferredActivity ds=" 5162 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5163 + "\n component=" + pa.mPref.mComponent); 5164 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5165 } 5166 if (pa.mPref.mMatch != match) { 5167 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5168 + Integer.toHexString(pa.mPref.mMatch)); 5169 continue; 5170 } 5171 // If it's not an "always" type preferred activity and that's what we're 5172 // looking for, skip it. 5173 if (always && !pa.mPref.mAlways) { 5174 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5175 continue; 5176 } 5177 final ActivityInfo ai = getActivityInfo( 5178 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5179 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5180 userId); 5181 if (DEBUG_PREFERRED || debug) { 5182 Slog.v(TAG, "Found preferred activity:"); 5183 if (ai != null) { 5184 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5185 } else { 5186 Slog.v(TAG, " null"); 5187 } 5188 } 5189 if (ai == null) { 5190 // This previously registered preferred activity 5191 // component is no longer known. Most likely an update 5192 // to the app was installed and in the new version this 5193 // component no longer exists. Clean it up by removing 5194 // it from the preferred activities list, and skip it. 5195 Slog.w(TAG, "Removing dangling preferred activity: " 5196 + pa.mPref.mComponent); 5197 pir.removeFilter(pa); 5198 changed = true; 5199 continue; 5200 } 5201 for (int j=0; j<N; j++) { 5202 final ResolveInfo ri = query.get(j); 5203 if (!ri.activityInfo.applicationInfo.packageName 5204 .equals(ai.applicationInfo.packageName)) { 5205 continue; 5206 } 5207 if (!ri.activityInfo.name.equals(ai.name)) { 5208 continue; 5209 } 5210 5211 if (removeMatches) { 5212 pir.removeFilter(pa); 5213 changed = true; 5214 if (DEBUG_PREFERRED) { 5215 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5216 } 5217 break; 5218 } 5219 5220 // Okay we found a previously set preferred or last chosen app. 5221 // If the result set is different from when this 5222 // was created, we need to clear it and re-ask the 5223 // user their preference, if we're looking for an "always" type entry. 5224 if (always && !pa.mPref.sameSet(query)) { 5225 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5226 + intent + " type " + resolvedType); 5227 if (DEBUG_PREFERRED) { 5228 Slog.v(TAG, "Removing preferred activity since set changed " 5229 + pa.mPref.mComponent); 5230 } 5231 pir.removeFilter(pa); 5232 // Re-add the filter as a "last chosen" entry (!always) 5233 PreferredActivity lastChosen = new PreferredActivity( 5234 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5235 pir.addFilter(lastChosen); 5236 changed = true; 5237 return null; 5238 } 5239 5240 // Yay! Either the set matched or we're looking for the last chosen 5241 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5242 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5243 return ri; 5244 } 5245 } 5246 } finally { 5247 if (changed) { 5248 if (DEBUG_PREFERRED) { 5249 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5250 } 5251 scheduleWritePackageRestrictionsLocked(userId); 5252 } 5253 } 5254 } 5255 } 5256 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5257 return null; 5258 } 5259 5260 /* 5261 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5262 */ 5263 @Override 5264 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5265 int targetUserId) { 5266 mContext.enforceCallingOrSelfPermission( 5267 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5268 List<CrossProfileIntentFilter> matches = 5269 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5270 if (matches != null) { 5271 int size = matches.size(); 5272 for (int i = 0; i < size; i++) { 5273 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5274 } 5275 } 5276 if (hasWebURI(intent)) { 5277 // cross-profile app linking works only towards the parent. 5278 final UserInfo parent = getProfileParent(sourceUserId); 5279 synchronized(mPackages) { 5280 int flags = updateFlagsForResolve(0, parent.id, intent); 5281 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5282 intent, resolvedType, flags, sourceUserId, parent.id); 5283 return xpDomainInfo != null; 5284 } 5285 } 5286 return false; 5287 } 5288 5289 private UserInfo getProfileParent(int userId) { 5290 final long identity = Binder.clearCallingIdentity(); 5291 try { 5292 return sUserManager.getProfileParent(userId); 5293 } finally { 5294 Binder.restoreCallingIdentity(identity); 5295 } 5296 } 5297 5298 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5299 String resolvedType, int userId) { 5300 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5301 if (resolver != null) { 5302 return resolver.queryIntent(intent, resolvedType, false, userId); 5303 } 5304 return null; 5305 } 5306 5307 @Override 5308 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5309 String resolvedType, int flags, int userId) { 5310 try { 5311 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5312 5313 return new ParceledListSlice<>( 5314 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5315 } finally { 5316 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5317 } 5318 } 5319 5320 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5321 String resolvedType, int flags, int userId) { 5322 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5323 flags = updateFlagsForResolve(flags, userId, intent); 5324 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5325 false /* requireFullPermission */, false /* checkShell */, 5326 "query intent activities"); 5327 ComponentName comp = intent.getComponent(); 5328 if (comp == null) { 5329 if (intent.getSelector() != null) { 5330 intent = intent.getSelector(); 5331 comp = intent.getComponent(); 5332 } 5333 } 5334 5335 if (comp != null) { 5336 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5337 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5338 if (ai != null) { 5339 final ResolveInfo ri = new ResolveInfo(); 5340 ri.activityInfo = ai; 5341 list.add(ri); 5342 } 5343 return list; 5344 } 5345 5346 // reader 5347 boolean sortResult = false; 5348 boolean addEphemeral = false; 5349 boolean matchEphemeralPackage = false; 5350 List<ResolveInfo> result; 5351 final String pkgName = intent.getPackage(); 5352 synchronized (mPackages) { 5353 if (pkgName == null) { 5354 List<CrossProfileIntentFilter> matchingFilters = 5355 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5356 // Check for results that need to skip the current profile. 5357 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5358 resolvedType, flags, userId); 5359 if (xpResolveInfo != null) { 5360 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5361 xpResult.add(xpResolveInfo); 5362 return filterIfNotSystemUser(xpResult, userId); 5363 } 5364 5365 // Check for results in the current profile. 5366 result = filterIfNotSystemUser(mActivities.queryIntent( 5367 intent, resolvedType, flags, userId), userId); 5368 addEphemeral = 5369 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5370 5371 // Check for cross profile results. 5372 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5373 xpResolveInfo = queryCrossProfileIntents( 5374 matchingFilters, intent, resolvedType, flags, userId, 5375 hasNonNegativePriorityResult); 5376 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5377 boolean isVisibleToUser = filterIfNotSystemUser( 5378 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5379 if (isVisibleToUser) { 5380 result.add(xpResolveInfo); 5381 sortResult = true; 5382 } 5383 } 5384 if (hasWebURI(intent)) { 5385 CrossProfileDomainInfo xpDomainInfo = null; 5386 final UserInfo parent = getProfileParent(userId); 5387 if (parent != null) { 5388 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5389 flags, userId, parent.id); 5390 } 5391 if (xpDomainInfo != null) { 5392 if (xpResolveInfo != null) { 5393 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5394 // in the result. 5395 result.remove(xpResolveInfo); 5396 } 5397 if (result.size() == 0 && !addEphemeral) { 5398 // No result in current profile, but found candidate in parent user. 5399 // And we are not going to add emphemeral app, so we can return the 5400 // result straight away. 5401 result.add(xpDomainInfo.resolveInfo); 5402 return result; 5403 } 5404 } else if (result.size() <= 1 && !addEphemeral) { 5405 // No result in parent user and <= 1 result in current profile, and we 5406 // are not going to add emphemeral app, so we can return the result without 5407 // further processing. 5408 return result; 5409 } 5410 // We have more than one candidate (combining results from current and parent 5411 // profile), so we need filtering and sorting. 5412 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5413 intent, flags, result, xpDomainInfo, userId); 5414 sortResult = true; 5415 } 5416 } else { 5417 final PackageParser.Package pkg = mPackages.get(pkgName); 5418 if (pkg != null) { 5419 result = filterIfNotSystemUser( 5420 mActivities.queryIntentForPackage( 5421 intent, resolvedType, flags, pkg.activities, userId), 5422 userId); 5423 } else { 5424 // the caller wants to resolve for a particular package; however, there 5425 // were no installed results, so, try to find an ephemeral result 5426 addEphemeral = isEphemeralAllowed( 5427 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5428 matchEphemeralPackage = true; 5429 result = new ArrayList<ResolveInfo>(); 5430 } 5431 } 5432 } 5433 if (addEphemeral) { 5434 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5435 final EphemeralRequest requestObject = new EphemeralRequest( 5436 null /*responseObj*/, intent /*origIntent*/, resolvedType, 5437 null /*launchIntent*/, null /*callingPackage*/, userId); 5438 final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne( 5439 mContext, mEphemeralResolverConnection, requestObject); 5440 if (intentInfo != null) { 5441 if (DEBUG_EPHEMERAL) { 5442 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5443 } 5444 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5445 ephemeralInstaller.ephemeralResponse = intentInfo; 5446 // make sure this resolver is the default 5447 ephemeralInstaller.isDefault = true; 5448 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5449 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5450 // add a non-generic filter 5451 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5452 ephemeralInstaller.filter.addDataPath( 5453 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5454 result.add(ephemeralInstaller); 5455 } 5456 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5457 } 5458 if (sortResult) { 5459 Collections.sort(result, mResolvePrioritySorter); 5460 } 5461 return result; 5462 } 5463 5464 private static class CrossProfileDomainInfo { 5465 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5466 ResolveInfo resolveInfo; 5467 /* Best domain verification status of the activities found in the other profile */ 5468 int bestDomainVerificationStatus; 5469 } 5470 5471 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5472 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5473 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5474 sourceUserId)) { 5475 return null; 5476 } 5477 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5478 resolvedType, flags, parentUserId); 5479 5480 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5481 return null; 5482 } 5483 CrossProfileDomainInfo result = null; 5484 int size = resultTargetUser.size(); 5485 for (int i = 0; i < size; i++) { 5486 ResolveInfo riTargetUser = resultTargetUser.get(i); 5487 // Intent filter verification is only for filters that specify a host. So don't return 5488 // those that handle all web uris. 5489 if (riTargetUser.handleAllWebDataURI) { 5490 continue; 5491 } 5492 String packageName = riTargetUser.activityInfo.packageName; 5493 PackageSetting ps = mSettings.mPackages.get(packageName); 5494 if (ps == null) { 5495 continue; 5496 } 5497 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5498 int status = (int)(verificationState >> 32); 5499 if (result == null) { 5500 result = new CrossProfileDomainInfo(); 5501 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5502 sourceUserId, parentUserId); 5503 result.bestDomainVerificationStatus = status; 5504 } else { 5505 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5506 result.bestDomainVerificationStatus); 5507 } 5508 } 5509 // Don't consider matches with status NEVER across profiles. 5510 if (result != null && result.bestDomainVerificationStatus 5511 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5512 return null; 5513 } 5514 return result; 5515 } 5516 5517 /** 5518 * Verification statuses are ordered from the worse to the best, except for 5519 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5520 */ 5521 private int bestDomainVerificationStatus(int status1, int status2) { 5522 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5523 return status2; 5524 } 5525 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5526 return status1; 5527 } 5528 return (int) MathUtils.max(status1, status2); 5529 } 5530 5531 private boolean isUserEnabled(int userId) { 5532 long callingId = Binder.clearCallingIdentity(); 5533 try { 5534 UserInfo userInfo = sUserManager.getUserInfo(userId); 5535 return userInfo != null && userInfo.isEnabled(); 5536 } finally { 5537 Binder.restoreCallingIdentity(callingId); 5538 } 5539 } 5540 5541 /** 5542 * Filter out activities with systemUserOnly flag set, when current user is not System. 5543 * 5544 * @return filtered list 5545 */ 5546 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5547 if (userId == UserHandle.USER_SYSTEM) { 5548 return resolveInfos; 5549 } 5550 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5551 ResolveInfo info = resolveInfos.get(i); 5552 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5553 resolveInfos.remove(i); 5554 } 5555 } 5556 return resolveInfos; 5557 } 5558 5559 /** 5560 * @param resolveInfos list of resolve infos in descending priority order 5561 * @return if the list contains a resolve info with non-negative priority 5562 */ 5563 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5564 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5565 } 5566 5567 private static boolean hasWebURI(Intent intent) { 5568 if (intent.getData() == null) { 5569 return false; 5570 } 5571 final String scheme = intent.getScheme(); 5572 if (TextUtils.isEmpty(scheme)) { 5573 return false; 5574 } 5575 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5576 } 5577 5578 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5579 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5580 int userId) { 5581 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5582 5583 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5584 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5585 candidates.size()); 5586 } 5587 5588 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5589 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5590 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5591 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5592 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5593 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5594 5595 synchronized (mPackages) { 5596 final int count = candidates.size(); 5597 // First, try to use linked apps. Partition the candidates into four lists: 5598 // one for the final results, one for the "do not use ever", one for "undefined status" 5599 // and finally one for "browser app type". 5600 for (int n=0; n<count; n++) { 5601 ResolveInfo info = candidates.get(n); 5602 String packageName = info.activityInfo.packageName; 5603 PackageSetting ps = mSettings.mPackages.get(packageName); 5604 if (ps != null) { 5605 // Add to the special match all list (Browser use case) 5606 if (info.handleAllWebDataURI) { 5607 matchAllList.add(info); 5608 continue; 5609 } 5610 // Try to get the status from User settings first 5611 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5612 int status = (int)(packedStatus >> 32); 5613 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5614 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5615 if (DEBUG_DOMAIN_VERIFICATION) { 5616 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5617 + " : linkgen=" + linkGeneration); 5618 } 5619 // Use link-enabled generation as preferredOrder, i.e. 5620 // prefer newly-enabled over earlier-enabled. 5621 info.preferredOrder = linkGeneration; 5622 alwaysList.add(info); 5623 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5624 if (DEBUG_DOMAIN_VERIFICATION) { 5625 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5626 } 5627 neverList.add(info); 5628 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5629 if (DEBUG_DOMAIN_VERIFICATION) { 5630 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5631 } 5632 alwaysAskList.add(info); 5633 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5634 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5635 if (DEBUG_DOMAIN_VERIFICATION) { 5636 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5637 } 5638 undefinedList.add(info); 5639 } 5640 } 5641 } 5642 5643 // We'll want to include browser possibilities in a few cases 5644 boolean includeBrowser = false; 5645 5646 // First try to add the "always" resolution(s) for the current user, if any 5647 if (alwaysList.size() > 0) { 5648 result.addAll(alwaysList); 5649 } else { 5650 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5651 result.addAll(undefinedList); 5652 // Maybe add one for the other profile. 5653 if (xpDomainInfo != null && ( 5654 xpDomainInfo.bestDomainVerificationStatus 5655 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5656 result.add(xpDomainInfo.resolveInfo); 5657 } 5658 includeBrowser = true; 5659 } 5660 5661 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5662 // If there were 'always' entries their preferred order has been set, so we also 5663 // back that off to make the alternatives equivalent 5664 if (alwaysAskList.size() > 0) { 5665 for (ResolveInfo i : result) { 5666 i.preferredOrder = 0; 5667 } 5668 result.addAll(alwaysAskList); 5669 includeBrowser = true; 5670 } 5671 5672 if (includeBrowser) { 5673 // Also add browsers (all of them or only the default one) 5674 if (DEBUG_DOMAIN_VERIFICATION) { 5675 Slog.v(TAG, " ...including browsers in candidate set"); 5676 } 5677 if ((matchFlags & MATCH_ALL) != 0) { 5678 result.addAll(matchAllList); 5679 } else { 5680 // Browser/generic handling case. If there's a default browser, go straight 5681 // to that (but only if there is no other higher-priority match). 5682 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5683 int maxMatchPrio = 0; 5684 ResolveInfo defaultBrowserMatch = null; 5685 final int numCandidates = matchAllList.size(); 5686 for (int n = 0; n < numCandidates; n++) { 5687 ResolveInfo info = matchAllList.get(n); 5688 // track the highest overall match priority... 5689 if (info.priority > maxMatchPrio) { 5690 maxMatchPrio = info.priority; 5691 } 5692 // ...and the highest-priority default browser match 5693 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5694 if (defaultBrowserMatch == null 5695 || (defaultBrowserMatch.priority < info.priority)) { 5696 if (debug) { 5697 Slog.v(TAG, "Considering default browser match " + info); 5698 } 5699 defaultBrowserMatch = info; 5700 } 5701 } 5702 } 5703 if (defaultBrowserMatch != null 5704 && defaultBrowserMatch.priority >= maxMatchPrio 5705 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5706 { 5707 if (debug) { 5708 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5709 } 5710 result.add(defaultBrowserMatch); 5711 } else { 5712 result.addAll(matchAllList); 5713 } 5714 } 5715 5716 // If there is nothing selected, add all candidates and remove the ones that the user 5717 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5718 if (result.size() == 0) { 5719 result.addAll(candidates); 5720 result.removeAll(neverList); 5721 } 5722 } 5723 } 5724 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5725 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5726 result.size()); 5727 for (ResolveInfo info : result) { 5728 Slog.v(TAG, " + " + info.activityInfo); 5729 } 5730 } 5731 return result; 5732 } 5733 5734 // Returns a packed value as a long: 5735 // 5736 // high 'int'-sized word: link status: undefined/ask/never/always. 5737 // low 'int'-sized word: relative priority among 'always' results. 5738 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5739 long result = ps.getDomainVerificationStatusForUser(userId); 5740 // if none available, get the master status 5741 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5742 if (ps.getIntentFilterVerificationInfo() != null) { 5743 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5744 } 5745 } 5746 return result; 5747 } 5748 5749 private ResolveInfo querySkipCurrentProfileIntents( 5750 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5751 int flags, int sourceUserId) { 5752 if (matchingFilters != null) { 5753 int size = matchingFilters.size(); 5754 for (int i = 0; i < size; i ++) { 5755 CrossProfileIntentFilter filter = matchingFilters.get(i); 5756 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5757 // Checking if there are activities in the target user that can handle the 5758 // intent. 5759 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5760 resolvedType, flags, sourceUserId); 5761 if (resolveInfo != null) { 5762 return resolveInfo; 5763 } 5764 } 5765 } 5766 } 5767 return null; 5768 } 5769 5770 // Return matching ResolveInfo in target user if any. 5771 private ResolveInfo queryCrossProfileIntents( 5772 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5773 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5774 if (matchingFilters != null) { 5775 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5776 // match the same intent. For performance reasons, it is better not to 5777 // run queryIntent twice for the same userId 5778 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5779 int size = matchingFilters.size(); 5780 for (int i = 0; i < size; i++) { 5781 CrossProfileIntentFilter filter = matchingFilters.get(i); 5782 int targetUserId = filter.getTargetUserId(); 5783 boolean skipCurrentProfile = 5784 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5785 boolean skipCurrentProfileIfNoMatchFound = 5786 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5787 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5788 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5789 // Checking if there are activities in the target user that can handle the 5790 // intent. 5791 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5792 resolvedType, flags, sourceUserId); 5793 if (resolveInfo != null) return resolveInfo; 5794 alreadyTriedUserIds.put(targetUserId, true); 5795 } 5796 } 5797 } 5798 return null; 5799 } 5800 5801 /** 5802 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5803 * will forward the intent to the filter's target user. 5804 * Otherwise, returns null. 5805 */ 5806 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5807 String resolvedType, int flags, int sourceUserId) { 5808 int targetUserId = filter.getTargetUserId(); 5809 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5810 resolvedType, flags, targetUserId); 5811 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5812 // If all the matches in the target profile are suspended, return null. 5813 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5814 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5815 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5816 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5817 targetUserId); 5818 } 5819 } 5820 } 5821 return null; 5822 } 5823 5824 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5825 int sourceUserId, int targetUserId) { 5826 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5827 long ident = Binder.clearCallingIdentity(); 5828 boolean targetIsProfile; 5829 try { 5830 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5831 } finally { 5832 Binder.restoreCallingIdentity(ident); 5833 } 5834 String className; 5835 if (targetIsProfile) { 5836 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5837 } else { 5838 className = FORWARD_INTENT_TO_PARENT; 5839 } 5840 ComponentName forwardingActivityComponentName = new ComponentName( 5841 mAndroidApplication.packageName, className); 5842 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5843 sourceUserId); 5844 if (!targetIsProfile) { 5845 forwardingActivityInfo.showUserIcon = targetUserId; 5846 forwardingResolveInfo.noResourceId = true; 5847 } 5848 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5849 forwardingResolveInfo.priority = 0; 5850 forwardingResolveInfo.preferredOrder = 0; 5851 forwardingResolveInfo.match = 0; 5852 forwardingResolveInfo.isDefault = true; 5853 forwardingResolveInfo.filter = filter; 5854 forwardingResolveInfo.targetUserId = targetUserId; 5855 return forwardingResolveInfo; 5856 } 5857 5858 @Override 5859 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5860 Intent[] specifics, String[] specificTypes, Intent intent, 5861 String resolvedType, int flags, int userId) { 5862 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5863 specificTypes, intent, resolvedType, flags, userId)); 5864 } 5865 5866 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5867 Intent[] specifics, String[] specificTypes, Intent intent, 5868 String resolvedType, int flags, int userId) { 5869 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5870 flags = updateFlagsForResolve(flags, userId, intent); 5871 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5872 false /* requireFullPermission */, false /* checkShell */, 5873 "query intent activity options"); 5874 final String resultsAction = intent.getAction(); 5875 5876 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5877 | PackageManager.GET_RESOLVED_FILTER, userId); 5878 5879 if (DEBUG_INTENT_MATCHING) { 5880 Log.v(TAG, "Query " + intent + ": " + results); 5881 } 5882 5883 int specificsPos = 0; 5884 int N; 5885 5886 // todo: note that the algorithm used here is O(N^2). This 5887 // isn't a problem in our current environment, but if we start running 5888 // into situations where we have more than 5 or 10 matches then this 5889 // should probably be changed to something smarter... 5890 5891 // First we go through and resolve each of the specific items 5892 // that were supplied, taking care of removing any corresponding 5893 // duplicate items in the generic resolve list. 5894 if (specifics != null) { 5895 for (int i=0; i<specifics.length; i++) { 5896 final Intent sintent = specifics[i]; 5897 if (sintent == null) { 5898 continue; 5899 } 5900 5901 if (DEBUG_INTENT_MATCHING) { 5902 Log.v(TAG, "Specific #" + i + ": " + sintent); 5903 } 5904 5905 String action = sintent.getAction(); 5906 if (resultsAction != null && resultsAction.equals(action)) { 5907 // If this action was explicitly requested, then don't 5908 // remove things that have it. 5909 action = null; 5910 } 5911 5912 ResolveInfo ri = null; 5913 ActivityInfo ai = null; 5914 5915 ComponentName comp = sintent.getComponent(); 5916 if (comp == null) { 5917 ri = resolveIntent( 5918 sintent, 5919 specificTypes != null ? specificTypes[i] : null, 5920 flags, userId); 5921 if (ri == null) { 5922 continue; 5923 } 5924 if (ri == mResolveInfo) { 5925 // ACK! Must do something better with this. 5926 } 5927 ai = ri.activityInfo; 5928 comp = new ComponentName(ai.applicationInfo.packageName, 5929 ai.name); 5930 } else { 5931 ai = getActivityInfo(comp, flags, userId); 5932 if (ai == null) { 5933 continue; 5934 } 5935 } 5936 5937 // Look for any generic query activities that are duplicates 5938 // of this specific one, and remove them from the results. 5939 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5940 N = results.size(); 5941 int j; 5942 for (j=specificsPos; j<N; j++) { 5943 ResolveInfo sri = results.get(j); 5944 if ((sri.activityInfo.name.equals(comp.getClassName()) 5945 && sri.activityInfo.applicationInfo.packageName.equals( 5946 comp.getPackageName())) 5947 || (action != null && sri.filter.matchAction(action))) { 5948 results.remove(j); 5949 if (DEBUG_INTENT_MATCHING) Log.v( 5950 TAG, "Removing duplicate item from " + j 5951 + " due to specific " + specificsPos); 5952 if (ri == null) { 5953 ri = sri; 5954 } 5955 j--; 5956 N--; 5957 } 5958 } 5959 5960 // Add this specific item to its proper place. 5961 if (ri == null) { 5962 ri = new ResolveInfo(); 5963 ri.activityInfo = ai; 5964 } 5965 results.add(specificsPos, ri); 5966 ri.specificIndex = i; 5967 specificsPos++; 5968 } 5969 } 5970 5971 // Now we go through the remaining generic results and remove any 5972 // duplicate actions that are found here. 5973 N = results.size(); 5974 for (int i=specificsPos; i<N-1; i++) { 5975 final ResolveInfo rii = results.get(i); 5976 if (rii.filter == null) { 5977 continue; 5978 } 5979 5980 // Iterate over all of the actions of this result's intent 5981 // filter... typically this should be just one. 5982 final Iterator<String> it = rii.filter.actionsIterator(); 5983 if (it == null) { 5984 continue; 5985 } 5986 while (it.hasNext()) { 5987 final String action = it.next(); 5988 if (resultsAction != null && resultsAction.equals(action)) { 5989 // If this action was explicitly requested, then don't 5990 // remove things that have it. 5991 continue; 5992 } 5993 for (int j=i+1; j<N; j++) { 5994 final ResolveInfo rij = results.get(j); 5995 if (rij.filter != null && rij.filter.hasAction(action)) { 5996 results.remove(j); 5997 if (DEBUG_INTENT_MATCHING) Log.v( 5998 TAG, "Removing duplicate item from " + j 5999 + " due to action " + action + " at " + i); 6000 j--; 6001 N--; 6002 } 6003 } 6004 } 6005 6006 // If the caller didn't request filter information, drop it now 6007 // so we don't have to marshall/unmarshall it. 6008 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6009 rii.filter = null; 6010 } 6011 } 6012 6013 // Filter out the caller activity if so requested. 6014 if (caller != null) { 6015 N = results.size(); 6016 for (int i=0; i<N; i++) { 6017 ActivityInfo ainfo = results.get(i).activityInfo; 6018 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6019 && caller.getClassName().equals(ainfo.name)) { 6020 results.remove(i); 6021 break; 6022 } 6023 } 6024 } 6025 6026 // If the caller didn't request filter information, 6027 // drop them now so we don't have to 6028 // marshall/unmarshall it. 6029 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6030 N = results.size(); 6031 for (int i=0; i<N; i++) { 6032 results.get(i).filter = null; 6033 } 6034 } 6035 6036 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6037 return results; 6038 } 6039 6040 @Override 6041 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6042 String resolvedType, int flags, int userId) { 6043 return new ParceledListSlice<>( 6044 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6045 } 6046 6047 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6048 String resolvedType, int flags, int userId) { 6049 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6050 flags = updateFlagsForResolve(flags, userId, intent); 6051 ComponentName comp = intent.getComponent(); 6052 if (comp == null) { 6053 if (intent.getSelector() != null) { 6054 intent = intent.getSelector(); 6055 comp = intent.getComponent(); 6056 } 6057 } 6058 if (comp != null) { 6059 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6060 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6061 if (ai != null) { 6062 ResolveInfo ri = new ResolveInfo(); 6063 ri.activityInfo = ai; 6064 list.add(ri); 6065 } 6066 return list; 6067 } 6068 6069 // reader 6070 synchronized (mPackages) { 6071 String pkgName = intent.getPackage(); 6072 if (pkgName == null) { 6073 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6074 } 6075 final PackageParser.Package pkg = mPackages.get(pkgName); 6076 if (pkg != null) { 6077 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6078 userId); 6079 } 6080 return Collections.emptyList(); 6081 } 6082 } 6083 6084 @Override 6085 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6086 if (!sUserManager.exists(userId)) return null; 6087 flags = updateFlagsForResolve(flags, userId, intent); 6088 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6089 if (query != null) { 6090 if (query.size() >= 1) { 6091 // If there is more than one service with the same priority, 6092 // just arbitrarily pick the first one. 6093 return query.get(0); 6094 } 6095 } 6096 return null; 6097 } 6098 6099 @Override 6100 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6101 String resolvedType, int flags, int userId) { 6102 return new ParceledListSlice<>( 6103 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6104 } 6105 6106 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6107 String resolvedType, int flags, int userId) { 6108 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6109 flags = updateFlagsForResolve(flags, userId, intent); 6110 ComponentName comp = intent.getComponent(); 6111 if (comp == null) { 6112 if (intent.getSelector() != null) { 6113 intent = intent.getSelector(); 6114 comp = intent.getComponent(); 6115 } 6116 } 6117 if (comp != null) { 6118 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6119 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6120 if (si != null) { 6121 final ResolveInfo ri = new ResolveInfo(); 6122 ri.serviceInfo = si; 6123 list.add(ri); 6124 } 6125 return list; 6126 } 6127 6128 // reader 6129 synchronized (mPackages) { 6130 String pkgName = intent.getPackage(); 6131 if (pkgName == null) { 6132 return mServices.queryIntent(intent, resolvedType, flags, userId); 6133 } 6134 final PackageParser.Package pkg = mPackages.get(pkgName); 6135 if (pkg != null) { 6136 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6137 userId); 6138 } 6139 return Collections.emptyList(); 6140 } 6141 } 6142 6143 @Override 6144 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6145 String resolvedType, int flags, int userId) { 6146 return new ParceledListSlice<>( 6147 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6148 } 6149 6150 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6151 Intent intent, String resolvedType, int flags, int userId) { 6152 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6153 flags = updateFlagsForResolve(flags, userId, intent); 6154 ComponentName comp = intent.getComponent(); 6155 if (comp == null) { 6156 if (intent.getSelector() != null) { 6157 intent = intent.getSelector(); 6158 comp = intent.getComponent(); 6159 } 6160 } 6161 if (comp != null) { 6162 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6163 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6164 if (pi != null) { 6165 final ResolveInfo ri = new ResolveInfo(); 6166 ri.providerInfo = pi; 6167 list.add(ri); 6168 } 6169 return list; 6170 } 6171 6172 // reader 6173 synchronized (mPackages) { 6174 String pkgName = intent.getPackage(); 6175 if (pkgName == null) { 6176 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6177 } 6178 final PackageParser.Package pkg = mPackages.get(pkgName); 6179 if (pkg != null) { 6180 return mProviders.queryIntentForPackage( 6181 intent, resolvedType, flags, pkg.providers, userId); 6182 } 6183 return Collections.emptyList(); 6184 } 6185 } 6186 6187 @Override 6188 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6189 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6190 flags = updateFlagsForPackage(flags, userId, null); 6191 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6192 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6193 true /* requireFullPermission */, false /* checkShell */, 6194 "get installed packages"); 6195 6196 // writer 6197 synchronized (mPackages) { 6198 ArrayList<PackageInfo> list; 6199 if (listUninstalled) { 6200 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6201 for (PackageSetting ps : mSettings.mPackages.values()) { 6202 final PackageInfo pi; 6203 if (ps.pkg != null) { 6204 pi = generatePackageInfo(ps, flags, userId); 6205 } else { 6206 pi = generatePackageInfo(ps, flags, userId); 6207 } 6208 if (pi != null) { 6209 list.add(pi); 6210 } 6211 } 6212 } else { 6213 list = new ArrayList<PackageInfo>(mPackages.size()); 6214 for (PackageParser.Package p : mPackages.values()) { 6215 final PackageInfo pi = 6216 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6217 if (pi != null) { 6218 list.add(pi); 6219 } 6220 } 6221 } 6222 6223 return new ParceledListSlice<PackageInfo>(list); 6224 } 6225 } 6226 6227 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6228 String[] permissions, boolean[] tmp, int flags, int userId) { 6229 int numMatch = 0; 6230 final PermissionsState permissionsState = ps.getPermissionsState(); 6231 for (int i=0; i<permissions.length; i++) { 6232 final String permission = permissions[i]; 6233 if (permissionsState.hasPermission(permission, userId)) { 6234 tmp[i] = true; 6235 numMatch++; 6236 } else { 6237 tmp[i] = false; 6238 } 6239 } 6240 if (numMatch == 0) { 6241 return; 6242 } 6243 final PackageInfo pi; 6244 if (ps.pkg != null) { 6245 pi = generatePackageInfo(ps, flags, userId); 6246 } else { 6247 pi = generatePackageInfo(ps, flags, userId); 6248 } 6249 // The above might return null in cases of uninstalled apps or install-state 6250 // skew across users/profiles. 6251 if (pi != null) { 6252 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6253 if (numMatch == permissions.length) { 6254 pi.requestedPermissions = permissions; 6255 } else { 6256 pi.requestedPermissions = new String[numMatch]; 6257 numMatch = 0; 6258 for (int i=0; i<permissions.length; i++) { 6259 if (tmp[i]) { 6260 pi.requestedPermissions[numMatch] = permissions[i]; 6261 numMatch++; 6262 } 6263 } 6264 } 6265 } 6266 list.add(pi); 6267 } 6268 } 6269 6270 @Override 6271 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6272 String[] permissions, int flags, int userId) { 6273 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6274 flags = updateFlagsForPackage(flags, userId, permissions); 6275 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6276 6277 // writer 6278 synchronized (mPackages) { 6279 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6280 boolean[] tmpBools = new boolean[permissions.length]; 6281 if (listUninstalled) { 6282 for (PackageSetting ps : mSettings.mPackages.values()) { 6283 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6284 } 6285 } else { 6286 for (PackageParser.Package pkg : mPackages.values()) { 6287 PackageSetting ps = (PackageSetting)pkg.mExtras; 6288 if (ps != null) { 6289 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6290 userId); 6291 } 6292 } 6293 } 6294 6295 return new ParceledListSlice<PackageInfo>(list); 6296 } 6297 } 6298 6299 @Override 6300 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6301 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6302 flags = updateFlagsForApplication(flags, userId, null); 6303 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6304 6305 // writer 6306 synchronized (mPackages) { 6307 ArrayList<ApplicationInfo> list; 6308 if (listUninstalled) { 6309 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6310 for (PackageSetting ps : mSettings.mPackages.values()) { 6311 ApplicationInfo ai; 6312 if (ps.pkg != null) { 6313 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6314 ps.readUserState(userId), userId); 6315 } else { 6316 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6317 } 6318 if (ai != null) { 6319 list.add(ai); 6320 } 6321 } 6322 } else { 6323 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6324 for (PackageParser.Package p : mPackages.values()) { 6325 if (p.mExtras != null) { 6326 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6327 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6328 if (ai != null) { 6329 list.add(ai); 6330 } 6331 } 6332 } 6333 } 6334 6335 return new ParceledListSlice<ApplicationInfo>(list); 6336 } 6337 } 6338 6339 @Override 6340 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6341 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6342 return null; 6343 } 6344 6345 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6346 "getEphemeralApplications"); 6347 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6348 true /* requireFullPermission */, false /* checkShell */, 6349 "getEphemeralApplications"); 6350 synchronized (mPackages) { 6351 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6352 .getEphemeralApplicationsLPw(userId); 6353 if (ephemeralApps != null) { 6354 return new ParceledListSlice<>(ephemeralApps); 6355 } 6356 } 6357 return null; 6358 } 6359 6360 @Override 6361 public boolean isEphemeralApplication(String packageName, int userId) { 6362 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6363 true /* requireFullPermission */, false /* checkShell */, 6364 "isEphemeral"); 6365 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6366 return false; 6367 } 6368 6369 if (!isCallerSameApp(packageName)) { 6370 return false; 6371 } 6372 synchronized (mPackages) { 6373 PackageParser.Package pkg = mPackages.get(packageName); 6374 if (pkg != null) { 6375 return pkg.applicationInfo.isEphemeralApp(); 6376 } 6377 } 6378 return false; 6379 } 6380 6381 @Override 6382 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6383 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6384 return null; 6385 } 6386 6387 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6388 true /* requireFullPermission */, false /* checkShell */, 6389 "getCookie"); 6390 if (!isCallerSameApp(packageName)) { 6391 return null; 6392 } 6393 synchronized (mPackages) { 6394 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6395 packageName, userId); 6396 } 6397 } 6398 6399 @Override 6400 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6401 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6402 return true; 6403 } 6404 6405 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6406 true /* requireFullPermission */, true /* checkShell */, 6407 "setCookie"); 6408 if (!isCallerSameApp(packageName)) { 6409 return false; 6410 } 6411 synchronized (mPackages) { 6412 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6413 packageName, cookie, userId); 6414 } 6415 } 6416 6417 @Override 6418 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6419 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6420 return null; 6421 } 6422 6423 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6424 "getEphemeralApplicationIcon"); 6425 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6426 true /* requireFullPermission */, false /* checkShell */, 6427 "getEphemeralApplicationIcon"); 6428 synchronized (mPackages) { 6429 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6430 packageName, userId); 6431 } 6432 } 6433 6434 private boolean isCallerSameApp(String packageName) { 6435 PackageParser.Package pkg = mPackages.get(packageName); 6436 return pkg != null 6437 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6438 } 6439 6440 @Override 6441 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6442 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6443 } 6444 6445 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6446 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6447 6448 // reader 6449 synchronized (mPackages) { 6450 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6451 final int userId = UserHandle.getCallingUserId(); 6452 while (i.hasNext()) { 6453 final PackageParser.Package p = i.next(); 6454 if (p.applicationInfo == null) continue; 6455 6456 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6457 && !p.applicationInfo.isDirectBootAware(); 6458 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6459 && p.applicationInfo.isDirectBootAware(); 6460 6461 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6462 && (!mSafeMode || isSystemApp(p)) 6463 && (matchesUnaware || matchesAware)) { 6464 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6465 if (ps != null) { 6466 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6467 ps.readUserState(userId), userId); 6468 if (ai != null) { 6469 finalList.add(ai); 6470 } 6471 } 6472 } 6473 } 6474 } 6475 6476 return finalList; 6477 } 6478 6479 @Override 6480 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6481 if (!sUserManager.exists(userId)) return null; 6482 flags = updateFlagsForComponent(flags, userId, name); 6483 // reader 6484 synchronized (mPackages) { 6485 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6486 PackageSetting ps = provider != null 6487 ? mSettings.mPackages.get(provider.owner.packageName) 6488 : null; 6489 return ps != null 6490 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6491 ? PackageParser.generateProviderInfo(provider, flags, 6492 ps.readUserState(userId), userId) 6493 : null; 6494 } 6495 } 6496 6497 /** 6498 * @deprecated 6499 */ 6500 @Deprecated 6501 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6502 // reader 6503 synchronized (mPackages) { 6504 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6505 .entrySet().iterator(); 6506 final int userId = UserHandle.getCallingUserId(); 6507 while (i.hasNext()) { 6508 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6509 PackageParser.Provider p = entry.getValue(); 6510 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6511 6512 if (ps != null && p.syncable 6513 && (!mSafeMode || (p.info.applicationInfo.flags 6514 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6515 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6516 ps.readUserState(userId), userId); 6517 if (info != null) { 6518 outNames.add(entry.getKey()); 6519 outInfo.add(info); 6520 } 6521 } 6522 } 6523 } 6524 } 6525 6526 @Override 6527 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6528 int uid, int flags) { 6529 final int userId = processName != null ? UserHandle.getUserId(uid) 6530 : UserHandle.getCallingUserId(); 6531 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6532 flags = updateFlagsForComponent(flags, userId, processName); 6533 6534 ArrayList<ProviderInfo> finalList = null; 6535 // reader 6536 synchronized (mPackages) { 6537 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6538 while (i.hasNext()) { 6539 final PackageParser.Provider p = i.next(); 6540 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6541 if (ps != null && p.info.authority != null 6542 && (processName == null 6543 || (p.info.processName.equals(processName) 6544 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6545 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6546 if (finalList == null) { 6547 finalList = new ArrayList<ProviderInfo>(3); 6548 } 6549 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6550 ps.readUserState(userId), userId); 6551 if (info != null) { 6552 finalList.add(info); 6553 } 6554 } 6555 } 6556 } 6557 6558 if (finalList != null) { 6559 Collections.sort(finalList, mProviderInitOrderSorter); 6560 return new ParceledListSlice<ProviderInfo>(finalList); 6561 } 6562 6563 return ParceledListSlice.emptyList(); 6564 } 6565 6566 @Override 6567 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6568 // reader 6569 synchronized (mPackages) { 6570 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6571 return PackageParser.generateInstrumentationInfo(i, flags); 6572 } 6573 } 6574 6575 @Override 6576 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6577 String targetPackage, int flags) { 6578 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6579 } 6580 6581 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6582 int flags) { 6583 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6584 6585 // reader 6586 synchronized (mPackages) { 6587 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6588 while (i.hasNext()) { 6589 final PackageParser.Instrumentation p = i.next(); 6590 if (targetPackage == null 6591 || targetPackage.equals(p.info.targetPackage)) { 6592 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6593 flags); 6594 if (ii != null) { 6595 finalList.add(ii); 6596 } 6597 } 6598 } 6599 } 6600 6601 return finalList; 6602 } 6603 6604 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6605 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6606 if (overlays == null) { 6607 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6608 return; 6609 } 6610 for (PackageParser.Package opkg : overlays.values()) { 6611 // Not much to do if idmap fails: we already logged the error 6612 // and we certainly don't want to abort installation of pkg simply 6613 // because an overlay didn't fit properly. For these reasons, 6614 // ignore the return value of createIdmapForPackagePairLI. 6615 createIdmapForPackagePairLI(pkg, opkg); 6616 } 6617 } 6618 6619 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6620 PackageParser.Package opkg) { 6621 if (!opkg.mTrustedOverlay) { 6622 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6623 opkg.baseCodePath + ": overlay not trusted"); 6624 return false; 6625 } 6626 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6627 if (overlaySet == null) { 6628 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6629 opkg.baseCodePath + " but target package has no known overlays"); 6630 return false; 6631 } 6632 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6633 // TODO: generate idmap for split APKs 6634 try { 6635 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6636 } catch (InstallerException e) { 6637 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6638 + opkg.baseCodePath); 6639 return false; 6640 } 6641 PackageParser.Package[] overlayArray = 6642 overlaySet.values().toArray(new PackageParser.Package[0]); 6643 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6644 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6645 return p1.mOverlayPriority - p2.mOverlayPriority; 6646 } 6647 }; 6648 Arrays.sort(overlayArray, cmp); 6649 6650 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6651 int i = 0; 6652 for (PackageParser.Package p : overlayArray) { 6653 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6654 } 6655 return true; 6656 } 6657 6658 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6659 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 6660 try { 6661 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6662 } finally { 6663 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6664 } 6665 } 6666 6667 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6668 final File[] files = dir.listFiles(); 6669 if (ArrayUtils.isEmpty(files)) { 6670 Log.d(TAG, "No files in app dir " + dir); 6671 return; 6672 } 6673 6674 if (DEBUG_PACKAGE_SCANNING) { 6675 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6676 + " flags=0x" + Integer.toHexString(parseFlags)); 6677 } 6678 6679 for (File file : files) { 6680 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6681 && !PackageInstallerService.isStageName(file.getName()); 6682 if (!isPackage) { 6683 // Ignore entries which are not packages 6684 continue; 6685 } 6686 try { 6687 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6688 scanFlags, currentTime, null); 6689 } catch (PackageManagerException e) { 6690 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6691 6692 // Delete invalid userdata apps 6693 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6694 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6695 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6696 removeCodePathLI(file); 6697 } 6698 } 6699 } 6700 } 6701 6702 private static File getSettingsProblemFile() { 6703 File dataDir = Environment.getDataDirectory(); 6704 File systemDir = new File(dataDir, "system"); 6705 File fname = new File(systemDir, "uiderrors.txt"); 6706 return fname; 6707 } 6708 6709 static void reportSettingsProblem(int priority, String msg) { 6710 logCriticalInfo(priority, msg); 6711 } 6712 6713 static void logCriticalInfo(int priority, String msg) { 6714 Slog.println(priority, TAG, msg); 6715 EventLogTags.writePmCriticalInfo(msg); 6716 try { 6717 File fname = getSettingsProblemFile(); 6718 FileOutputStream out = new FileOutputStream(fname, true); 6719 PrintWriter pw = new FastPrintWriter(out); 6720 SimpleDateFormat formatter = new SimpleDateFormat(); 6721 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6722 pw.println(dateString + ": " + msg); 6723 pw.close(); 6724 FileUtils.setPermissions( 6725 fname.toString(), 6726 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6727 -1, -1); 6728 } catch (java.io.IOException e) { 6729 } 6730 } 6731 6732 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6733 if (srcFile.isDirectory()) { 6734 final File baseFile = new File(pkg.baseCodePath); 6735 long maxModifiedTime = baseFile.lastModified(); 6736 if (pkg.splitCodePaths != null) { 6737 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6738 final File splitFile = new File(pkg.splitCodePaths[i]); 6739 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6740 } 6741 } 6742 return maxModifiedTime; 6743 } 6744 return srcFile.lastModified(); 6745 } 6746 6747 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6748 final int policyFlags) throws PackageManagerException { 6749 // When upgrading from pre-N MR1, verify the package time stamp using the package 6750 // directory and not the APK file. 6751 final long lastModifiedTime = mIsPreNMR1Upgrade 6752 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 6753 if (ps != null 6754 && ps.codePath.equals(srcFile) 6755 && ps.timeStamp == lastModifiedTime 6756 && !isCompatSignatureUpdateNeeded(pkg) 6757 && !isRecoverSignatureUpdateNeeded(pkg)) { 6758 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6759 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6760 ArraySet<PublicKey> signingKs; 6761 synchronized (mPackages) { 6762 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6763 } 6764 if (ps.signatures.mSignatures != null 6765 && ps.signatures.mSignatures.length != 0 6766 && signingKs != null) { 6767 // Optimization: reuse the existing cached certificates 6768 // if the package appears to be unchanged. 6769 pkg.mSignatures = ps.signatures.mSignatures; 6770 pkg.mSigningKeys = signingKs; 6771 return; 6772 } 6773 6774 Slog.w(TAG, "PackageSetting for " + ps.name 6775 + " is missing signatures. Collecting certs again to recover them."); 6776 } else { 6777 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 6778 } 6779 6780 try { 6781 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 6782 PackageParser.collectCertificates(pkg, policyFlags); 6783 } catch (PackageParserException e) { 6784 throw PackageManagerException.from(e); 6785 } finally { 6786 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6787 } 6788 } 6789 6790 /** 6791 * Traces a package scan. 6792 * @see #scanPackageLI(File, int, int, long, UserHandle) 6793 */ 6794 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6795 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6796 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 6797 try { 6798 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6799 } finally { 6800 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6801 } 6802 } 6803 6804 /** 6805 * Scans a package and returns the newly parsed package. 6806 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6807 */ 6808 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6809 long currentTime, UserHandle user) throws PackageManagerException { 6810 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6811 PackageParser pp = new PackageParser(); 6812 pp.setSeparateProcesses(mSeparateProcesses); 6813 pp.setOnlyCoreApps(mOnlyCore); 6814 pp.setDisplayMetrics(mMetrics); 6815 6816 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6817 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6818 } 6819 6820 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6821 final PackageParser.Package pkg; 6822 try { 6823 pkg = pp.parsePackage(scanFile, parseFlags); 6824 } catch (PackageParserException e) { 6825 throw PackageManagerException.from(e); 6826 } finally { 6827 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6828 } 6829 6830 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6831 } 6832 6833 /** 6834 * Scans a package and returns the newly parsed package. 6835 * @throws PackageManagerException on a parse error. 6836 */ 6837 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6838 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6839 throws PackageManagerException { 6840 // If the package has children and this is the first dive in the function 6841 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6842 // packages (parent and children) would be successfully scanned before the 6843 // actual scan since scanning mutates internal state and we want to atomically 6844 // install the package and its children. 6845 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6846 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6847 scanFlags |= SCAN_CHECK_ONLY; 6848 } 6849 } else { 6850 scanFlags &= ~SCAN_CHECK_ONLY; 6851 } 6852 6853 // Scan the parent 6854 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6855 scanFlags, currentTime, user); 6856 6857 // Scan the children 6858 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6859 for (int i = 0; i < childCount; i++) { 6860 PackageParser.Package childPackage = pkg.childPackages.get(i); 6861 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6862 currentTime, user); 6863 } 6864 6865 6866 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6867 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6868 } 6869 6870 return scannedPkg; 6871 } 6872 6873 /** 6874 * Scans a package and returns the newly parsed package. 6875 * @throws PackageManagerException on a parse error. 6876 */ 6877 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6878 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6879 throws PackageManagerException { 6880 PackageSetting ps = null; 6881 PackageSetting updatedPkg; 6882 // reader 6883 synchronized (mPackages) { 6884 // Look to see if we already know about this package. 6885 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 6886 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6887 // This package has been renamed to its original name. Let's 6888 // use that. 6889 ps = mSettings.getPackageLPr(oldName); 6890 } 6891 // If there was no original package, see one for the real package name. 6892 if (ps == null) { 6893 ps = mSettings.getPackageLPr(pkg.packageName); 6894 } 6895 // Check to see if this package could be hiding/updating a system 6896 // package. Must look for it either under the original or real 6897 // package name depending on our state. 6898 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6899 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6900 6901 // If this is a package we don't know about on the system partition, we 6902 // may need to remove disabled child packages on the system partition 6903 // or may need to not add child packages if the parent apk is updated 6904 // on the data partition and no longer defines this child package. 6905 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6906 // If this is a parent package for an updated system app and this system 6907 // app got an OTA update which no longer defines some of the child packages 6908 // we have to prune them from the disabled system packages. 6909 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6910 if (disabledPs != null) { 6911 final int scannedChildCount = (pkg.childPackages != null) 6912 ? pkg.childPackages.size() : 0; 6913 final int disabledChildCount = disabledPs.childPackageNames != null 6914 ? disabledPs.childPackageNames.size() : 0; 6915 for (int i = 0; i < disabledChildCount; i++) { 6916 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6917 boolean disabledPackageAvailable = false; 6918 for (int j = 0; j < scannedChildCount; j++) { 6919 PackageParser.Package childPkg = pkg.childPackages.get(j); 6920 if (childPkg.packageName.equals(disabledChildPackageName)) { 6921 disabledPackageAvailable = true; 6922 break; 6923 } 6924 } 6925 if (!disabledPackageAvailable) { 6926 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6927 } 6928 } 6929 } 6930 } 6931 } 6932 6933 boolean updatedPkgBetter = false; 6934 // First check if this is a system package that may involve an update 6935 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6936 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6937 // it needs to drop FLAG_PRIVILEGED. 6938 if (locationIsPrivileged(scanFile)) { 6939 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6940 } else { 6941 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6942 } 6943 6944 if (ps != null && !ps.codePath.equals(scanFile)) { 6945 // The path has changed from what was last scanned... check the 6946 // version of the new path against what we have stored to determine 6947 // what to do. 6948 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6949 if (pkg.mVersionCode <= ps.versionCode) { 6950 // The system package has been updated and the code path does not match 6951 // Ignore entry. Skip it. 6952 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6953 + " ignored: updated version " + ps.versionCode 6954 + " better than this " + pkg.mVersionCode); 6955 if (!updatedPkg.codePath.equals(scanFile)) { 6956 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6957 + ps.name + " changing from " + updatedPkg.codePathString 6958 + " to " + scanFile); 6959 updatedPkg.codePath = scanFile; 6960 updatedPkg.codePathString = scanFile.toString(); 6961 updatedPkg.resourcePath = scanFile; 6962 updatedPkg.resourcePathString = scanFile.toString(); 6963 } 6964 updatedPkg.pkg = pkg; 6965 updatedPkg.versionCode = pkg.mVersionCode; 6966 6967 // Update the disabled system child packages to point to the package too. 6968 final int childCount = updatedPkg.childPackageNames != null 6969 ? updatedPkg.childPackageNames.size() : 0; 6970 for (int i = 0; i < childCount; i++) { 6971 String childPackageName = updatedPkg.childPackageNames.get(i); 6972 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6973 childPackageName); 6974 if (updatedChildPkg != null) { 6975 updatedChildPkg.pkg = pkg; 6976 updatedChildPkg.versionCode = pkg.mVersionCode; 6977 } 6978 } 6979 6980 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6981 + scanFile + " ignored: updated version " + ps.versionCode 6982 + " better than this " + pkg.mVersionCode); 6983 } else { 6984 // The current app on the system partition is better than 6985 // what we have updated to on the data partition; switch 6986 // back to the system partition version. 6987 // At this point, its safely assumed that package installation for 6988 // apps in system partition will go through. If not there won't be a working 6989 // version of the app 6990 // writer 6991 synchronized (mPackages) { 6992 // Just remove the loaded entries from package lists. 6993 mPackages.remove(ps.name); 6994 } 6995 6996 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6997 + " reverting from " + ps.codePathString 6998 + ": new version " + pkg.mVersionCode 6999 + " better than installed " + ps.versionCode); 7000 7001 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7002 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7003 synchronized (mInstallLock) { 7004 args.cleanUpResourcesLI(); 7005 } 7006 synchronized (mPackages) { 7007 mSettings.enableSystemPackageLPw(ps.name); 7008 } 7009 updatedPkgBetter = true; 7010 } 7011 } 7012 } 7013 7014 if (updatedPkg != null) { 7015 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7016 // initially 7017 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7018 7019 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7020 // flag set initially 7021 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7022 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7023 } 7024 } 7025 7026 // Verify certificates against what was last scanned 7027 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7028 7029 /* 7030 * A new system app appeared, but we already had a non-system one of the 7031 * same name installed earlier. 7032 */ 7033 boolean shouldHideSystemApp = false; 7034 if (updatedPkg == null && ps != null 7035 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7036 /* 7037 * Check to make sure the signatures match first. If they don't, 7038 * wipe the installed application and its data. 7039 */ 7040 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7041 != PackageManager.SIGNATURE_MATCH) { 7042 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7043 + " signatures don't match existing userdata copy; removing"); 7044 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7045 "scanPackageInternalLI")) { 7046 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7047 } 7048 ps = null; 7049 } else { 7050 /* 7051 * If the newly-added system app is an older version than the 7052 * already installed version, hide it. It will be scanned later 7053 * and re-added like an update. 7054 */ 7055 if (pkg.mVersionCode <= ps.versionCode) { 7056 shouldHideSystemApp = true; 7057 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7058 + " but new version " + pkg.mVersionCode + " better than installed " 7059 + ps.versionCode + "; hiding system"); 7060 } else { 7061 /* 7062 * The newly found system app is a newer version that the 7063 * one previously installed. Simply remove the 7064 * already-installed application and replace it with our own 7065 * while keeping the application data. 7066 */ 7067 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7068 + " reverting from " + ps.codePathString + ": new version " 7069 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7070 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7071 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7072 synchronized (mInstallLock) { 7073 args.cleanUpResourcesLI(); 7074 } 7075 } 7076 } 7077 } 7078 7079 // The apk is forward locked (not public) if its code and resources 7080 // are kept in different files. (except for app in either system or 7081 // vendor path). 7082 // TODO grab this value from PackageSettings 7083 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7084 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7085 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7086 } 7087 } 7088 7089 // TODO: extend to support forward-locked splits 7090 String resourcePath = null; 7091 String baseResourcePath = null; 7092 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7093 if (ps != null && ps.resourcePathString != null) { 7094 resourcePath = ps.resourcePathString; 7095 baseResourcePath = ps.resourcePathString; 7096 } else { 7097 // Should not happen at all. Just log an error. 7098 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7099 } 7100 } else { 7101 resourcePath = pkg.codePath; 7102 baseResourcePath = pkg.baseCodePath; 7103 } 7104 7105 // Set application objects path explicitly. 7106 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7107 pkg.setApplicationInfoCodePath(pkg.codePath); 7108 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7109 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7110 pkg.setApplicationInfoResourcePath(resourcePath); 7111 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7112 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7113 7114 // Note that we invoke the following method only if we are about to unpack an application 7115 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7116 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7117 7118 /* 7119 * If the system app should be overridden by a previously installed 7120 * data, hide the system app now and let the /data/app scan pick it up 7121 * again. 7122 */ 7123 if (shouldHideSystemApp) { 7124 synchronized (mPackages) { 7125 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7126 } 7127 } 7128 7129 return scannedPkg; 7130 } 7131 7132 private static String fixProcessName(String defProcessName, 7133 String processName) { 7134 if (processName == null) { 7135 return defProcessName; 7136 } 7137 return processName; 7138 } 7139 7140 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7141 throws PackageManagerException { 7142 if (pkgSetting.signatures.mSignatures != null) { 7143 // Already existing package. Make sure signatures match 7144 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7145 == PackageManager.SIGNATURE_MATCH; 7146 if (!match) { 7147 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7148 == PackageManager.SIGNATURE_MATCH; 7149 } 7150 if (!match) { 7151 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7152 == PackageManager.SIGNATURE_MATCH; 7153 } 7154 if (!match) { 7155 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7156 + pkg.packageName + " signatures do not match the " 7157 + "previously installed version; ignoring!"); 7158 } 7159 } 7160 7161 // Check for shared user signatures 7162 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7163 // Already existing package. Make sure signatures match 7164 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7165 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7166 if (!match) { 7167 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7168 == PackageManager.SIGNATURE_MATCH; 7169 } 7170 if (!match) { 7171 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7172 == PackageManager.SIGNATURE_MATCH; 7173 } 7174 if (!match) { 7175 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7176 "Package " + pkg.packageName 7177 + " has no signatures that match those in shared user " 7178 + pkgSetting.sharedUser.name + "; ignoring!"); 7179 } 7180 } 7181 } 7182 7183 /** 7184 * Enforces that only the system UID or root's UID can call a method exposed 7185 * via Binder. 7186 * 7187 * @param message used as message if SecurityException is thrown 7188 * @throws SecurityException if the caller is not system or root 7189 */ 7190 private static final void enforceSystemOrRoot(String message) { 7191 final int uid = Binder.getCallingUid(); 7192 if (uid != Process.SYSTEM_UID && uid != 0) { 7193 throw new SecurityException(message); 7194 } 7195 } 7196 7197 @Override 7198 public void performFstrimIfNeeded() { 7199 enforceSystemOrRoot("Only the system can request fstrim"); 7200 7201 // Before everything else, see whether we need to fstrim. 7202 try { 7203 IMountService ms = PackageHelper.getMountService(); 7204 if (ms != null) { 7205 boolean doTrim = false; 7206 final long interval = android.provider.Settings.Global.getLong( 7207 mContext.getContentResolver(), 7208 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7209 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7210 if (interval > 0) { 7211 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7212 if (timeSinceLast > interval) { 7213 doTrim = true; 7214 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7215 + "; running immediately"); 7216 } 7217 } 7218 if (doTrim) { 7219 final boolean dexOptDialogShown; 7220 synchronized (mPackages) { 7221 dexOptDialogShown = mDexOptDialogShown; 7222 } 7223 if (!isFirstBoot() && dexOptDialogShown) { 7224 try { 7225 ActivityManagerNative.getDefault().showBootMessage( 7226 mContext.getResources().getString( 7227 R.string.android_upgrading_fstrim), true); 7228 } catch (RemoteException e) { 7229 } 7230 } 7231 ms.runMaintenance(); 7232 } 7233 } else { 7234 Slog.e(TAG, "Mount service unavailable!"); 7235 } 7236 } catch (RemoteException e) { 7237 // Can't happen; MountService is local 7238 } 7239 } 7240 7241 @Override 7242 public void updatePackagesIfNeeded() { 7243 enforceSystemOrRoot("Only the system can request package update"); 7244 7245 // We need to re-extract after an OTA. 7246 boolean causeUpgrade = isUpgrade(); 7247 7248 // First boot or factory reset. 7249 // Note: we also handle devices that are upgrading to N right now as if it is their 7250 // first boot, as they do not have profile data. 7251 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7252 7253 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7254 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7255 7256 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7257 return; 7258 } 7259 7260 List<PackageParser.Package> pkgs; 7261 synchronized (mPackages) { 7262 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7263 } 7264 7265 final long startTime = System.nanoTime(); 7266 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7267 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7268 7269 final int elapsedTimeSeconds = 7270 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7271 7272 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7273 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7274 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7275 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7276 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7277 } 7278 7279 /** 7280 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7281 * containing statistics about the invocation. The array consists of three elements, 7282 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7283 * and {@code numberOfPackagesFailed}. 7284 */ 7285 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7286 String compilerFilter) { 7287 7288 int numberOfPackagesVisited = 0; 7289 int numberOfPackagesOptimized = 0; 7290 int numberOfPackagesSkipped = 0; 7291 int numberOfPackagesFailed = 0; 7292 final int numberOfPackagesToDexopt = pkgs.size(); 7293 7294 for (PackageParser.Package pkg : pkgs) { 7295 numberOfPackagesVisited++; 7296 7297 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7298 if (DEBUG_DEXOPT) { 7299 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7300 } 7301 numberOfPackagesSkipped++; 7302 continue; 7303 } 7304 7305 if (DEBUG_DEXOPT) { 7306 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7307 numberOfPackagesToDexopt + ": " + pkg.packageName); 7308 } 7309 7310 if (showDialog) { 7311 try { 7312 ActivityManagerNative.getDefault().showBootMessage( 7313 mContext.getResources().getString(R.string.android_upgrading_apk, 7314 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7315 } catch (RemoteException e) { 7316 } 7317 synchronized (mPackages) { 7318 mDexOptDialogShown = true; 7319 } 7320 } 7321 7322 // If the OTA updates a system app which was previously preopted to a non-preopted state 7323 // the app might end up being verified at runtime. That's because by default the apps 7324 // are verify-profile but for preopted apps there's no profile. 7325 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7326 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7327 // filter (by default interpret-only). 7328 // Note that at this stage unused apps are already filtered. 7329 if (isSystemApp(pkg) && 7330 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7331 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7332 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7333 } 7334 7335 // If the OTA updates a system app which was previously preopted to a non-preopted state 7336 // the app might end up being verified at runtime. That's because by default the apps 7337 // are verify-profile but for preopted apps there's no profile. 7338 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7339 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7340 // filter (by default interpret-only). 7341 // Note that at this stage unused apps are already filtered. 7342 if (isSystemApp(pkg) && 7343 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7344 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7345 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7346 } 7347 7348 // checkProfiles is false to avoid merging profiles during boot which 7349 // might interfere with background compilation (b/28612421). 7350 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7351 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7352 // trade-off worth doing to save boot time work. 7353 int dexOptStatus = performDexOptTraced(pkg.packageName, 7354 false /* checkProfiles */, 7355 compilerFilter, 7356 false /* force */); 7357 switch (dexOptStatus) { 7358 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7359 numberOfPackagesOptimized++; 7360 break; 7361 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7362 numberOfPackagesSkipped++; 7363 break; 7364 case PackageDexOptimizer.DEX_OPT_FAILED: 7365 numberOfPackagesFailed++; 7366 break; 7367 default: 7368 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7369 break; 7370 } 7371 } 7372 7373 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7374 numberOfPackagesFailed }; 7375 } 7376 7377 @Override 7378 public void notifyPackageUse(String packageName, int reason) { 7379 synchronized (mPackages) { 7380 PackageParser.Package p = mPackages.get(packageName); 7381 if (p == null) { 7382 return; 7383 } 7384 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7385 } 7386 } 7387 7388 // TODO: this is not used nor needed. Delete it. 7389 @Override 7390 public boolean performDexOptIfNeeded(String packageName) { 7391 int dexOptStatus = performDexOptTraced(packageName, 7392 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7393 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7394 } 7395 7396 @Override 7397 public boolean performDexOpt(String packageName, 7398 boolean checkProfiles, int compileReason, boolean force) { 7399 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7400 getCompilerFilterForReason(compileReason), force); 7401 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7402 } 7403 7404 @Override 7405 public boolean performDexOptMode(String packageName, 7406 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7407 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7408 targetCompilerFilter, force); 7409 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7410 } 7411 7412 private int performDexOptTraced(String packageName, 7413 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7414 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7415 try { 7416 return performDexOptInternal(packageName, checkProfiles, 7417 targetCompilerFilter, force); 7418 } finally { 7419 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7420 } 7421 } 7422 7423 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7424 // if the package can now be considered up to date for the given filter. 7425 private int performDexOptInternal(String packageName, 7426 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7427 PackageParser.Package p; 7428 synchronized (mPackages) { 7429 p = mPackages.get(packageName); 7430 if (p == null) { 7431 // Package could not be found. Report failure. 7432 return PackageDexOptimizer.DEX_OPT_FAILED; 7433 } 7434 mPackageUsage.maybeWriteAsync(mPackages); 7435 mCompilerStats.maybeWriteAsync(); 7436 } 7437 long callingId = Binder.clearCallingIdentity(); 7438 try { 7439 synchronized (mInstallLock) { 7440 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7441 targetCompilerFilter, force); 7442 } 7443 } finally { 7444 Binder.restoreCallingIdentity(callingId); 7445 } 7446 } 7447 7448 public ArraySet<String> getOptimizablePackages() { 7449 ArraySet<String> pkgs = new ArraySet<String>(); 7450 synchronized (mPackages) { 7451 for (PackageParser.Package p : mPackages.values()) { 7452 if (PackageDexOptimizer.canOptimizePackage(p)) { 7453 pkgs.add(p.packageName); 7454 } 7455 } 7456 } 7457 return pkgs; 7458 } 7459 7460 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7461 boolean checkProfiles, String targetCompilerFilter, 7462 boolean force) { 7463 // Select the dex optimizer based on the force parameter. 7464 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7465 // allocate an object here. 7466 PackageDexOptimizer pdo = force 7467 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7468 : mPackageDexOptimizer; 7469 7470 // Optimize all dependencies first. Note: we ignore the return value and march on 7471 // on errors. 7472 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7473 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7474 if (!deps.isEmpty()) { 7475 for (PackageParser.Package depPackage : deps) { 7476 // TODO: Analyze and investigate if we (should) profile libraries. 7477 // Currently this will do a full compilation of the library by default. 7478 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7479 false /* checkProfiles */, 7480 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7481 getOrCreateCompilerPackageStats(depPackage)); 7482 } 7483 } 7484 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7485 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7486 } 7487 7488 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7489 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7490 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7491 Set<String> collectedNames = new HashSet<>(); 7492 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7493 7494 retValue.remove(p); 7495 7496 return retValue; 7497 } else { 7498 return Collections.emptyList(); 7499 } 7500 } 7501 7502 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7503 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7504 if (!collectedNames.contains(p.packageName)) { 7505 collectedNames.add(p.packageName); 7506 collected.add(p); 7507 7508 if (p.usesLibraries != null) { 7509 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7510 } 7511 if (p.usesOptionalLibraries != null) { 7512 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7513 collectedNames); 7514 } 7515 } 7516 } 7517 7518 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7519 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7520 for (String libName : libs) { 7521 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7522 if (libPkg != null) { 7523 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7524 } 7525 } 7526 } 7527 7528 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7529 synchronized (mPackages) { 7530 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7531 if (lib != null && lib.apk != null) { 7532 return mPackages.get(lib.apk); 7533 } 7534 } 7535 return null; 7536 } 7537 7538 public void shutdown() { 7539 mPackageUsage.writeNow(mPackages); 7540 mCompilerStats.writeNow(); 7541 } 7542 7543 @Override 7544 public void dumpProfiles(String packageName) { 7545 PackageParser.Package pkg; 7546 synchronized (mPackages) { 7547 pkg = mPackages.get(packageName); 7548 if (pkg == null) { 7549 throw new IllegalArgumentException("Unknown package: " + packageName); 7550 } 7551 } 7552 /* Only the shell, root, or the app user should be able to dump profiles. */ 7553 int callingUid = Binder.getCallingUid(); 7554 if (callingUid != Process.SHELL_UID && 7555 callingUid != Process.ROOT_UID && 7556 callingUid != pkg.applicationInfo.uid) { 7557 throw new SecurityException("dumpProfiles"); 7558 } 7559 7560 synchronized (mInstallLock) { 7561 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7562 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7563 try { 7564 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7565 String gid = Integer.toString(sharedGid); 7566 String codePaths = TextUtils.join(";", allCodePaths); 7567 mInstaller.dumpProfiles(gid, packageName, codePaths); 7568 } catch (InstallerException e) { 7569 Slog.w(TAG, "Failed to dump profiles", e); 7570 } 7571 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7572 } 7573 } 7574 7575 @Override 7576 public void forceDexOpt(String packageName) { 7577 enforceSystemOrRoot("forceDexOpt"); 7578 7579 PackageParser.Package pkg; 7580 synchronized (mPackages) { 7581 pkg = mPackages.get(packageName); 7582 if (pkg == null) { 7583 throw new IllegalArgumentException("Unknown package: " + packageName); 7584 } 7585 } 7586 7587 synchronized (mInstallLock) { 7588 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7589 7590 // Whoever is calling forceDexOpt wants a fully compiled package. 7591 // Don't use profiles since that may cause compilation to be skipped. 7592 final int res = performDexOptInternalWithDependenciesLI(pkg, 7593 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7594 true /* force */); 7595 7596 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7597 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7598 throw new IllegalStateException("Failed to dexopt: " + res); 7599 } 7600 } 7601 } 7602 7603 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7604 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7605 Slog.w(TAG, "Unable to update from " + oldPkg.name 7606 + " to " + newPkg.packageName 7607 + ": old package not in system partition"); 7608 return false; 7609 } else if (mPackages.get(oldPkg.name) != null) { 7610 Slog.w(TAG, "Unable to update from " + oldPkg.name 7611 + " to " + newPkg.packageName 7612 + ": old package still exists"); 7613 return false; 7614 } 7615 return true; 7616 } 7617 7618 void removeCodePathLI(File codePath) { 7619 if (codePath.isDirectory()) { 7620 try { 7621 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7622 } catch (InstallerException e) { 7623 Slog.w(TAG, "Failed to remove code path", e); 7624 } 7625 } else { 7626 codePath.delete(); 7627 } 7628 } 7629 7630 private int[] resolveUserIds(int userId) { 7631 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7632 } 7633 7634 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7635 if (pkg == null) { 7636 Slog.wtf(TAG, "Package was null!", new Throwable()); 7637 return; 7638 } 7639 clearAppDataLeafLIF(pkg, userId, flags); 7640 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7641 for (int i = 0; i < childCount; i++) { 7642 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7643 } 7644 } 7645 7646 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7647 final PackageSetting ps; 7648 synchronized (mPackages) { 7649 ps = mSettings.mPackages.get(pkg.packageName); 7650 } 7651 for (int realUserId : resolveUserIds(userId)) { 7652 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7653 try { 7654 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7655 ceDataInode); 7656 } catch (InstallerException e) { 7657 Slog.w(TAG, String.valueOf(e)); 7658 } 7659 } 7660 } 7661 7662 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7663 if (pkg == null) { 7664 Slog.wtf(TAG, "Package was null!", new Throwable()); 7665 return; 7666 } 7667 destroyAppDataLeafLIF(pkg, userId, flags); 7668 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7669 for (int i = 0; i < childCount; i++) { 7670 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7671 } 7672 } 7673 7674 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7675 final PackageSetting ps; 7676 synchronized (mPackages) { 7677 ps = mSettings.mPackages.get(pkg.packageName); 7678 } 7679 for (int realUserId : resolveUserIds(userId)) { 7680 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7681 try { 7682 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7683 ceDataInode); 7684 } catch (InstallerException e) { 7685 Slog.w(TAG, String.valueOf(e)); 7686 } 7687 } 7688 } 7689 7690 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7691 if (pkg == null) { 7692 Slog.wtf(TAG, "Package was null!", new Throwable()); 7693 return; 7694 } 7695 destroyAppProfilesLeafLIF(pkg); 7696 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7697 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7698 for (int i = 0; i < childCount; i++) { 7699 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7700 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7701 true /* removeBaseMarker */); 7702 } 7703 } 7704 7705 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7706 boolean removeBaseMarker) { 7707 if (pkg.isForwardLocked()) { 7708 return; 7709 } 7710 7711 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7712 try { 7713 path = PackageManagerServiceUtils.realpath(new File(path)); 7714 } catch (IOException e) { 7715 // TODO: Should we return early here ? 7716 Slog.w(TAG, "Failed to get canonical path", e); 7717 continue; 7718 } 7719 7720 final String useMarker = path.replace('/', '@'); 7721 for (int realUserId : resolveUserIds(userId)) { 7722 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7723 if (removeBaseMarker) { 7724 File foreignUseMark = new File(profileDir, useMarker); 7725 if (foreignUseMark.exists()) { 7726 if (!foreignUseMark.delete()) { 7727 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7728 + pkg.packageName); 7729 } 7730 } 7731 } 7732 7733 File[] markers = profileDir.listFiles(); 7734 if (markers != null) { 7735 final String searchString = "@" + pkg.packageName + "@"; 7736 // We also delete all markers that contain the package name we're 7737 // uninstalling. These are associated with secondary dex-files belonging 7738 // to the package. Reconstructing the path of these dex files is messy 7739 // in general. 7740 for (File marker : markers) { 7741 if (marker.getName().indexOf(searchString) > 0) { 7742 if (!marker.delete()) { 7743 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7744 + pkg.packageName); 7745 } 7746 } 7747 } 7748 } 7749 } 7750 } 7751 } 7752 7753 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7754 try { 7755 mInstaller.destroyAppProfiles(pkg.packageName); 7756 } catch (InstallerException e) { 7757 Slog.w(TAG, String.valueOf(e)); 7758 } 7759 } 7760 7761 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7762 if (pkg == null) { 7763 Slog.wtf(TAG, "Package was null!", new Throwable()); 7764 return; 7765 } 7766 clearAppProfilesLeafLIF(pkg); 7767 // We don't remove the base foreign use marker when clearing profiles because 7768 // we will rename it when the app is updated. Unlike the actual profile contents, 7769 // the foreign use marker is good across installs. 7770 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7771 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7772 for (int i = 0; i < childCount; i++) { 7773 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7774 } 7775 } 7776 7777 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7778 try { 7779 mInstaller.clearAppProfiles(pkg.packageName); 7780 } catch (InstallerException e) { 7781 Slog.w(TAG, String.valueOf(e)); 7782 } 7783 } 7784 7785 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7786 long lastUpdateTime) { 7787 // Set parent install/update time 7788 PackageSetting ps = (PackageSetting) pkg.mExtras; 7789 if (ps != null) { 7790 ps.firstInstallTime = firstInstallTime; 7791 ps.lastUpdateTime = lastUpdateTime; 7792 } 7793 // Set children install/update time 7794 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7795 for (int i = 0; i < childCount; i++) { 7796 PackageParser.Package childPkg = pkg.childPackages.get(i); 7797 ps = (PackageSetting) childPkg.mExtras; 7798 if (ps != null) { 7799 ps.firstInstallTime = firstInstallTime; 7800 ps.lastUpdateTime = lastUpdateTime; 7801 } 7802 } 7803 } 7804 7805 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7806 PackageParser.Package changingLib) { 7807 if (file.path != null) { 7808 usesLibraryFiles.add(file.path); 7809 return; 7810 } 7811 PackageParser.Package p = mPackages.get(file.apk); 7812 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7813 // If we are doing this while in the middle of updating a library apk, 7814 // then we need to make sure to use that new apk for determining the 7815 // dependencies here. (We haven't yet finished committing the new apk 7816 // to the package manager state.) 7817 if (p == null || p.packageName.equals(changingLib.packageName)) { 7818 p = changingLib; 7819 } 7820 } 7821 if (p != null) { 7822 usesLibraryFiles.addAll(p.getAllCodePaths()); 7823 } 7824 } 7825 7826 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 7827 PackageParser.Package changingLib) throws PackageManagerException { 7828 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7829 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7830 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7831 for (int i=0; i<N; i++) { 7832 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7833 if (file == null) { 7834 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7835 "Package " + pkg.packageName + " requires unavailable shared library " 7836 + pkg.usesLibraries.get(i) + "; failing!"); 7837 } 7838 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 7839 } 7840 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7841 for (int i=0; i<N; i++) { 7842 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7843 if (file == null) { 7844 Slog.w(TAG, "Package " + pkg.packageName 7845 + " desires unavailable shared library " 7846 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7847 } else { 7848 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 7849 } 7850 } 7851 N = usesLibraryFiles.size(); 7852 if (N > 0) { 7853 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7854 } else { 7855 pkg.usesLibraryFiles = null; 7856 } 7857 } 7858 } 7859 7860 private static boolean hasString(List<String> list, List<String> which) { 7861 if (list == null) { 7862 return false; 7863 } 7864 for (int i=list.size()-1; i>=0; i--) { 7865 for (int j=which.size()-1; j>=0; j--) { 7866 if (which.get(j).equals(list.get(i))) { 7867 return true; 7868 } 7869 } 7870 } 7871 return false; 7872 } 7873 7874 private void updateAllSharedLibrariesLPw() { 7875 for (PackageParser.Package pkg : mPackages.values()) { 7876 try { 7877 updateSharedLibrariesLPr(pkg, null); 7878 } catch (PackageManagerException e) { 7879 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7880 } 7881 } 7882 } 7883 7884 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7885 PackageParser.Package changingPkg) { 7886 ArrayList<PackageParser.Package> res = null; 7887 for (PackageParser.Package pkg : mPackages.values()) { 7888 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7889 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7890 if (res == null) { 7891 res = new ArrayList<PackageParser.Package>(); 7892 } 7893 res.add(pkg); 7894 try { 7895 updateSharedLibrariesLPr(pkg, changingPkg); 7896 } catch (PackageManagerException e) { 7897 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7898 } 7899 } 7900 } 7901 return res; 7902 } 7903 7904 /** 7905 * Derive the value of the {@code cpuAbiOverride} based on the provided 7906 * value and an optional stored value from the package settings. 7907 */ 7908 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7909 String cpuAbiOverride = null; 7910 7911 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7912 cpuAbiOverride = null; 7913 } else if (abiOverride != null) { 7914 cpuAbiOverride = abiOverride; 7915 } else if (settings != null) { 7916 cpuAbiOverride = settings.cpuAbiOverrideString; 7917 } 7918 7919 return cpuAbiOverride; 7920 } 7921 7922 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7923 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7924 throws PackageManagerException { 7925 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7926 // If the package has children and this is the first dive in the function 7927 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7928 // whether all packages (parent and children) would be successfully scanned 7929 // before the actual scan since scanning mutates internal state and we want 7930 // to atomically install the package and its children. 7931 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7932 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7933 scanFlags |= SCAN_CHECK_ONLY; 7934 } 7935 } else { 7936 scanFlags &= ~SCAN_CHECK_ONLY; 7937 } 7938 7939 final PackageParser.Package scannedPkg; 7940 try { 7941 // Scan the parent 7942 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7943 // Scan the children 7944 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7945 for (int i = 0; i < childCount; i++) { 7946 PackageParser.Package childPkg = pkg.childPackages.get(i); 7947 scanPackageLI(childPkg, policyFlags, 7948 scanFlags, currentTime, user); 7949 } 7950 } finally { 7951 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7952 } 7953 7954 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7955 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7956 } 7957 7958 return scannedPkg; 7959 } 7960 7961 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7962 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7963 boolean success = false; 7964 try { 7965 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7966 currentTime, user); 7967 success = true; 7968 return res; 7969 } finally { 7970 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7971 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7972 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7973 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7974 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7975 } 7976 } 7977 } 7978 7979 /** 7980 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7981 */ 7982 private static boolean apkHasCode(String fileName) { 7983 StrictJarFile jarFile = null; 7984 try { 7985 jarFile = new StrictJarFile(fileName, 7986 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7987 return jarFile.findEntry("classes.dex") != null; 7988 } catch (IOException ignore) { 7989 } finally { 7990 try { 7991 if (jarFile != null) { 7992 jarFile.close(); 7993 } 7994 } catch (IOException ignore) {} 7995 } 7996 return false; 7997 } 7998 7999 /** 8000 * Enforces code policy for the package. This ensures that if an APK has 8001 * declared hasCode="true" in its manifest that the APK actually contains 8002 * code. 8003 * 8004 * @throws PackageManagerException If bytecode could not be found when it should exist 8005 */ 8006 private static void assertCodePolicy(PackageParser.Package pkg) 8007 throws PackageManagerException { 8008 final boolean shouldHaveCode = 8009 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8010 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8011 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8012 "Package " + pkg.baseCodePath + " code is missing"); 8013 } 8014 8015 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8016 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8017 final boolean splitShouldHaveCode = 8018 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8019 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8020 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8021 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8022 } 8023 } 8024 } 8025 } 8026 8027 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8028 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8029 throws PackageManagerException { 8030 if (DEBUG_PACKAGE_SCANNING) { 8031 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8032 Log.d(TAG, "Scanning package " + pkg.packageName); 8033 } 8034 8035 applyPolicy(pkg, policyFlags); 8036 8037 assertPackageIsValid(pkg, policyFlags); 8038 8039 // Initialize package source and resource directories 8040 final File scanFile = new File(pkg.codePath); 8041 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8042 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8043 8044 SharedUserSetting suid = null; 8045 PackageSetting pkgSetting = null; 8046 8047 // Getting the package setting may have a side-effect, so if we 8048 // are only checking if scan would succeed, stash a copy of the 8049 // old setting to restore at the end. 8050 PackageSetting nonMutatedPs = null; 8051 8052 // writer 8053 synchronized (mPackages) { 8054 if (pkg.mSharedUserId != null) { 8055 // SIDE EFFECTS; may potentially allocate a new shared user 8056 suid = mSettings.getSharedUserLPw( 8057 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 8058 if (DEBUG_PACKAGE_SCANNING) { 8059 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8060 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8061 + "): packages=" + suid.packages); 8062 } 8063 } 8064 8065 // Check if we are renaming from an original package name. 8066 PackageSetting origPackage = null; 8067 String realName = null; 8068 if (pkg.mOriginalPackages != null) { 8069 // This package may need to be renamed to a previously 8070 // installed name. Let's check on that... 8071 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8072 if (pkg.mOriginalPackages.contains(renamed)) { 8073 // This package had originally been installed as the 8074 // original name, and we have already taken care of 8075 // transitioning to the new one. Just update the new 8076 // one to continue using the old name. 8077 realName = pkg.mRealPackage; 8078 if (!pkg.packageName.equals(renamed)) { 8079 // Callers into this function may have already taken 8080 // care of renaming the package; only do it here if 8081 // it is not already done. 8082 pkg.setPackageName(renamed); 8083 } 8084 } else { 8085 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8086 if ((origPackage = mSettings.getPackageLPr( 8087 pkg.mOriginalPackages.get(i))) != null) { 8088 // We do have the package already installed under its 8089 // original name... should we use it? 8090 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8091 // New package is not compatible with original. 8092 origPackage = null; 8093 continue; 8094 } else if (origPackage.sharedUser != null) { 8095 // Make sure uid is compatible between packages. 8096 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8097 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8098 + " to " + pkg.packageName + ": old uid " 8099 + origPackage.sharedUser.name 8100 + " differs from " + pkg.mSharedUserId); 8101 origPackage = null; 8102 continue; 8103 } 8104 // TODO: Add case when shared user id is added [b/28144775] 8105 } else { 8106 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8107 + pkg.packageName + " to old name " + origPackage.name); 8108 } 8109 break; 8110 } 8111 } 8112 } 8113 } 8114 8115 if (mTransferedPackages.contains(pkg.packageName)) { 8116 Slog.w(TAG, "Package " + pkg.packageName 8117 + " was transferred to another, but its .apk remains"); 8118 } 8119 8120 // See comments in nonMutatedPs declaration 8121 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8122 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8123 if (foundPs != null) { 8124 nonMutatedPs = new PackageSetting(foundPs); 8125 } 8126 } 8127 8128 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8129 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 8130 PackageManagerService.reportSettingsProblem(Log.WARN, 8131 "Package " + pkg.packageName + " shared user changed from " 8132 + (pkgSetting.sharedUser != null 8133 ? pkgSetting.sharedUser.name : "<nothing>") 8134 + " to " 8135 + (suid != null ? suid.name : "<nothing>") 8136 + "; replacing with new"); 8137 pkgSetting = null; 8138 } 8139 final PackageSetting oldPkgSetting = 8140 pkgSetting == null ? null : new PackageSetting(pkgSetting); 8141 final PackageSetting disabledPkgSetting = 8142 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8143 if (pkgSetting == null) { 8144 final String parentPackageName = (pkg.parentPackage != null) 8145 ? pkg.parentPackage.packageName : null; 8146 // REMOVE SharedUserSetting from method; update in a separate call 8147 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 8148 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 8149 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 8150 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 8151 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 8152 true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(), 8153 UserManagerService.getInstance()); 8154 // SIDE EFFECTS; updates system state; move elsewhere 8155 if (origPackage != null) { 8156 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 8157 } 8158 mSettings.addUserToSettingLPw(pkgSetting); 8159 } else { 8160 // REMOVE SharedUserSetting from method; update in a separate call 8161 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 8162 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 8163 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 8164 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 8165 UserManagerService.getInstance()); 8166 } 8167 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 8168 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 8169 8170 // SIDE EFFECTS; modifies system state; move elsewhere 8171 if (pkgSetting.origPackage != null) { 8172 // If we are first transitioning from an original package, 8173 // fix up the new package's name now. We need to do this after 8174 // looking up the package under its new name, so getPackageLP 8175 // can take care of fiddling things correctly. 8176 pkg.setPackageName(origPackage.name); 8177 8178 // File a report about this. 8179 String msg = "New package " + pkgSetting.realName 8180 + " renamed to replace old package " + pkgSetting.name; 8181 reportSettingsProblem(Log.WARN, msg); 8182 8183 // Make a note of it. 8184 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8185 mTransferedPackages.add(origPackage.name); 8186 } 8187 8188 // No longer need to retain this. 8189 pkgSetting.origPackage = null; 8190 } 8191 8192 // SIDE EFFECTS; modifies system state; move elsewhere 8193 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8194 // Make a note of it. 8195 mTransferedPackages.add(pkg.packageName); 8196 } 8197 8198 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8199 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8200 } 8201 8202 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8203 // Check all shared libraries and map to their actual file path. 8204 // We only do this here for apps not on a system dir, because those 8205 // are the only ones that can fail an install due to this. We 8206 // will take care of the system apps by updating all of their 8207 // library paths after the scan is done. 8208 updateSharedLibrariesLPr(pkg, null); 8209 } 8210 8211 if (mFoundPolicyFile) { 8212 SELinuxMMAC.assignSeinfoValue(pkg); 8213 } 8214 8215 pkg.applicationInfo.uid = pkgSetting.appId; 8216 pkg.mExtras = pkgSetting; 8217 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8218 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8219 // We just determined the app is signed correctly, so bring 8220 // over the latest parsed certs. 8221 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8222 } else { 8223 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8224 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8225 "Package " + pkg.packageName + " upgrade keys do not match the " 8226 + "previously installed version"); 8227 } else { 8228 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8229 String msg = "System package " + pkg.packageName 8230 + " signature changed; retaining data."; 8231 reportSettingsProblem(Log.WARN, msg); 8232 } 8233 } 8234 } else { 8235 try { 8236 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 8237 verifySignaturesLP(pkgSetting, pkg); 8238 // We just determined the app is signed correctly, so bring 8239 // over the latest parsed certs. 8240 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8241 } catch (PackageManagerException e) { 8242 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8243 throw e; 8244 } 8245 // The signature has changed, but this package is in the system 8246 // image... let's recover! 8247 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8248 // However... if this package is part of a shared user, but it 8249 // doesn't match the signature of the shared user, let's fail. 8250 // What this means is that you can't change the signatures 8251 // associated with an overall shared user, which doesn't seem all 8252 // that unreasonable. 8253 if (pkgSetting.sharedUser != null) { 8254 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8255 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8256 throw new PackageManagerException( 8257 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8258 "Signature mismatch for shared user: " 8259 + pkgSetting.sharedUser); 8260 } 8261 } 8262 // File a report about this. 8263 String msg = "System package " + pkg.packageName 8264 + " signature changed; retaining data."; 8265 reportSettingsProblem(Log.WARN, msg); 8266 } 8267 } 8268 8269 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8270 // This package wants to adopt ownership of permissions from 8271 // another package. 8272 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8273 final String origName = pkg.mAdoptPermissions.get(i); 8274 final PackageSetting orig = mSettings.getPackageLPr(origName); 8275 if (orig != null) { 8276 if (verifyPackageUpdateLPr(orig, pkg)) { 8277 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8278 + pkg.packageName); 8279 // SIDE EFFECTS; updates permissions system state; move elsewhere 8280 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8281 } 8282 } 8283 } 8284 } 8285 } 8286 8287 pkg.applicationInfo.processName = fixProcessName( 8288 pkg.applicationInfo.packageName, 8289 pkg.applicationInfo.processName); 8290 8291 if (pkg != mPlatformPackage) { 8292 // Get all of our default paths setup 8293 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8294 } 8295 8296 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8297 8298 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8299 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 8300 derivePackageAbi( 8301 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 8302 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8303 8304 // Some system apps still use directory structure for native libraries 8305 // in which case we might end up not detecting abi solely based on apk 8306 // structure. Try to detect abi based on directory structure. 8307 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8308 pkg.applicationInfo.primaryCpuAbi == null) { 8309 setBundledAppAbisAndRoots(pkg, pkgSetting); 8310 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8311 } 8312 } else { 8313 if ((scanFlags & SCAN_MOVE) != 0) { 8314 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8315 // but we already have this packages package info in the PackageSetting. We just 8316 // use that and derive the native library path based on the new codepath. 8317 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8318 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8319 } 8320 8321 // Set native library paths again. For moves, the path will be updated based on the 8322 // ABIs we've determined above. For non-moves, the path will be updated based on the 8323 // ABIs we determined during compilation, but the path will depend on the final 8324 // package path (after the rename away from the stage path). 8325 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8326 } 8327 8328 // This is a special case for the "system" package, where the ABI is 8329 // dictated by the zygote configuration (and init.rc). We should keep track 8330 // of this ABI so that we can deal with "normal" applications that run under 8331 // the same UID correctly. 8332 if (mPlatformPackage == pkg) { 8333 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8334 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8335 } 8336 8337 // If there's a mismatch between the abi-override in the package setting 8338 // and the abiOverride specified for the install. Warn about this because we 8339 // would've already compiled the app without taking the package setting into 8340 // account. 8341 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8342 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8343 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8344 " for package " + pkg.packageName); 8345 } 8346 } 8347 8348 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8349 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8350 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8351 8352 // Copy the derived override back to the parsed package, so that we can 8353 // update the package settings accordingly. 8354 pkg.cpuAbiOverride = cpuAbiOverride; 8355 8356 if (DEBUG_ABI_SELECTION) { 8357 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8358 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8359 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8360 } 8361 8362 // Push the derived path down into PackageSettings so we know what to 8363 // clean up at uninstall time. 8364 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8365 8366 if (DEBUG_ABI_SELECTION) { 8367 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8368 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8369 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8370 } 8371 8372 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 8373 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8374 // We don't do this here during boot because we can do it all 8375 // at once after scanning all existing packages. 8376 // 8377 // We also do this *before* we perform dexopt on this package, so that 8378 // we can avoid redundant dexopts, and also to make sure we've got the 8379 // code and package path correct. 8380 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 8381 } 8382 8383 if (mFactoryTest && pkg.requestedPermissions.contains( 8384 android.Manifest.permission.FACTORY_TEST)) { 8385 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8386 } 8387 8388 if (isSystemApp(pkg)) { 8389 pkgSetting.isOrphaned = true; 8390 } 8391 8392 // Take care of first install / last update times. 8393 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8394 if (currentTime != 0) { 8395 if (pkgSetting.firstInstallTime == 0) { 8396 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8397 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 8398 pkgSetting.lastUpdateTime = currentTime; 8399 } 8400 } else if (pkgSetting.firstInstallTime == 0) { 8401 // We need *something*. Take time time stamp of the file. 8402 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8403 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8404 if (scanFileTime != pkgSetting.timeStamp) { 8405 // A package on the system image has changed; consider this 8406 // to be an update. 8407 pkgSetting.lastUpdateTime = scanFileTime; 8408 } 8409 } 8410 pkgSetting.setTimeStamp(scanFileTime); 8411 8412 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8413 if (nonMutatedPs != null) { 8414 synchronized (mPackages) { 8415 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8416 } 8417 } 8418 } else { 8419 // Modify state for the given package setting 8420 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 8421 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 8422 } 8423 return pkg; 8424 } 8425 8426 /** 8427 * Applies policy to the parsed package based upon the given policy flags. 8428 * Ensures the package is in a good state. 8429 * <p> 8430 * Implementation detail: This method must NOT have any side effect. It would 8431 * ideally be static, but, it requires locks to read system state. 8432 */ 8433 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 8434 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8435 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8436 if (pkg.applicationInfo.isDirectBootAware()) { 8437 // we're direct boot aware; set for all components 8438 for (PackageParser.Service s : pkg.services) { 8439 s.info.encryptionAware = s.info.directBootAware = true; 8440 } 8441 for (PackageParser.Provider p : pkg.providers) { 8442 p.info.encryptionAware = p.info.directBootAware = true; 8443 } 8444 for (PackageParser.Activity a : pkg.activities) { 8445 a.info.encryptionAware = a.info.directBootAware = true; 8446 } 8447 for (PackageParser.Activity r : pkg.receivers) { 8448 r.info.encryptionAware = r.info.directBootAware = true; 8449 } 8450 } 8451 } else { 8452 // Only allow system apps to be flagged as core apps. 8453 pkg.coreApp = false; 8454 // clear flags not applicable to regular apps 8455 pkg.applicationInfo.privateFlags &= 8456 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8457 pkg.applicationInfo.privateFlags &= 8458 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8459 } 8460 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8461 8462 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8463 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8464 } 8465 8466 if (!isSystemApp(pkg)) { 8467 // Only system apps can use these features. 8468 pkg.mOriginalPackages = null; 8469 pkg.mRealPackage = null; 8470 pkg.mAdoptPermissions = null; 8471 } 8472 } 8473 8474 /** 8475 * Asserts the parsed package is valid according to teh given policy. If the 8476 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 8477 * <p> 8478 * Implementation detail: This method must NOT have any side effects. It would 8479 * ideally be static, but, it requires locks to read system state. 8480 * 8481 * @throws PackageManagerException If the package fails any of the validation checks 8482 */ 8483 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags) 8484 throws PackageManagerException { 8485 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8486 assertCodePolicy(pkg); 8487 } 8488 8489 if (pkg.applicationInfo.getCodePath() == null || 8490 pkg.applicationInfo.getResourcePath() == null) { 8491 // Bail out. The resource and code paths haven't been set. 8492 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8493 "Code and resource paths haven't been set correctly"); 8494 } 8495 8496 // Make sure we're not adding any bogus keyset info 8497 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8498 ksms.assertScannedPackageValid(pkg); 8499 8500 synchronized (mPackages) { 8501 // The special "android" package can only be defined once 8502 if (pkg.packageName.equals("android")) { 8503 if (mAndroidApplication != null) { 8504 Slog.w(TAG, "*************************************************"); 8505 Slog.w(TAG, "Core android package being redefined. Skipping."); 8506 Slog.w(TAG, " codePath=" + pkg.codePath); 8507 Slog.w(TAG, "*************************************************"); 8508 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8509 "Core android package being redefined. Skipping."); 8510 } 8511 } 8512 8513 // A package name must be unique; don't allow duplicates 8514 if (mPackages.containsKey(pkg.packageName) 8515 || mSharedLibraries.containsKey(pkg.packageName)) { 8516 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8517 "Application package " + pkg.packageName 8518 + " already installed. Skipping duplicate."); 8519 } 8520 8521 // Only privileged apps and updated privileged apps can add child packages. 8522 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8523 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8524 throw new PackageManagerException("Only privileged apps can add child " 8525 + "packages. Ignoring package " + pkg.packageName); 8526 } 8527 final int childCount = pkg.childPackages.size(); 8528 for (int i = 0; i < childCount; i++) { 8529 PackageParser.Package childPkg = pkg.childPackages.get(i); 8530 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8531 childPkg.packageName)) { 8532 throw new PackageManagerException("Can't override child of " 8533 + "another disabled app. Ignoring package " + pkg.packageName); 8534 } 8535 } 8536 } 8537 8538 // If we're only installing presumed-existing packages, require that the 8539 // scanned APK is both already known and at the path previously established 8540 // for it. Previously unknown packages we pick up normally, but if we have an 8541 // a priori expectation about this package's install presence, enforce it. 8542 // With a singular exception for new system packages. When an OTA contains 8543 // a new system package, we allow the codepath to change from a system location 8544 // to the user-installed location. If we don't allow this change, any newer, 8545 // user-installed version of the application will be ignored. 8546 if ((policyFlags & SCAN_REQUIRE_KNOWN) != 0) { 8547 if (mExpectingBetter.containsKey(pkg.packageName)) { 8548 logCriticalInfo(Log.WARN, 8549 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8550 } else { 8551 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 8552 if (known != null) { 8553 if (DEBUG_PACKAGE_SCANNING) { 8554 Log.d(TAG, "Examining " + pkg.codePath 8555 + " and requiring known paths " + known.codePathString 8556 + " & " + known.resourcePathString); 8557 } 8558 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8559 || !pkg.applicationInfo.getResourcePath().equals( 8560 known.resourcePathString)) { 8561 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8562 "Application package " + pkg.packageName 8563 + " found at " + pkg.applicationInfo.getCodePath() 8564 + " but expected at " + known.codePathString 8565 + "; ignoring."); 8566 } 8567 } 8568 } 8569 } 8570 8571 // Verify that this new package doesn't have any content providers 8572 // that conflict with existing packages. Only do this if the 8573 // package isn't already installed, since we don't want to break 8574 // things that are installed. 8575 if ((policyFlags & SCAN_NEW_INSTALL) != 0) { 8576 final int N = pkg.providers.size(); 8577 int i; 8578 for (i=0; i<N; i++) { 8579 PackageParser.Provider p = pkg.providers.get(i); 8580 if (p.info.authority != null) { 8581 String names[] = p.info.authority.split(";"); 8582 for (int j = 0; j < names.length; j++) { 8583 if (mProvidersByAuthority.containsKey(names[j])) { 8584 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8585 final String otherPackageName = 8586 ((other != null && other.getComponentName() != null) ? 8587 other.getComponentName().getPackageName() : "?"); 8588 throw new PackageManagerException( 8589 INSTALL_FAILED_CONFLICTING_PROVIDER, 8590 "Can't install because provider name " + names[j] 8591 + " (in package " + pkg.applicationInfo.packageName 8592 + ") is already used by " + otherPackageName); 8593 } 8594 } 8595 } 8596 } 8597 } 8598 } 8599 } 8600 8601 /** 8602 * Adds a scanned package to the system. When this method is finished, the package will 8603 * be available for query, resolution, etc... 8604 */ 8605 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 8606 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 8607 final String pkgName = pkg.packageName; 8608 if (mCustomResolverComponentName != null && 8609 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8610 setUpCustomResolverActivity(pkg); 8611 } 8612 8613 if (pkg.packageName.equals("android")) { 8614 synchronized (mPackages) { 8615 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8616 // Set up information for our fall-back user intent resolution activity. 8617 mPlatformPackage = pkg; 8618 pkg.mVersionCode = mSdkVersion; 8619 mAndroidApplication = pkg.applicationInfo; 8620 8621 if (!mResolverReplaced) { 8622 mResolveActivity.applicationInfo = mAndroidApplication; 8623 mResolveActivity.name = ResolverActivity.class.getName(); 8624 mResolveActivity.packageName = mAndroidApplication.packageName; 8625 mResolveActivity.processName = "system:ui"; 8626 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8627 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8628 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8629 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8630 mResolveActivity.exported = true; 8631 mResolveActivity.enabled = true; 8632 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8633 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8634 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8635 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8636 | ActivityInfo.CONFIG_ORIENTATION 8637 | ActivityInfo.CONFIG_KEYBOARD 8638 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8639 mResolveInfo.activityInfo = mResolveActivity; 8640 mResolveInfo.priority = 0; 8641 mResolveInfo.preferredOrder = 0; 8642 mResolveInfo.match = 0; 8643 mResolveComponentName = new ComponentName( 8644 mAndroidApplication.packageName, mResolveActivity.name); 8645 } 8646 } 8647 } 8648 } 8649 8650 ArrayList<PackageParser.Package> clientLibPkgs = null; 8651 // writer 8652 synchronized (mPackages) { 8653 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8654 // Only system apps can add new shared libraries. 8655 if (pkg.libraryNames != null) { 8656 for (int i=0; i<pkg.libraryNames.size(); i++) { 8657 String name = pkg.libraryNames.get(i); 8658 boolean allowed = false; 8659 if (pkg.isUpdatedSystemApp()) { 8660 // New library entries can only be added through the 8661 // system image. This is important to get rid of a lot 8662 // of nasty edge cases: for example if we allowed a non- 8663 // system update of the app to add a library, then uninstalling 8664 // the update would make the library go away, and assumptions 8665 // we made such as through app install filtering would now 8666 // have allowed apps on the device which aren't compatible 8667 // with it. Better to just have the restriction here, be 8668 // conservative, and create many fewer cases that can negatively 8669 // impact the user experience. 8670 final PackageSetting sysPs = mSettings 8671 .getDisabledSystemPkgLPr(pkg.packageName); 8672 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8673 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8674 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8675 allowed = true; 8676 break; 8677 } 8678 } 8679 } 8680 } else { 8681 allowed = true; 8682 } 8683 if (allowed) { 8684 if (!mSharedLibraries.containsKey(name)) { 8685 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8686 } else if (!name.equals(pkg.packageName)) { 8687 Slog.w(TAG, "Package " + pkg.packageName + " library " 8688 + name + " already exists; skipping"); 8689 } 8690 } else { 8691 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8692 + name + " that is not declared on system image; skipping"); 8693 } 8694 } 8695 if ((scanFlags & SCAN_BOOTING) == 0) { 8696 // If we are not booting, we need to update any applications 8697 // that are clients of our shared library. If we are booting, 8698 // this will all be done once the scan is complete. 8699 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8700 } 8701 } 8702 } 8703 } 8704 8705 if ((scanFlags & SCAN_BOOTING) != 0) { 8706 // No apps can run during boot scan, so they don't need to be frozen 8707 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8708 // Caller asked to not kill app, so it's probably not frozen 8709 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8710 // Caller asked us to ignore frozen check for some reason; they 8711 // probably didn't know the package name 8712 } else { 8713 // We're doing major surgery on this package, so it better be frozen 8714 // right now to keep it from launching 8715 checkPackageFrozen(pkgName); 8716 } 8717 8718 // Also need to kill any apps that are dependent on the library. 8719 if (clientLibPkgs != null) { 8720 for (int i=0; i<clientLibPkgs.size(); i++) { 8721 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8722 killApplication(clientPkg.applicationInfo.packageName, 8723 clientPkg.applicationInfo.uid, "update lib"); 8724 } 8725 } 8726 8727 // writer 8728 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8729 8730 boolean createIdmapFailed = false; 8731 synchronized (mPackages) { 8732 // We don't expect installation to fail beyond this point 8733 8734 if (pkgSetting.pkg != null) { 8735 // Note that |user| might be null during the initial boot scan. If a codePath 8736 // for an app has changed during a boot scan, it's due to an app update that's 8737 // part of the system partition and marker changes must be applied to all users. 8738 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 8739 final int[] userIds = resolveUserIds(userId); 8740 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 8741 } 8742 8743 // Add the new setting to mSettings 8744 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8745 // Add the new setting to mPackages 8746 mPackages.put(pkg.applicationInfo.packageName, pkg); 8747 // Make sure we don't accidentally delete its data. 8748 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8749 while (iter.hasNext()) { 8750 PackageCleanItem item = iter.next(); 8751 if (pkgName.equals(item.packageName)) { 8752 iter.remove(); 8753 } 8754 } 8755 8756 // Add the package's KeySets to the global KeySetManagerService 8757 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8758 ksms.addScannedPackageLPw(pkg); 8759 8760 int N = pkg.providers.size(); 8761 StringBuilder r = null; 8762 int i; 8763 for (i=0; i<N; i++) { 8764 PackageParser.Provider p = pkg.providers.get(i); 8765 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8766 p.info.processName); 8767 mProviders.addProvider(p); 8768 p.syncable = p.info.isSyncable; 8769 if (p.info.authority != null) { 8770 String names[] = p.info.authority.split(";"); 8771 p.info.authority = null; 8772 for (int j = 0; j < names.length; j++) { 8773 if (j == 1 && p.syncable) { 8774 // We only want the first authority for a provider to possibly be 8775 // syncable, so if we already added this provider using a different 8776 // authority clear the syncable flag. We copy the provider before 8777 // changing it because the mProviders object contains a reference 8778 // to a provider that we don't want to change. 8779 // Only do this for the second authority since the resulting provider 8780 // object can be the same for all future authorities for this provider. 8781 p = new PackageParser.Provider(p); 8782 p.syncable = false; 8783 } 8784 if (!mProvidersByAuthority.containsKey(names[j])) { 8785 mProvidersByAuthority.put(names[j], p); 8786 if (p.info.authority == null) { 8787 p.info.authority = names[j]; 8788 } else { 8789 p.info.authority = p.info.authority + ";" + names[j]; 8790 } 8791 if (DEBUG_PACKAGE_SCANNING) { 8792 if (chatty) 8793 Log.d(TAG, "Registered content provider: " + names[j] 8794 + ", className = " + p.info.name + ", isSyncable = " 8795 + p.info.isSyncable); 8796 } 8797 } else { 8798 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8799 Slog.w(TAG, "Skipping provider name " + names[j] + 8800 " (in package " + pkg.applicationInfo.packageName + 8801 "): name already used by " 8802 + ((other != null && other.getComponentName() != null) 8803 ? other.getComponentName().getPackageName() : "?")); 8804 } 8805 } 8806 } 8807 if (chatty) { 8808 if (r == null) { 8809 r = new StringBuilder(256); 8810 } else { 8811 r.append(' '); 8812 } 8813 r.append(p.info.name); 8814 } 8815 } 8816 if (r != null) { 8817 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8818 } 8819 8820 N = pkg.services.size(); 8821 r = null; 8822 for (i=0; i<N; i++) { 8823 PackageParser.Service s = pkg.services.get(i); 8824 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8825 s.info.processName); 8826 mServices.addService(s); 8827 if (chatty) { 8828 if (r == null) { 8829 r = new StringBuilder(256); 8830 } else { 8831 r.append(' '); 8832 } 8833 r.append(s.info.name); 8834 } 8835 } 8836 if (r != null) { 8837 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8838 } 8839 8840 N = pkg.receivers.size(); 8841 r = null; 8842 for (i=0; i<N; i++) { 8843 PackageParser.Activity a = pkg.receivers.get(i); 8844 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8845 a.info.processName); 8846 mReceivers.addActivity(a, "receiver"); 8847 if (chatty) { 8848 if (r == null) { 8849 r = new StringBuilder(256); 8850 } else { 8851 r.append(' '); 8852 } 8853 r.append(a.info.name); 8854 } 8855 } 8856 if (r != null) { 8857 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8858 } 8859 8860 N = pkg.activities.size(); 8861 r = null; 8862 for (i=0; i<N; i++) { 8863 PackageParser.Activity a = pkg.activities.get(i); 8864 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8865 a.info.processName); 8866 mActivities.addActivity(a, "activity"); 8867 if (chatty) { 8868 if (r == null) { 8869 r = new StringBuilder(256); 8870 } else { 8871 r.append(' '); 8872 } 8873 r.append(a.info.name); 8874 } 8875 } 8876 if (r != null) { 8877 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8878 } 8879 8880 N = pkg.permissionGroups.size(); 8881 r = null; 8882 for (i=0; i<N; i++) { 8883 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8884 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8885 final String curPackageName = cur == null ? null : cur.info.packageName; 8886 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 8887 if (cur == null || isPackageUpdate) { 8888 mPermissionGroups.put(pg.info.name, pg); 8889 if (chatty) { 8890 if (r == null) { 8891 r = new StringBuilder(256); 8892 } else { 8893 r.append(' '); 8894 } 8895 if (isPackageUpdate) { 8896 r.append("UPD:"); 8897 } 8898 r.append(pg.info.name); 8899 } 8900 } else { 8901 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8902 + pg.info.packageName + " ignored: original from " 8903 + cur.info.packageName); 8904 if (chatty) { 8905 if (r == null) { 8906 r = new StringBuilder(256); 8907 } else { 8908 r.append(' '); 8909 } 8910 r.append("DUP:"); 8911 r.append(pg.info.name); 8912 } 8913 } 8914 } 8915 if (r != null) { 8916 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8917 } 8918 8919 N = pkg.permissions.size(); 8920 r = null; 8921 for (i=0; i<N; i++) { 8922 PackageParser.Permission p = pkg.permissions.get(i); 8923 8924 // Assume by default that we did not install this permission into the system. 8925 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8926 8927 // Now that permission groups have a special meaning, we ignore permission 8928 // groups for legacy apps to prevent unexpected behavior. In particular, 8929 // permissions for one app being granted to someone just becase they happen 8930 // to be in a group defined by another app (before this had no implications). 8931 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8932 p.group = mPermissionGroups.get(p.info.group); 8933 // Warn for a permission in an unknown group. 8934 if (p.info.group != null && p.group == null) { 8935 Slog.w(TAG, "Permission " + p.info.name + " from package " 8936 + p.info.packageName + " in an unknown group " + p.info.group); 8937 } 8938 } 8939 8940 ArrayMap<String, BasePermission> permissionMap = 8941 p.tree ? mSettings.mPermissionTrees 8942 : mSettings.mPermissions; 8943 BasePermission bp = permissionMap.get(p.info.name); 8944 8945 // Allow system apps to redefine non-system permissions 8946 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8947 final boolean currentOwnerIsSystem = (bp.perm != null 8948 && isSystemApp(bp.perm.owner)); 8949 if (isSystemApp(p.owner)) { 8950 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8951 // It's a built-in permission and no owner, take ownership now 8952 bp.packageSetting = pkgSetting; 8953 bp.perm = p; 8954 bp.uid = pkg.applicationInfo.uid; 8955 bp.sourcePackage = p.info.packageName; 8956 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8957 } else if (!currentOwnerIsSystem) { 8958 String msg = "New decl " + p.owner + " of permission " 8959 + p.info.name + " is system; overriding " + bp.sourcePackage; 8960 reportSettingsProblem(Log.WARN, msg); 8961 bp = null; 8962 } 8963 } 8964 } 8965 8966 if (bp == null) { 8967 bp = new BasePermission(p.info.name, p.info.packageName, 8968 BasePermission.TYPE_NORMAL); 8969 permissionMap.put(p.info.name, bp); 8970 } 8971 8972 if (bp.perm == null) { 8973 if (bp.sourcePackage == null 8974 || bp.sourcePackage.equals(p.info.packageName)) { 8975 BasePermission tree = findPermissionTreeLP(p.info.name); 8976 if (tree == null 8977 || tree.sourcePackage.equals(p.info.packageName)) { 8978 bp.packageSetting = pkgSetting; 8979 bp.perm = p; 8980 bp.uid = pkg.applicationInfo.uid; 8981 bp.sourcePackage = p.info.packageName; 8982 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8983 if (chatty) { 8984 if (r == null) { 8985 r = new StringBuilder(256); 8986 } else { 8987 r.append(' '); 8988 } 8989 r.append(p.info.name); 8990 } 8991 } else { 8992 Slog.w(TAG, "Permission " + p.info.name + " from package " 8993 + p.info.packageName + " ignored: base tree " 8994 + tree.name + " is from package " 8995 + tree.sourcePackage); 8996 } 8997 } else { 8998 Slog.w(TAG, "Permission " + p.info.name + " from package " 8999 + p.info.packageName + " ignored: original from " 9000 + bp.sourcePackage); 9001 } 9002 } else if (chatty) { 9003 if (r == null) { 9004 r = new StringBuilder(256); 9005 } else { 9006 r.append(' '); 9007 } 9008 r.append("DUP:"); 9009 r.append(p.info.name); 9010 } 9011 if (bp.perm == p) { 9012 bp.protectionLevel = p.info.protectionLevel; 9013 } 9014 } 9015 9016 if (r != null) { 9017 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 9018 } 9019 9020 N = pkg.instrumentation.size(); 9021 r = null; 9022 for (i=0; i<N; i++) { 9023 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9024 a.info.packageName = pkg.applicationInfo.packageName; 9025 a.info.sourceDir = pkg.applicationInfo.sourceDir; 9026 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 9027 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 9028 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 9029 a.info.dataDir = pkg.applicationInfo.dataDir; 9030 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 9031 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 9032 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 9033 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 9034 mInstrumentation.put(a.getComponentName(), a); 9035 if (chatty) { 9036 if (r == null) { 9037 r = new StringBuilder(256); 9038 } else { 9039 r.append(' '); 9040 } 9041 r.append(a.info.name); 9042 } 9043 } 9044 if (r != null) { 9045 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9046 } 9047 9048 if (pkg.protectedBroadcasts != null) { 9049 N = pkg.protectedBroadcasts.size(); 9050 for (i=0; i<N; i++) { 9051 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9052 } 9053 } 9054 9055 // Create idmap files for pairs of (packages, overlay packages). 9056 // Note: "android", ie framework-res.apk, is handled by native layers. 9057 if (pkg.mOverlayTarget != null) { 9058 // This is an overlay package. 9059 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9060 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9061 mOverlays.put(pkg.mOverlayTarget, 9062 new ArrayMap<String, PackageParser.Package>()); 9063 } 9064 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9065 map.put(pkg.packageName, pkg); 9066 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9067 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9068 createIdmapFailed = true; 9069 } 9070 } 9071 } else if (mOverlays.containsKey(pkg.packageName) && 9072 !pkg.packageName.equals("android")) { 9073 // This is a regular package, with one or more known overlay packages. 9074 createIdmapsForPackageLI(pkg); 9075 } 9076 } 9077 9078 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9079 9080 if (createIdmapFailed) { 9081 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9082 "scanPackageLI failed to createIdmap"); 9083 } 9084 } 9085 9086 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9087 PackageParser.Package update, int[] userIds) { 9088 if (existing.applicationInfo == null || update.applicationInfo == null) { 9089 // This isn't due to an app installation. 9090 return; 9091 } 9092 9093 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9094 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9095 9096 // The codePath hasn't changed, so there's nothing for us to do. 9097 if (Objects.equals(oldCodePath, newCodePath)) { 9098 return; 9099 } 9100 9101 File canonicalNewCodePath; 9102 try { 9103 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9104 } catch (IOException e) { 9105 Slog.w(TAG, "Failed to get canonical path.", e); 9106 return; 9107 } 9108 9109 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9110 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9111 // that the last component of the path (i.e, the name) doesn't need canonicalization 9112 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9113 // but may change in the future. Hopefully this function won't exist at that point. 9114 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9115 oldCodePath.getName()); 9116 9117 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9118 // with "@". 9119 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9120 if (!oldMarkerPrefix.endsWith("@")) { 9121 oldMarkerPrefix += "@"; 9122 } 9123 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9124 if (!newMarkerPrefix.endsWith("@")) { 9125 newMarkerPrefix += "@"; 9126 } 9127 9128 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9129 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9130 for (String updatedPath : updatedPaths) { 9131 String updatedPathName = new File(updatedPath).getName(); 9132 markerSuffixes.add(updatedPathName.replace('/', '@')); 9133 } 9134 9135 for (int userId : userIds) { 9136 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9137 9138 for (String markerSuffix : markerSuffixes) { 9139 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9140 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9141 if (oldForeignUseMark.exists()) { 9142 try { 9143 Os.rename(oldForeignUseMark.getAbsolutePath(), 9144 newForeignUseMark.getAbsolutePath()); 9145 } catch (ErrnoException e) { 9146 Slog.w(TAG, "Failed to rename foreign use marker", e); 9147 oldForeignUseMark.delete(); 9148 } 9149 } 9150 } 9151 } 9152 } 9153 9154 /** 9155 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9156 * is derived purely on the basis of the contents of {@code scanFile} and 9157 * {@code cpuAbiOverride}. 9158 * 9159 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9160 */ 9161 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9162 String cpuAbiOverride, boolean extractLibs, 9163 File appLib32InstallDir) 9164 throws PackageManagerException { 9165 // TODO: We can probably be smarter about this stuff. For installed apps, 9166 // we can calculate this information at install time once and for all. For 9167 // system apps, we can probably assume that this information doesn't change 9168 // after the first boot scan. As things stand, we do lots of unnecessary work. 9169 9170 // Give ourselves some initial paths; we'll come back for another 9171 // pass once we've determined ABI below. 9172 setNativeLibraryPaths(pkg, appLib32InstallDir); 9173 9174 // We would never need to extract libs for forward-locked and external packages, 9175 // since the container service will do it for us. We shouldn't attempt to 9176 // extract libs from system app when it was not updated. 9177 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9178 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9179 extractLibs = false; 9180 } 9181 9182 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9183 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9184 9185 NativeLibraryHelper.Handle handle = null; 9186 try { 9187 handle = NativeLibraryHelper.Handle.create(pkg); 9188 // TODO(multiArch): This can be null for apps that didn't go through the 9189 // usual installation process. We can calculate it again, like we 9190 // do during install time. 9191 // 9192 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9193 // unnecessary. 9194 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9195 9196 // Null out the abis so that they can be recalculated. 9197 pkg.applicationInfo.primaryCpuAbi = null; 9198 pkg.applicationInfo.secondaryCpuAbi = null; 9199 if (isMultiArch(pkg.applicationInfo)) { 9200 // Warn if we've set an abiOverride for multi-lib packages.. 9201 // By definition, we need to copy both 32 and 64 bit libraries for 9202 // such packages. 9203 if (pkg.cpuAbiOverride != null 9204 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9205 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9206 } 9207 9208 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9209 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9210 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9211 if (extractLibs) { 9212 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9213 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9214 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9215 useIsaSpecificSubdirs); 9216 } else { 9217 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9218 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9219 } 9220 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9221 } 9222 9223 maybeThrowExceptionForMultiArchCopy( 9224 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9225 9226 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9227 if (extractLibs) { 9228 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9229 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9230 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9231 useIsaSpecificSubdirs); 9232 } else { 9233 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9234 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9235 } 9236 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9237 } 9238 9239 maybeThrowExceptionForMultiArchCopy( 9240 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9241 9242 if (abi64 >= 0) { 9243 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9244 } 9245 9246 if (abi32 >= 0) { 9247 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9248 if (abi64 >= 0) { 9249 if (pkg.use32bitAbi) { 9250 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9251 pkg.applicationInfo.primaryCpuAbi = abi; 9252 } else { 9253 pkg.applicationInfo.secondaryCpuAbi = abi; 9254 } 9255 } else { 9256 pkg.applicationInfo.primaryCpuAbi = abi; 9257 } 9258 } 9259 9260 } else { 9261 String[] abiList = (cpuAbiOverride != null) ? 9262 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9263 9264 // Enable gross and lame hacks for apps that are built with old 9265 // SDK tools. We must scan their APKs for renderscript bitcode and 9266 // not launch them if it's present. Don't bother checking on devices 9267 // that don't have 64 bit support. 9268 boolean needsRenderScriptOverride = false; 9269 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9270 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9271 abiList = Build.SUPPORTED_32_BIT_ABIS; 9272 needsRenderScriptOverride = true; 9273 } 9274 9275 final int copyRet; 9276 if (extractLibs) { 9277 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9278 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9279 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9280 } else { 9281 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9282 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9283 } 9284 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9285 9286 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9287 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9288 "Error unpackaging native libs for app, errorCode=" + copyRet); 9289 } 9290 9291 if (copyRet >= 0) { 9292 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9293 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9294 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9295 } else if (needsRenderScriptOverride) { 9296 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9297 } 9298 } 9299 } catch (IOException ioe) { 9300 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9301 } finally { 9302 IoUtils.closeQuietly(handle); 9303 } 9304 9305 // Now that we've calculated the ABIs and determined if it's an internal app, 9306 // we will go ahead and populate the nativeLibraryPath. 9307 setNativeLibraryPaths(pkg, appLib32InstallDir); 9308 } 9309 9310 /** 9311 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9312 * i.e, so that all packages can be run inside a single process if required. 9313 * 9314 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9315 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9316 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9317 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9318 * updating a package that belongs to a shared user. 9319 * 9320 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9321 * adds unnecessary complexity. 9322 */ 9323 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9324 PackageParser.Package scannedPackage) { 9325 String requiredInstructionSet = null; 9326 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9327 requiredInstructionSet = VMRuntime.getInstructionSet( 9328 scannedPackage.applicationInfo.primaryCpuAbi); 9329 } 9330 9331 PackageSetting requirer = null; 9332 for (PackageSetting ps : packagesForUser) { 9333 // If packagesForUser contains scannedPackage, we skip it. This will happen 9334 // when scannedPackage is an update of an existing package. Without this check, 9335 // we will never be able to change the ABI of any package belonging to a shared 9336 // user, even if it's compatible with other packages. 9337 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9338 if (ps.primaryCpuAbiString == null) { 9339 continue; 9340 } 9341 9342 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9343 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9344 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9345 // this but there's not much we can do. 9346 String errorMessage = "Instruction set mismatch, " 9347 + ((requirer == null) ? "[caller]" : requirer) 9348 + " requires " + requiredInstructionSet + " whereas " + ps 9349 + " requires " + instructionSet; 9350 Slog.w(TAG, errorMessage); 9351 } 9352 9353 if (requiredInstructionSet == null) { 9354 requiredInstructionSet = instructionSet; 9355 requirer = ps; 9356 } 9357 } 9358 } 9359 9360 if (requiredInstructionSet != null) { 9361 String adjustedAbi; 9362 if (requirer != null) { 9363 // requirer != null implies that either scannedPackage was null or that scannedPackage 9364 // did not require an ABI, in which case we have to adjust scannedPackage to match 9365 // the ABI of the set (which is the same as requirer's ABI) 9366 adjustedAbi = requirer.primaryCpuAbiString; 9367 if (scannedPackage != null) { 9368 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9369 } 9370 } else { 9371 // requirer == null implies that we're updating all ABIs in the set to 9372 // match scannedPackage. 9373 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9374 } 9375 9376 for (PackageSetting ps : packagesForUser) { 9377 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9378 if (ps.primaryCpuAbiString != null) { 9379 continue; 9380 } 9381 9382 ps.primaryCpuAbiString = adjustedAbi; 9383 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9384 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9385 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9386 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9387 + " (requirer=" 9388 + (requirer == null ? "null" : requirer.pkg.packageName) 9389 + ", scannedPackage=" 9390 + (scannedPackage != null ? scannedPackage.packageName : "null") 9391 + ")"); 9392 try { 9393 mInstaller.rmdex(ps.codePathString, 9394 getDexCodeInstructionSet(getPreferredInstructionSet())); 9395 } catch (InstallerException ignored) { 9396 } 9397 } 9398 } 9399 } 9400 } 9401 } 9402 9403 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9404 synchronized (mPackages) { 9405 mResolverReplaced = true; 9406 // Set up information for custom user intent resolution activity. 9407 mResolveActivity.applicationInfo = pkg.applicationInfo; 9408 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9409 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9410 mResolveActivity.processName = pkg.applicationInfo.packageName; 9411 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9412 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9413 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9414 mResolveActivity.theme = 0; 9415 mResolveActivity.exported = true; 9416 mResolveActivity.enabled = true; 9417 mResolveInfo.activityInfo = mResolveActivity; 9418 mResolveInfo.priority = 0; 9419 mResolveInfo.preferredOrder = 0; 9420 mResolveInfo.match = 0; 9421 mResolveComponentName = mCustomResolverComponentName; 9422 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9423 mResolveComponentName); 9424 } 9425 } 9426 9427 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9428 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9429 9430 // Set up information for ephemeral installer activity 9431 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9432 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9433 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9434 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9435 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9436 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9437 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9438 mEphemeralInstallerActivity.theme = 0; 9439 mEphemeralInstallerActivity.exported = true; 9440 mEphemeralInstallerActivity.enabled = true; 9441 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9442 mEphemeralInstallerInfo.priority = 0; 9443 mEphemeralInstallerInfo.preferredOrder = 1; 9444 mEphemeralInstallerInfo.isDefault = true; 9445 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9446 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9447 9448 if (DEBUG_EPHEMERAL) { 9449 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9450 } 9451 } 9452 9453 private static String calculateBundledApkRoot(final String codePathString) { 9454 final File codePath = new File(codePathString); 9455 final File codeRoot; 9456 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9457 codeRoot = Environment.getRootDirectory(); 9458 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9459 codeRoot = Environment.getOemDirectory(); 9460 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9461 codeRoot = Environment.getVendorDirectory(); 9462 } else { 9463 // Unrecognized code path; take its top real segment as the apk root: 9464 // e.g. /something/app/blah.apk => /something 9465 try { 9466 File f = codePath.getCanonicalFile(); 9467 File parent = f.getParentFile(); // non-null because codePath is a file 9468 File tmp; 9469 while ((tmp = parent.getParentFile()) != null) { 9470 f = parent; 9471 parent = tmp; 9472 } 9473 codeRoot = f; 9474 Slog.w(TAG, "Unrecognized code path " 9475 + codePath + " - using " + codeRoot); 9476 } catch (IOException e) { 9477 // Can't canonicalize the code path -- shenanigans? 9478 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9479 return Environment.getRootDirectory().getPath(); 9480 } 9481 } 9482 return codeRoot.getPath(); 9483 } 9484 9485 /** 9486 * Derive and set the location of native libraries for the given package, 9487 * which varies depending on where and how the package was installed. 9488 */ 9489 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 9490 final ApplicationInfo info = pkg.applicationInfo; 9491 final String codePath = pkg.codePath; 9492 final File codeFile = new File(codePath); 9493 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9494 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9495 9496 info.nativeLibraryRootDir = null; 9497 info.nativeLibraryRootRequiresIsa = false; 9498 info.nativeLibraryDir = null; 9499 info.secondaryNativeLibraryDir = null; 9500 9501 if (isApkFile(codeFile)) { 9502 // Monolithic install 9503 if (bundledApp) { 9504 // If "/system/lib64/apkname" exists, assume that is the per-package 9505 // native library directory to use; otherwise use "/system/lib/apkname". 9506 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9507 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9508 getPrimaryInstructionSet(info)); 9509 9510 // This is a bundled system app so choose the path based on the ABI. 9511 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9512 // is just the default path. 9513 final String apkName = deriveCodePathName(codePath); 9514 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9515 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9516 apkName).getAbsolutePath(); 9517 9518 if (info.secondaryCpuAbi != null) { 9519 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9520 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9521 secondaryLibDir, apkName).getAbsolutePath(); 9522 } 9523 } else if (asecApp) { 9524 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9525 .getAbsolutePath(); 9526 } else { 9527 final String apkName = deriveCodePathName(codePath); 9528 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 9529 .getAbsolutePath(); 9530 } 9531 9532 info.nativeLibraryRootRequiresIsa = false; 9533 info.nativeLibraryDir = info.nativeLibraryRootDir; 9534 } else { 9535 // Cluster install 9536 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9537 info.nativeLibraryRootRequiresIsa = true; 9538 9539 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9540 getPrimaryInstructionSet(info)).getAbsolutePath(); 9541 9542 if (info.secondaryCpuAbi != null) { 9543 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9544 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9545 } 9546 } 9547 } 9548 9549 /** 9550 * Calculate the abis and roots for a bundled app. These can uniquely 9551 * be determined from the contents of the system partition, i.e whether 9552 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9553 * of this information, and instead assume that the system was built 9554 * sensibly. 9555 */ 9556 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9557 PackageSetting pkgSetting) { 9558 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9559 9560 // If "/system/lib64/apkname" exists, assume that is the per-package 9561 // native library directory to use; otherwise use "/system/lib/apkname". 9562 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9563 setBundledAppAbi(pkg, apkRoot, apkName); 9564 // pkgSetting might be null during rescan following uninstall of updates 9565 // to a bundled app, so accommodate that possibility. The settings in 9566 // that case will be established later from the parsed package. 9567 // 9568 // If the settings aren't null, sync them up with what we've just derived. 9569 // note that apkRoot isn't stored in the package settings. 9570 if (pkgSetting != null) { 9571 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9572 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9573 } 9574 } 9575 9576 /** 9577 * Deduces the ABI of a bundled app and sets the relevant fields on the 9578 * parsed pkg object. 9579 * 9580 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9581 * under which system libraries are installed. 9582 * @param apkName the name of the installed package. 9583 */ 9584 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9585 final File codeFile = new File(pkg.codePath); 9586 9587 final boolean has64BitLibs; 9588 final boolean has32BitLibs; 9589 if (isApkFile(codeFile)) { 9590 // Monolithic install 9591 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9592 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9593 } else { 9594 // Cluster install 9595 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9596 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9597 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9598 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9599 has64BitLibs = (new File(rootDir, isa)).exists(); 9600 } else { 9601 has64BitLibs = false; 9602 } 9603 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9604 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9605 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9606 has32BitLibs = (new File(rootDir, isa)).exists(); 9607 } else { 9608 has32BitLibs = false; 9609 } 9610 } 9611 9612 if (has64BitLibs && !has32BitLibs) { 9613 // The package has 64 bit libs, but not 32 bit libs. Its primary 9614 // ABI should be 64 bit. We can safely assume here that the bundled 9615 // native libraries correspond to the most preferred ABI in the list. 9616 9617 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9618 pkg.applicationInfo.secondaryCpuAbi = null; 9619 } else if (has32BitLibs && !has64BitLibs) { 9620 // The package has 32 bit libs but not 64 bit libs. Its primary 9621 // ABI should be 32 bit. 9622 9623 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9624 pkg.applicationInfo.secondaryCpuAbi = null; 9625 } else if (has32BitLibs && has64BitLibs) { 9626 // The application has both 64 and 32 bit bundled libraries. We check 9627 // here that the app declares multiArch support, and warn if it doesn't. 9628 // 9629 // We will be lenient here and record both ABIs. The primary will be the 9630 // ABI that's higher on the list, i.e, a device that's configured to prefer 9631 // 64 bit apps will see a 64 bit primary ABI, 9632 9633 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9634 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9635 } 9636 9637 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9638 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9639 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9640 } else { 9641 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9642 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9643 } 9644 } else { 9645 pkg.applicationInfo.primaryCpuAbi = null; 9646 pkg.applicationInfo.secondaryCpuAbi = null; 9647 } 9648 } 9649 9650 private void killApplication(String pkgName, int appId, String reason) { 9651 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9652 } 9653 9654 private void killApplication(String pkgName, int appId, int userId, String reason) { 9655 // Request the ActivityManager to kill the process(only for existing packages) 9656 // so that we do not end up in a confused state while the user is still using the older 9657 // version of the application while the new one gets installed. 9658 final long token = Binder.clearCallingIdentity(); 9659 try { 9660 IActivityManager am = ActivityManagerNative.getDefault(); 9661 if (am != null) { 9662 try { 9663 am.killApplication(pkgName, appId, userId, reason); 9664 } catch (RemoteException e) { 9665 } 9666 } 9667 } finally { 9668 Binder.restoreCallingIdentity(token); 9669 } 9670 } 9671 9672 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9673 // Remove the parent package setting 9674 PackageSetting ps = (PackageSetting) pkg.mExtras; 9675 if (ps != null) { 9676 removePackageLI(ps, chatty); 9677 } 9678 // Remove the child package setting 9679 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9680 for (int i = 0; i < childCount; i++) { 9681 PackageParser.Package childPkg = pkg.childPackages.get(i); 9682 ps = (PackageSetting) childPkg.mExtras; 9683 if (ps != null) { 9684 removePackageLI(ps, chatty); 9685 } 9686 } 9687 } 9688 9689 void removePackageLI(PackageSetting ps, boolean chatty) { 9690 if (DEBUG_INSTALL) { 9691 if (chatty) 9692 Log.d(TAG, "Removing package " + ps.name); 9693 } 9694 9695 // writer 9696 synchronized (mPackages) { 9697 mPackages.remove(ps.name); 9698 final PackageParser.Package pkg = ps.pkg; 9699 if (pkg != null) { 9700 cleanPackageDataStructuresLILPw(pkg, chatty); 9701 } 9702 } 9703 } 9704 9705 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9706 if (DEBUG_INSTALL) { 9707 if (chatty) 9708 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9709 } 9710 9711 // writer 9712 synchronized (mPackages) { 9713 // Remove the parent package 9714 mPackages.remove(pkg.applicationInfo.packageName); 9715 cleanPackageDataStructuresLILPw(pkg, chatty); 9716 9717 // Remove the child packages 9718 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9719 for (int i = 0; i < childCount; i++) { 9720 PackageParser.Package childPkg = pkg.childPackages.get(i); 9721 mPackages.remove(childPkg.applicationInfo.packageName); 9722 cleanPackageDataStructuresLILPw(childPkg, chatty); 9723 } 9724 } 9725 } 9726 9727 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9728 int N = pkg.providers.size(); 9729 StringBuilder r = null; 9730 int i; 9731 for (i=0; i<N; i++) { 9732 PackageParser.Provider p = pkg.providers.get(i); 9733 mProviders.removeProvider(p); 9734 if (p.info.authority == null) { 9735 9736 /* There was another ContentProvider with this authority when 9737 * this app was installed so this authority is null, 9738 * Ignore it as we don't have to unregister the provider. 9739 */ 9740 continue; 9741 } 9742 String names[] = p.info.authority.split(";"); 9743 for (int j = 0; j < names.length; j++) { 9744 if (mProvidersByAuthority.get(names[j]) == p) { 9745 mProvidersByAuthority.remove(names[j]); 9746 if (DEBUG_REMOVE) { 9747 if (chatty) 9748 Log.d(TAG, "Unregistered content provider: " + names[j] 9749 + ", className = " + p.info.name + ", isSyncable = " 9750 + p.info.isSyncable); 9751 } 9752 } 9753 } 9754 if (DEBUG_REMOVE && chatty) { 9755 if (r == null) { 9756 r = new StringBuilder(256); 9757 } else { 9758 r.append(' '); 9759 } 9760 r.append(p.info.name); 9761 } 9762 } 9763 if (r != null) { 9764 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9765 } 9766 9767 N = pkg.services.size(); 9768 r = null; 9769 for (i=0; i<N; i++) { 9770 PackageParser.Service s = pkg.services.get(i); 9771 mServices.removeService(s); 9772 if (chatty) { 9773 if (r == null) { 9774 r = new StringBuilder(256); 9775 } else { 9776 r.append(' '); 9777 } 9778 r.append(s.info.name); 9779 } 9780 } 9781 if (r != null) { 9782 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9783 } 9784 9785 N = pkg.receivers.size(); 9786 r = null; 9787 for (i=0; i<N; i++) { 9788 PackageParser.Activity a = pkg.receivers.get(i); 9789 mReceivers.removeActivity(a, "receiver"); 9790 if (DEBUG_REMOVE && chatty) { 9791 if (r == null) { 9792 r = new StringBuilder(256); 9793 } else { 9794 r.append(' '); 9795 } 9796 r.append(a.info.name); 9797 } 9798 } 9799 if (r != null) { 9800 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9801 } 9802 9803 N = pkg.activities.size(); 9804 r = null; 9805 for (i=0; i<N; i++) { 9806 PackageParser.Activity a = pkg.activities.get(i); 9807 mActivities.removeActivity(a, "activity"); 9808 if (DEBUG_REMOVE && chatty) { 9809 if (r == null) { 9810 r = new StringBuilder(256); 9811 } else { 9812 r.append(' '); 9813 } 9814 r.append(a.info.name); 9815 } 9816 } 9817 if (r != null) { 9818 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9819 } 9820 9821 N = pkg.permissions.size(); 9822 r = null; 9823 for (i=0; i<N; i++) { 9824 PackageParser.Permission p = pkg.permissions.get(i); 9825 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9826 if (bp == null) { 9827 bp = mSettings.mPermissionTrees.get(p.info.name); 9828 } 9829 if (bp != null && bp.perm == p) { 9830 bp.perm = null; 9831 if (DEBUG_REMOVE && chatty) { 9832 if (r == null) { 9833 r = new StringBuilder(256); 9834 } else { 9835 r.append(' '); 9836 } 9837 r.append(p.info.name); 9838 } 9839 } 9840 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9841 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9842 if (appOpPkgs != null) { 9843 appOpPkgs.remove(pkg.packageName); 9844 } 9845 } 9846 } 9847 if (r != null) { 9848 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9849 } 9850 9851 N = pkg.requestedPermissions.size(); 9852 r = null; 9853 for (i=0; i<N; i++) { 9854 String perm = pkg.requestedPermissions.get(i); 9855 BasePermission bp = mSettings.mPermissions.get(perm); 9856 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9857 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9858 if (appOpPkgs != null) { 9859 appOpPkgs.remove(pkg.packageName); 9860 if (appOpPkgs.isEmpty()) { 9861 mAppOpPermissionPackages.remove(perm); 9862 } 9863 } 9864 } 9865 } 9866 if (r != null) { 9867 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9868 } 9869 9870 N = pkg.instrumentation.size(); 9871 r = null; 9872 for (i=0; i<N; i++) { 9873 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9874 mInstrumentation.remove(a.getComponentName()); 9875 if (DEBUG_REMOVE && chatty) { 9876 if (r == null) { 9877 r = new StringBuilder(256); 9878 } else { 9879 r.append(' '); 9880 } 9881 r.append(a.info.name); 9882 } 9883 } 9884 if (r != null) { 9885 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9886 } 9887 9888 r = null; 9889 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9890 // Only system apps can hold shared libraries. 9891 if (pkg.libraryNames != null) { 9892 for (i=0; i<pkg.libraryNames.size(); i++) { 9893 String name = pkg.libraryNames.get(i); 9894 SharedLibraryEntry cur = mSharedLibraries.get(name); 9895 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9896 mSharedLibraries.remove(name); 9897 if (DEBUG_REMOVE && chatty) { 9898 if (r == null) { 9899 r = new StringBuilder(256); 9900 } else { 9901 r.append(' '); 9902 } 9903 r.append(name); 9904 } 9905 } 9906 } 9907 } 9908 } 9909 if (r != null) { 9910 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9911 } 9912 } 9913 9914 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9915 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9916 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9917 return true; 9918 } 9919 } 9920 return false; 9921 } 9922 9923 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9924 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9925 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9926 9927 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9928 // Update the parent permissions 9929 updatePermissionsLPw(pkg.packageName, pkg, flags); 9930 // Update the child permissions 9931 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9932 for (int i = 0; i < childCount; i++) { 9933 PackageParser.Package childPkg = pkg.childPackages.get(i); 9934 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9935 } 9936 } 9937 9938 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9939 int flags) { 9940 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9941 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9942 } 9943 9944 private void updatePermissionsLPw(String changingPkg, 9945 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9946 // Make sure there are no dangling permission trees. 9947 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9948 while (it.hasNext()) { 9949 final BasePermission bp = it.next(); 9950 if (bp.packageSetting == null) { 9951 // We may not yet have parsed the package, so just see if 9952 // we still know about its settings. 9953 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9954 } 9955 if (bp.packageSetting == null) { 9956 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9957 + " from package " + bp.sourcePackage); 9958 it.remove(); 9959 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9960 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9961 Slog.i(TAG, "Removing old permission tree: " + bp.name 9962 + " from package " + bp.sourcePackage); 9963 flags |= UPDATE_PERMISSIONS_ALL; 9964 it.remove(); 9965 } 9966 } 9967 } 9968 9969 // Make sure all dynamic permissions have been assigned to a package, 9970 // and make sure there are no dangling permissions. 9971 it = mSettings.mPermissions.values().iterator(); 9972 while (it.hasNext()) { 9973 final BasePermission bp = it.next(); 9974 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9975 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9976 + bp.name + " pkg=" + bp.sourcePackage 9977 + " info=" + bp.pendingInfo); 9978 if (bp.packageSetting == null && bp.pendingInfo != null) { 9979 final BasePermission tree = findPermissionTreeLP(bp.name); 9980 if (tree != null && tree.perm != null) { 9981 bp.packageSetting = tree.packageSetting; 9982 bp.perm = new PackageParser.Permission(tree.perm.owner, 9983 new PermissionInfo(bp.pendingInfo)); 9984 bp.perm.info.packageName = tree.perm.info.packageName; 9985 bp.perm.info.name = bp.name; 9986 bp.uid = tree.uid; 9987 } 9988 } 9989 } 9990 if (bp.packageSetting == null) { 9991 // We may not yet have parsed the package, so just see if 9992 // we still know about its settings. 9993 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9994 } 9995 if (bp.packageSetting == null) { 9996 Slog.w(TAG, "Removing dangling permission: " + bp.name 9997 + " from package " + bp.sourcePackage); 9998 it.remove(); 9999 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10000 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10001 Slog.i(TAG, "Removing old permission: " + bp.name 10002 + " from package " + bp.sourcePackage); 10003 flags |= UPDATE_PERMISSIONS_ALL; 10004 it.remove(); 10005 } 10006 } 10007 } 10008 10009 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 10010 // Now update the permissions for all packages, in particular 10011 // replace the granted permissions of the system packages. 10012 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 10013 for (PackageParser.Package pkg : mPackages.values()) { 10014 if (pkg != pkgInfo) { 10015 // Only replace for packages on requested volume 10016 final String volumeUuid = getVolumeUuidForPackage(pkg); 10017 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 10018 && Objects.equals(replaceVolumeUuid, volumeUuid); 10019 grantPermissionsLPw(pkg, replace, changingPkg); 10020 } 10021 } 10022 } 10023 10024 if (pkgInfo != null) { 10025 // Only replace for packages on requested volume 10026 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 10027 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 10028 && Objects.equals(replaceVolumeUuid, volumeUuid); 10029 grantPermissionsLPw(pkgInfo, replace, changingPkg); 10030 } 10031 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10032 } 10033 10034 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 10035 String packageOfInterest) { 10036 // IMPORTANT: There are two types of permissions: install and runtime. 10037 // Install time permissions are granted when the app is installed to 10038 // all device users and users added in the future. Runtime permissions 10039 // are granted at runtime explicitly to specific users. Normal and signature 10040 // protected permissions are install time permissions. Dangerous permissions 10041 // are install permissions if the app's target SDK is Lollipop MR1 or older, 10042 // otherwise they are runtime permissions. This function does not manage 10043 // runtime permissions except for the case an app targeting Lollipop MR1 10044 // being upgraded to target a newer SDK, in which case dangerous permissions 10045 // are transformed from install time to runtime ones. 10046 10047 final PackageSetting ps = (PackageSetting) pkg.mExtras; 10048 if (ps == null) { 10049 return; 10050 } 10051 10052 PermissionsState permissionsState = ps.getPermissionsState(); 10053 PermissionsState origPermissions = permissionsState; 10054 10055 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10056 10057 boolean runtimePermissionsRevoked = false; 10058 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10059 10060 boolean changedInstallPermission = false; 10061 10062 if (replace) { 10063 ps.installPermissionsFixed = false; 10064 if (!ps.isSharedUser()) { 10065 origPermissions = new PermissionsState(permissionsState); 10066 permissionsState.reset(); 10067 } else { 10068 // We need to know only about runtime permission changes since the 10069 // calling code always writes the install permissions state but 10070 // the runtime ones are written only if changed. The only cases of 10071 // changed runtime permissions here are promotion of an install to 10072 // runtime and revocation of a runtime from a shared user. 10073 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10074 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10075 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10076 runtimePermissionsRevoked = true; 10077 } 10078 } 10079 } 10080 10081 permissionsState.setGlobalGids(mGlobalGids); 10082 10083 final int N = pkg.requestedPermissions.size(); 10084 for (int i=0; i<N; i++) { 10085 final String name = pkg.requestedPermissions.get(i); 10086 final BasePermission bp = mSettings.mPermissions.get(name); 10087 10088 if (DEBUG_INSTALL) { 10089 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10090 } 10091 10092 if (bp == null || bp.packageSetting == null) { 10093 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10094 Slog.w(TAG, "Unknown permission " + name 10095 + " in package " + pkg.packageName); 10096 } 10097 continue; 10098 } 10099 10100 10101 // Limit ephemeral apps to ephemeral allowed permissions. 10102 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 10103 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 10104 + pkg.packageName); 10105 continue; 10106 } 10107 10108 final String perm = bp.name; 10109 boolean allowedSig = false; 10110 int grant = GRANT_DENIED; 10111 10112 // Keep track of app op permissions. 10113 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10114 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10115 if (pkgs == null) { 10116 pkgs = new ArraySet<>(); 10117 mAppOpPermissionPackages.put(bp.name, pkgs); 10118 } 10119 pkgs.add(pkg.packageName); 10120 } 10121 10122 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10123 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10124 >= Build.VERSION_CODES.M; 10125 switch (level) { 10126 case PermissionInfo.PROTECTION_NORMAL: { 10127 // For all apps normal permissions are install time ones. 10128 grant = GRANT_INSTALL; 10129 } break; 10130 10131 case PermissionInfo.PROTECTION_DANGEROUS: { 10132 // If a permission review is required for legacy apps we represent 10133 // their permissions as always granted runtime ones since we need 10134 // to keep the review required permission flag per user while an 10135 // install permission's state is shared across all users. 10136 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 10137 // For legacy apps dangerous permissions are install time ones. 10138 grant = GRANT_INSTALL; 10139 } else if (origPermissions.hasInstallPermission(bp.name)) { 10140 // For legacy apps that became modern, install becomes runtime. 10141 grant = GRANT_UPGRADE; 10142 } else if (mPromoteSystemApps 10143 && isSystemApp(ps) 10144 && mExistingSystemPackages.contains(ps.name)) { 10145 // For legacy system apps, install becomes runtime. 10146 // We cannot check hasInstallPermission() for system apps since those 10147 // permissions were granted implicitly and not persisted pre-M. 10148 grant = GRANT_UPGRADE; 10149 } else { 10150 // For modern apps keep runtime permissions unchanged. 10151 grant = GRANT_RUNTIME; 10152 } 10153 } break; 10154 10155 case PermissionInfo.PROTECTION_SIGNATURE: { 10156 // For all apps signature permissions are install time ones. 10157 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10158 if (allowedSig) { 10159 grant = GRANT_INSTALL; 10160 } 10161 } break; 10162 } 10163 10164 if (DEBUG_INSTALL) { 10165 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10166 } 10167 10168 if (grant != GRANT_DENIED) { 10169 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10170 // If this is an existing, non-system package, then 10171 // we can't add any new permissions to it. 10172 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10173 // Except... if this is a permission that was added 10174 // to the platform (note: need to only do this when 10175 // updating the platform). 10176 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10177 grant = GRANT_DENIED; 10178 } 10179 } 10180 } 10181 10182 switch (grant) { 10183 case GRANT_INSTALL: { 10184 // Revoke this as runtime permission to handle the case of 10185 // a runtime permission being downgraded to an install one. 10186 // Also in permission review mode we keep dangerous permissions 10187 // for legacy apps 10188 for (int userId : UserManagerService.getInstance().getUserIds()) { 10189 if (origPermissions.getRuntimePermissionState( 10190 bp.name, userId) != null) { 10191 // Revoke the runtime permission and clear the flags. 10192 origPermissions.revokeRuntimePermission(bp, userId); 10193 origPermissions.updatePermissionFlags(bp, userId, 10194 PackageManager.MASK_PERMISSION_FLAGS, 0); 10195 // If we revoked a permission permission, we have to write. 10196 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10197 changedRuntimePermissionUserIds, userId); 10198 } 10199 } 10200 // Grant an install permission. 10201 if (permissionsState.grantInstallPermission(bp) != 10202 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10203 changedInstallPermission = true; 10204 } 10205 } break; 10206 10207 case GRANT_RUNTIME: { 10208 // Grant previously granted runtime permissions. 10209 for (int userId : UserManagerService.getInstance().getUserIds()) { 10210 PermissionState permissionState = origPermissions 10211 .getRuntimePermissionState(bp.name, userId); 10212 int flags = permissionState != null 10213 ? permissionState.getFlags() : 0; 10214 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10215 if (permissionsState.grantRuntimePermission(bp, userId) == 10216 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10217 // If we cannot put the permission as it was, we have to write. 10218 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10219 changedRuntimePermissionUserIds, userId); 10220 } 10221 // If the app supports runtime permissions no need for a review. 10222 if (mPermissionReviewRequired 10223 && appSupportsRuntimePermissions 10224 && (flags & PackageManager 10225 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10226 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10227 // Since we changed the flags, we have to write. 10228 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10229 changedRuntimePermissionUserIds, userId); 10230 } 10231 } else if (mPermissionReviewRequired 10232 && !appSupportsRuntimePermissions) { 10233 // For legacy apps that need a permission review, every new 10234 // runtime permission is granted but it is pending a review. 10235 // We also need to review only platform defined runtime 10236 // permissions as these are the only ones the platform knows 10237 // how to disable the API to simulate revocation as legacy 10238 // apps don't expect to run with revoked permissions. 10239 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10240 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10241 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10242 // We changed the flags, hence have to write. 10243 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10244 changedRuntimePermissionUserIds, userId); 10245 } 10246 } 10247 if (permissionsState.grantRuntimePermission(bp, userId) 10248 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10249 // We changed the permission, hence have to write. 10250 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10251 changedRuntimePermissionUserIds, userId); 10252 } 10253 } 10254 // Propagate the permission flags. 10255 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10256 } 10257 } break; 10258 10259 case GRANT_UPGRADE: { 10260 // Grant runtime permissions for a previously held install permission. 10261 PermissionState permissionState = origPermissions 10262 .getInstallPermissionState(bp.name); 10263 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10264 10265 if (origPermissions.revokeInstallPermission(bp) 10266 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10267 // We will be transferring the permission flags, so clear them. 10268 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10269 PackageManager.MASK_PERMISSION_FLAGS, 0); 10270 changedInstallPermission = true; 10271 } 10272 10273 // If the permission is not to be promoted to runtime we ignore it and 10274 // also its other flags as they are not applicable to install permissions. 10275 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10276 for (int userId : currentUserIds) { 10277 if (permissionsState.grantRuntimePermission(bp, userId) != 10278 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10279 // Transfer the permission flags. 10280 permissionsState.updatePermissionFlags(bp, userId, 10281 flags, flags); 10282 // If we granted the permission, we have to write. 10283 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10284 changedRuntimePermissionUserIds, userId); 10285 } 10286 } 10287 } 10288 } break; 10289 10290 default: { 10291 if (packageOfInterest == null 10292 || packageOfInterest.equals(pkg.packageName)) { 10293 Slog.w(TAG, "Not granting permission " + perm 10294 + " to package " + pkg.packageName 10295 + " because it was previously installed without"); 10296 } 10297 } break; 10298 } 10299 } else { 10300 if (permissionsState.revokeInstallPermission(bp) != 10301 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10302 // Also drop the permission flags. 10303 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10304 PackageManager.MASK_PERMISSION_FLAGS, 0); 10305 changedInstallPermission = true; 10306 Slog.i(TAG, "Un-granting permission " + perm 10307 + " from package " + pkg.packageName 10308 + " (protectionLevel=" + bp.protectionLevel 10309 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10310 + ")"); 10311 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10312 // Don't print warning for app op permissions, since it is fine for them 10313 // not to be granted, there is a UI for the user to decide. 10314 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10315 Slog.w(TAG, "Not granting permission " + perm 10316 + " to package " + pkg.packageName 10317 + " (protectionLevel=" + bp.protectionLevel 10318 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10319 + ")"); 10320 } 10321 } 10322 } 10323 } 10324 10325 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10326 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10327 // This is the first that we have heard about this package, so the 10328 // permissions we have now selected are fixed until explicitly 10329 // changed. 10330 ps.installPermissionsFixed = true; 10331 } 10332 10333 // Persist the runtime permissions state for users with changes. If permissions 10334 // were revoked because no app in the shared user declares them we have to 10335 // write synchronously to avoid losing runtime permissions state. 10336 for (int userId : changedRuntimePermissionUserIds) { 10337 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10338 } 10339 } 10340 10341 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10342 boolean allowed = false; 10343 final int NP = PackageParser.NEW_PERMISSIONS.length; 10344 for (int ip=0; ip<NP; ip++) { 10345 final PackageParser.NewPermissionInfo npi 10346 = PackageParser.NEW_PERMISSIONS[ip]; 10347 if (npi.name.equals(perm) 10348 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10349 allowed = true; 10350 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10351 + pkg.packageName); 10352 break; 10353 } 10354 } 10355 return allowed; 10356 } 10357 10358 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10359 BasePermission bp, PermissionsState origPermissions) { 10360 boolean allowed; 10361 allowed = (compareSignatures( 10362 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10363 == PackageManager.SIGNATURE_MATCH) 10364 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10365 == PackageManager.SIGNATURE_MATCH); 10366 if (!allowed && (bp.protectionLevel 10367 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10368 if (isSystemApp(pkg)) { 10369 // For updated system applications, a system permission 10370 // is granted only if it had been defined by the original application. 10371 if (pkg.isUpdatedSystemApp()) { 10372 final PackageSetting sysPs = mSettings 10373 .getDisabledSystemPkgLPr(pkg.packageName); 10374 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10375 // If the original was granted this permission, we take 10376 // that grant decision as read and propagate it to the 10377 // update. 10378 if (sysPs.isPrivileged()) { 10379 allowed = true; 10380 } 10381 } else { 10382 // The system apk may have been updated with an older 10383 // version of the one on the data partition, but which 10384 // granted a new system permission that it didn't have 10385 // before. In this case we do want to allow the app to 10386 // now get the new permission if the ancestral apk is 10387 // privileged to get it. 10388 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10389 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10390 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10391 allowed = true; 10392 break; 10393 } 10394 } 10395 } 10396 // Also if a privileged parent package on the system image or any of 10397 // its children requested a privileged permission, the updated child 10398 // packages can also get the permission. 10399 if (pkg.parentPackage != null) { 10400 final PackageSetting disabledSysParentPs = mSettings 10401 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10402 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10403 && disabledSysParentPs.isPrivileged()) { 10404 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10405 allowed = true; 10406 } else if (disabledSysParentPs.pkg.childPackages != null) { 10407 final int count = disabledSysParentPs.pkg.childPackages.size(); 10408 for (int i = 0; i < count; i++) { 10409 PackageParser.Package disabledSysChildPkg = 10410 disabledSysParentPs.pkg.childPackages.get(i); 10411 if (isPackageRequestingPermission(disabledSysChildPkg, 10412 perm)) { 10413 allowed = true; 10414 break; 10415 } 10416 } 10417 } 10418 } 10419 } 10420 } 10421 } else { 10422 allowed = isPrivilegedApp(pkg); 10423 } 10424 } 10425 } 10426 if (!allowed) { 10427 if (!allowed && (bp.protectionLevel 10428 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10429 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10430 // If this was a previously normal/dangerous permission that got moved 10431 // to a system permission as part of the runtime permission redesign, then 10432 // we still want to blindly grant it to old apps. 10433 allowed = true; 10434 } 10435 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10436 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10437 // If this permission is to be granted to the system installer and 10438 // this app is an installer, then it gets the permission. 10439 allowed = true; 10440 } 10441 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10442 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10443 // If this permission is to be granted to the system verifier and 10444 // this app is a verifier, then it gets the permission. 10445 allowed = true; 10446 } 10447 if (!allowed && (bp.protectionLevel 10448 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10449 && isSystemApp(pkg)) { 10450 // Any pre-installed system app is allowed to get this permission. 10451 allowed = true; 10452 } 10453 if (!allowed && (bp.protectionLevel 10454 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10455 // For development permissions, a development permission 10456 // is granted only if it was already granted. 10457 allowed = origPermissions.hasInstallPermission(perm); 10458 } 10459 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10460 && pkg.packageName.equals(mSetupWizardPackage)) { 10461 // If this permission is to be granted to the system setup wizard and 10462 // this app is a setup wizard, then it gets the permission. 10463 allowed = true; 10464 } 10465 } 10466 return allowed; 10467 } 10468 10469 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10470 final int permCount = pkg.requestedPermissions.size(); 10471 for (int j = 0; j < permCount; j++) { 10472 String requestedPermission = pkg.requestedPermissions.get(j); 10473 if (permission.equals(requestedPermission)) { 10474 return true; 10475 } 10476 } 10477 return false; 10478 } 10479 10480 final class ActivityIntentResolver 10481 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10482 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10483 boolean defaultOnly, int userId) { 10484 if (!sUserManager.exists(userId)) return null; 10485 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10486 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10487 } 10488 10489 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10490 int userId) { 10491 if (!sUserManager.exists(userId)) return null; 10492 mFlags = flags; 10493 return super.queryIntent(intent, resolvedType, 10494 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10495 } 10496 10497 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10498 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10499 if (!sUserManager.exists(userId)) return null; 10500 if (packageActivities == null) { 10501 return null; 10502 } 10503 mFlags = flags; 10504 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10505 final int N = packageActivities.size(); 10506 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10507 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10508 10509 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10510 for (int i = 0; i < N; ++i) { 10511 intentFilters = packageActivities.get(i).intents; 10512 if (intentFilters != null && intentFilters.size() > 0) { 10513 PackageParser.ActivityIntentInfo[] array = 10514 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10515 intentFilters.toArray(array); 10516 listCut.add(array); 10517 } 10518 } 10519 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10520 } 10521 10522 /** 10523 * Finds a privileged activity that matches the specified activity names. 10524 */ 10525 private PackageParser.Activity findMatchingActivity( 10526 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10527 for (PackageParser.Activity sysActivity : activityList) { 10528 if (sysActivity.info.name.equals(activityInfo.name)) { 10529 return sysActivity; 10530 } 10531 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10532 return sysActivity; 10533 } 10534 if (sysActivity.info.targetActivity != null) { 10535 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10536 return sysActivity; 10537 } 10538 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10539 return sysActivity; 10540 } 10541 } 10542 } 10543 return null; 10544 } 10545 10546 public class IterGenerator<E> { 10547 public Iterator<E> generate(ActivityIntentInfo info) { 10548 return null; 10549 } 10550 } 10551 10552 public class ActionIterGenerator extends IterGenerator<String> { 10553 @Override 10554 public Iterator<String> generate(ActivityIntentInfo info) { 10555 return info.actionsIterator(); 10556 } 10557 } 10558 10559 public class CategoriesIterGenerator extends IterGenerator<String> { 10560 @Override 10561 public Iterator<String> generate(ActivityIntentInfo info) { 10562 return info.categoriesIterator(); 10563 } 10564 } 10565 10566 public class SchemesIterGenerator extends IterGenerator<String> { 10567 @Override 10568 public Iterator<String> generate(ActivityIntentInfo info) { 10569 return info.schemesIterator(); 10570 } 10571 } 10572 10573 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10574 @Override 10575 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10576 return info.authoritiesIterator(); 10577 } 10578 } 10579 10580 /** 10581 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10582 * MODIFIED. Do not pass in a list that should not be changed. 10583 */ 10584 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10585 IterGenerator<T> generator, Iterator<T> searchIterator) { 10586 // loop through the set of actions; every one must be found in the intent filter 10587 while (searchIterator.hasNext()) { 10588 // we must have at least one filter in the list to consider a match 10589 if (intentList.size() == 0) { 10590 break; 10591 } 10592 10593 final T searchAction = searchIterator.next(); 10594 10595 // loop through the set of intent filters 10596 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10597 while (intentIter.hasNext()) { 10598 final ActivityIntentInfo intentInfo = intentIter.next(); 10599 boolean selectionFound = false; 10600 10601 // loop through the intent filter's selection criteria; at least one 10602 // of them must match the searched criteria 10603 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10604 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10605 final T intentSelection = intentSelectionIter.next(); 10606 if (intentSelection != null && intentSelection.equals(searchAction)) { 10607 selectionFound = true; 10608 break; 10609 } 10610 } 10611 10612 // the selection criteria wasn't found in this filter's set; this filter 10613 // is not a potential match 10614 if (!selectionFound) { 10615 intentIter.remove(); 10616 } 10617 } 10618 } 10619 } 10620 10621 private boolean isProtectedAction(ActivityIntentInfo filter) { 10622 final Iterator<String> actionsIter = filter.actionsIterator(); 10623 while (actionsIter != null && actionsIter.hasNext()) { 10624 final String filterAction = actionsIter.next(); 10625 if (PROTECTED_ACTIONS.contains(filterAction)) { 10626 return true; 10627 } 10628 } 10629 return false; 10630 } 10631 10632 /** 10633 * Adjusts the priority of the given intent filter according to policy. 10634 * <p> 10635 * <ul> 10636 * <li>The priority for non privileged applications is capped to '0'</li> 10637 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10638 * <li>The priority for unbundled updates to privileged applications is capped to the 10639 * priority defined on the system partition</li> 10640 * </ul> 10641 * <p> 10642 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10643 * allowed to obtain any priority on any action. 10644 */ 10645 private void adjustPriority( 10646 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10647 // nothing to do; priority is fine as-is 10648 if (intent.getPriority() <= 0) { 10649 return; 10650 } 10651 10652 final ActivityInfo activityInfo = intent.activity.info; 10653 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10654 10655 final boolean privilegedApp = 10656 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10657 if (!privilegedApp) { 10658 // non-privileged applications can never define a priority >0 10659 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10660 + " package: " + applicationInfo.packageName 10661 + " activity: " + intent.activity.className 10662 + " origPrio: " + intent.getPriority()); 10663 intent.setPriority(0); 10664 return; 10665 } 10666 10667 if (systemActivities == null) { 10668 // the system package is not disabled; we're parsing the system partition 10669 if (isProtectedAction(intent)) { 10670 if (mDeferProtectedFilters) { 10671 // We can't deal with these just yet. No component should ever obtain a 10672 // >0 priority for a protected actions, with ONE exception -- the setup 10673 // wizard. The setup wizard, however, cannot be known until we're able to 10674 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10675 // until all intent filters have been processed. Chicken, meet egg. 10676 // Let the filter temporarily have a high priority and rectify the 10677 // priorities after all system packages have been scanned. 10678 mProtectedFilters.add(intent); 10679 if (DEBUG_FILTERS) { 10680 Slog.i(TAG, "Protected action; save for later;" 10681 + " package: " + applicationInfo.packageName 10682 + " activity: " + intent.activity.className 10683 + " origPrio: " + intent.getPriority()); 10684 } 10685 return; 10686 } else { 10687 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10688 Slog.i(TAG, "No setup wizard;" 10689 + " All protected intents capped to priority 0"); 10690 } 10691 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10692 if (DEBUG_FILTERS) { 10693 Slog.i(TAG, "Found setup wizard;" 10694 + " allow priority " + intent.getPriority() + ";" 10695 + " package: " + intent.activity.info.packageName 10696 + " activity: " + intent.activity.className 10697 + " priority: " + intent.getPriority()); 10698 } 10699 // setup wizard gets whatever it wants 10700 return; 10701 } 10702 Slog.w(TAG, "Protected action; cap priority to 0;" 10703 + " package: " + intent.activity.info.packageName 10704 + " activity: " + intent.activity.className 10705 + " origPrio: " + intent.getPriority()); 10706 intent.setPriority(0); 10707 return; 10708 } 10709 } 10710 // privileged apps on the system image get whatever priority they request 10711 return; 10712 } 10713 10714 // privileged app unbundled update ... try to find the same activity 10715 final PackageParser.Activity foundActivity = 10716 findMatchingActivity(systemActivities, activityInfo); 10717 if (foundActivity == null) { 10718 // this is a new activity; it cannot obtain >0 priority 10719 if (DEBUG_FILTERS) { 10720 Slog.i(TAG, "New activity; cap priority to 0;" 10721 + " package: " + applicationInfo.packageName 10722 + " activity: " + intent.activity.className 10723 + " origPrio: " + intent.getPriority()); 10724 } 10725 intent.setPriority(0); 10726 return; 10727 } 10728 10729 // found activity, now check for filter equivalence 10730 10731 // a shallow copy is enough; we modify the list, not its contents 10732 final List<ActivityIntentInfo> intentListCopy = 10733 new ArrayList<>(foundActivity.intents); 10734 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10735 10736 // find matching action subsets 10737 final Iterator<String> actionsIterator = intent.actionsIterator(); 10738 if (actionsIterator != null) { 10739 getIntentListSubset( 10740 intentListCopy, new ActionIterGenerator(), actionsIterator); 10741 if (intentListCopy.size() == 0) { 10742 // no more intents to match; we're not equivalent 10743 if (DEBUG_FILTERS) { 10744 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10745 + " package: " + applicationInfo.packageName 10746 + " activity: " + intent.activity.className 10747 + " origPrio: " + intent.getPriority()); 10748 } 10749 intent.setPriority(0); 10750 return; 10751 } 10752 } 10753 10754 // find matching category subsets 10755 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10756 if (categoriesIterator != null) { 10757 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10758 categoriesIterator); 10759 if (intentListCopy.size() == 0) { 10760 // no more intents to match; we're not equivalent 10761 if (DEBUG_FILTERS) { 10762 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10763 + " package: " + applicationInfo.packageName 10764 + " activity: " + intent.activity.className 10765 + " origPrio: " + intent.getPriority()); 10766 } 10767 intent.setPriority(0); 10768 return; 10769 } 10770 } 10771 10772 // find matching schemes subsets 10773 final Iterator<String> schemesIterator = intent.schemesIterator(); 10774 if (schemesIterator != null) { 10775 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10776 schemesIterator); 10777 if (intentListCopy.size() == 0) { 10778 // no more intents to match; we're not equivalent 10779 if (DEBUG_FILTERS) { 10780 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10781 + " package: " + applicationInfo.packageName 10782 + " activity: " + intent.activity.className 10783 + " origPrio: " + intent.getPriority()); 10784 } 10785 intent.setPriority(0); 10786 return; 10787 } 10788 } 10789 10790 // find matching authorities subsets 10791 final Iterator<IntentFilter.AuthorityEntry> 10792 authoritiesIterator = intent.authoritiesIterator(); 10793 if (authoritiesIterator != null) { 10794 getIntentListSubset(intentListCopy, 10795 new AuthoritiesIterGenerator(), 10796 authoritiesIterator); 10797 if (intentListCopy.size() == 0) { 10798 // no more intents to match; we're not equivalent 10799 if (DEBUG_FILTERS) { 10800 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10801 + " package: " + applicationInfo.packageName 10802 + " activity: " + intent.activity.className 10803 + " origPrio: " + intent.getPriority()); 10804 } 10805 intent.setPriority(0); 10806 return; 10807 } 10808 } 10809 10810 // we found matching filter(s); app gets the max priority of all intents 10811 int cappedPriority = 0; 10812 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10813 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10814 } 10815 if (intent.getPriority() > cappedPriority) { 10816 if (DEBUG_FILTERS) { 10817 Slog.i(TAG, "Found matching filter(s);" 10818 + " cap priority to " + cappedPriority + ";" 10819 + " package: " + applicationInfo.packageName 10820 + " activity: " + intent.activity.className 10821 + " origPrio: " + intent.getPriority()); 10822 } 10823 intent.setPriority(cappedPriority); 10824 return; 10825 } 10826 // all this for nothing; the requested priority was <= what was on the system 10827 } 10828 10829 public final void addActivity(PackageParser.Activity a, String type) { 10830 mActivities.put(a.getComponentName(), a); 10831 if (DEBUG_SHOW_INFO) 10832 Log.v( 10833 TAG, " " + type + " " + 10834 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10835 if (DEBUG_SHOW_INFO) 10836 Log.v(TAG, " Class=" + a.info.name); 10837 final int NI = a.intents.size(); 10838 for (int j=0; j<NI; j++) { 10839 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10840 if ("activity".equals(type)) { 10841 final PackageSetting ps = 10842 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10843 final List<PackageParser.Activity> systemActivities = 10844 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10845 adjustPriority(systemActivities, intent); 10846 } 10847 if (DEBUG_SHOW_INFO) { 10848 Log.v(TAG, " IntentFilter:"); 10849 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10850 } 10851 if (!intent.debugCheck()) { 10852 Log.w(TAG, "==> For Activity " + a.info.name); 10853 } 10854 addFilter(intent); 10855 } 10856 } 10857 10858 public final void removeActivity(PackageParser.Activity a, String type) { 10859 mActivities.remove(a.getComponentName()); 10860 if (DEBUG_SHOW_INFO) { 10861 Log.v(TAG, " " + type + " " 10862 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10863 : a.info.name) + ":"); 10864 Log.v(TAG, " Class=" + a.info.name); 10865 } 10866 final int NI = a.intents.size(); 10867 for (int j=0; j<NI; j++) { 10868 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10869 if (DEBUG_SHOW_INFO) { 10870 Log.v(TAG, " IntentFilter:"); 10871 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10872 } 10873 removeFilter(intent); 10874 } 10875 } 10876 10877 @Override 10878 protected boolean allowFilterResult( 10879 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10880 ActivityInfo filterAi = filter.activity.info; 10881 for (int i=dest.size()-1; i>=0; i--) { 10882 ActivityInfo destAi = dest.get(i).activityInfo; 10883 if (destAi.name == filterAi.name 10884 && destAi.packageName == filterAi.packageName) { 10885 return false; 10886 } 10887 } 10888 return true; 10889 } 10890 10891 @Override 10892 protected ActivityIntentInfo[] newArray(int size) { 10893 return new ActivityIntentInfo[size]; 10894 } 10895 10896 @Override 10897 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10898 if (!sUserManager.exists(userId)) return true; 10899 PackageParser.Package p = filter.activity.owner; 10900 if (p != null) { 10901 PackageSetting ps = (PackageSetting)p.mExtras; 10902 if (ps != null) { 10903 // System apps are never considered stopped for purposes of 10904 // filtering, because there may be no way for the user to 10905 // actually re-launch them. 10906 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10907 && ps.getStopped(userId); 10908 } 10909 } 10910 return false; 10911 } 10912 10913 @Override 10914 protected boolean isPackageForFilter(String packageName, 10915 PackageParser.ActivityIntentInfo info) { 10916 return packageName.equals(info.activity.owner.packageName); 10917 } 10918 10919 @Override 10920 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10921 int match, int userId) { 10922 if (!sUserManager.exists(userId)) return null; 10923 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10924 return null; 10925 } 10926 final PackageParser.Activity activity = info.activity; 10927 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10928 if (ps == null) { 10929 return null; 10930 } 10931 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10932 ps.readUserState(userId), userId); 10933 if (ai == null) { 10934 return null; 10935 } 10936 final ResolveInfo res = new ResolveInfo(); 10937 res.activityInfo = ai; 10938 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10939 res.filter = info; 10940 } 10941 if (info != null) { 10942 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10943 } 10944 res.priority = info.getPriority(); 10945 res.preferredOrder = activity.owner.mPreferredOrder; 10946 //System.out.println("Result: " + res.activityInfo.className + 10947 // " = " + res.priority); 10948 res.match = match; 10949 res.isDefault = info.hasDefault; 10950 res.labelRes = info.labelRes; 10951 res.nonLocalizedLabel = info.nonLocalizedLabel; 10952 if (userNeedsBadging(userId)) { 10953 res.noResourceId = true; 10954 } else { 10955 res.icon = info.icon; 10956 } 10957 res.iconResourceId = info.icon; 10958 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10959 return res; 10960 } 10961 10962 @Override 10963 protected void sortResults(List<ResolveInfo> results) { 10964 Collections.sort(results, mResolvePrioritySorter); 10965 } 10966 10967 @Override 10968 protected void dumpFilter(PrintWriter out, String prefix, 10969 PackageParser.ActivityIntentInfo filter) { 10970 out.print(prefix); out.print( 10971 Integer.toHexString(System.identityHashCode(filter.activity))); 10972 out.print(' '); 10973 filter.activity.printComponentShortName(out); 10974 out.print(" filter "); 10975 out.println(Integer.toHexString(System.identityHashCode(filter))); 10976 } 10977 10978 @Override 10979 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10980 return filter.activity; 10981 } 10982 10983 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10984 PackageParser.Activity activity = (PackageParser.Activity)label; 10985 out.print(prefix); out.print( 10986 Integer.toHexString(System.identityHashCode(activity))); 10987 out.print(' '); 10988 activity.printComponentShortName(out); 10989 if (count > 1) { 10990 out.print(" ("); out.print(count); out.print(" filters)"); 10991 } 10992 out.println(); 10993 } 10994 10995 // Keys are String (activity class name), values are Activity. 10996 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10997 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10998 private int mFlags; 10999 } 11000 11001 private final class ServiceIntentResolver 11002 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 11003 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11004 boolean defaultOnly, int userId) { 11005 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11006 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11007 } 11008 11009 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11010 int userId) { 11011 if (!sUserManager.exists(userId)) return null; 11012 mFlags = flags; 11013 return super.queryIntent(intent, resolvedType, 11014 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11015 } 11016 11017 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11018 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 11019 if (!sUserManager.exists(userId)) return null; 11020 if (packageServices == null) { 11021 return null; 11022 } 11023 mFlags = flags; 11024 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 11025 final int N = packageServices.size(); 11026 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 11027 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 11028 11029 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 11030 for (int i = 0; i < N; ++i) { 11031 intentFilters = packageServices.get(i).intents; 11032 if (intentFilters != null && intentFilters.size() > 0) { 11033 PackageParser.ServiceIntentInfo[] array = 11034 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 11035 intentFilters.toArray(array); 11036 listCut.add(array); 11037 } 11038 } 11039 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11040 } 11041 11042 public final void addService(PackageParser.Service s) { 11043 mServices.put(s.getComponentName(), s); 11044 if (DEBUG_SHOW_INFO) { 11045 Log.v(TAG, " " 11046 + (s.info.nonLocalizedLabel != null 11047 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11048 Log.v(TAG, " Class=" + s.info.name); 11049 } 11050 final int NI = s.intents.size(); 11051 int j; 11052 for (j=0; j<NI; j++) { 11053 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11054 if (DEBUG_SHOW_INFO) { 11055 Log.v(TAG, " IntentFilter:"); 11056 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11057 } 11058 if (!intent.debugCheck()) { 11059 Log.w(TAG, "==> For Service " + s.info.name); 11060 } 11061 addFilter(intent); 11062 } 11063 } 11064 11065 public final void removeService(PackageParser.Service s) { 11066 mServices.remove(s.getComponentName()); 11067 if (DEBUG_SHOW_INFO) { 11068 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11069 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11070 Log.v(TAG, " Class=" + s.info.name); 11071 } 11072 final int NI = s.intents.size(); 11073 int j; 11074 for (j=0; j<NI; j++) { 11075 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11076 if (DEBUG_SHOW_INFO) { 11077 Log.v(TAG, " IntentFilter:"); 11078 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11079 } 11080 removeFilter(intent); 11081 } 11082 } 11083 11084 @Override 11085 protected boolean allowFilterResult( 11086 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11087 ServiceInfo filterSi = filter.service.info; 11088 for (int i=dest.size()-1; i>=0; i--) { 11089 ServiceInfo destAi = dest.get(i).serviceInfo; 11090 if (destAi.name == filterSi.name 11091 && destAi.packageName == filterSi.packageName) { 11092 return false; 11093 } 11094 } 11095 return true; 11096 } 11097 11098 @Override 11099 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11100 return new PackageParser.ServiceIntentInfo[size]; 11101 } 11102 11103 @Override 11104 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11105 if (!sUserManager.exists(userId)) return true; 11106 PackageParser.Package p = filter.service.owner; 11107 if (p != null) { 11108 PackageSetting ps = (PackageSetting)p.mExtras; 11109 if (ps != null) { 11110 // System apps are never considered stopped for purposes of 11111 // filtering, because there may be no way for the user to 11112 // actually re-launch them. 11113 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11114 && ps.getStopped(userId); 11115 } 11116 } 11117 return false; 11118 } 11119 11120 @Override 11121 protected boolean isPackageForFilter(String packageName, 11122 PackageParser.ServiceIntentInfo info) { 11123 return packageName.equals(info.service.owner.packageName); 11124 } 11125 11126 @Override 11127 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11128 int match, int userId) { 11129 if (!sUserManager.exists(userId)) return null; 11130 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11131 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11132 return null; 11133 } 11134 final PackageParser.Service service = info.service; 11135 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11136 if (ps == null) { 11137 return null; 11138 } 11139 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11140 ps.readUserState(userId), userId); 11141 if (si == null) { 11142 return null; 11143 } 11144 final ResolveInfo res = new ResolveInfo(); 11145 res.serviceInfo = si; 11146 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11147 res.filter = filter; 11148 } 11149 res.priority = info.getPriority(); 11150 res.preferredOrder = service.owner.mPreferredOrder; 11151 res.match = match; 11152 res.isDefault = info.hasDefault; 11153 res.labelRes = info.labelRes; 11154 res.nonLocalizedLabel = info.nonLocalizedLabel; 11155 res.icon = info.icon; 11156 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11157 return res; 11158 } 11159 11160 @Override 11161 protected void sortResults(List<ResolveInfo> results) { 11162 Collections.sort(results, mResolvePrioritySorter); 11163 } 11164 11165 @Override 11166 protected void dumpFilter(PrintWriter out, String prefix, 11167 PackageParser.ServiceIntentInfo filter) { 11168 out.print(prefix); out.print( 11169 Integer.toHexString(System.identityHashCode(filter.service))); 11170 out.print(' '); 11171 filter.service.printComponentShortName(out); 11172 out.print(" filter "); 11173 out.println(Integer.toHexString(System.identityHashCode(filter))); 11174 } 11175 11176 @Override 11177 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11178 return filter.service; 11179 } 11180 11181 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11182 PackageParser.Service service = (PackageParser.Service)label; 11183 out.print(prefix); out.print( 11184 Integer.toHexString(System.identityHashCode(service))); 11185 out.print(' '); 11186 service.printComponentShortName(out); 11187 if (count > 1) { 11188 out.print(" ("); out.print(count); out.print(" filters)"); 11189 } 11190 out.println(); 11191 } 11192 11193// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11194// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11195// final List<ResolveInfo> retList = Lists.newArrayList(); 11196// while (i.hasNext()) { 11197// final ResolveInfo resolveInfo = (ResolveInfo) i; 11198// if (isEnabledLP(resolveInfo.serviceInfo)) { 11199// retList.add(resolveInfo); 11200// } 11201// } 11202// return retList; 11203// } 11204 11205 // Keys are String (activity class name), values are Activity. 11206 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11207 = new ArrayMap<ComponentName, PackageParser.Service>(); 11208 private int mFlags; 11209 }; 11210 11211 private final class ProviderIntentResolver 11212 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11213 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11214 boolean defaultOnly, int userId) { 11215 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11216 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11217 } 11218 11219 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11220 int userId) { 11221 if (!sUserManager.exists(userId)) 11222 return null; 11223 mFlags = flags; 11224 return super.queryIntent(intent, resolvedType, 11225 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11226 } 11227 11228 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11229 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11230 if (!sUserManager.exists(userId)) 11231 return null; 11232 if (packageProviders == null) { 11233 return null; 11234 } 11235 mFlags = flags; 11236 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11237 final int N = packageProviders.size(); 11238 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11239 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11240 11241 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11242 for (int i = 0; i < N; ++i) { 11243 intentFilters = packageProviders.get(i).intents; 11244 if (intentFilters != null && intentFilters.size() > 0) { 11245 PackageParser.ProviderIntentInfo[] array = 11246 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11247 intentFilters.toArray(array); 11248 listCut.add(array); 11249 } 11250 } 11251 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11252 } 11253 11254 public final void addProvider(PackageParser.Provider p) { 11255 if (mProviders.containsKey(p.getComponentName())) { 11256 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11257 return; 11258 } 11259 11260 mProviders.put(p.getComponentName(), p); 11261 if (DEBUG_SHOW_INFO) { 11262 Log.v(TAG, " " 11263 + (p.info.nonLocalizedLabel != null 11264 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11265 Log.v(TAG, " Class=" + p.info.name); 11266 } 11267 final int NI = p.intents.size(); 11268 int j; 11269 for (j = 0; j < NI; j++) { 11270 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11271 if (DEBUG_SHOW_INFO) { 11272 Log.v(TAG, " IntentFilter:"); 11273 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11274 } 11275 if (!intent.debugCheck()) { 11276 Log.w(TAG, "==> For Provider " + p.info.name); 11277 } 11278 addFilter(intent); 11279 } 11280 } 11281 11282 public final void removeProvider(PackageParser.Provider p) { 11283 mProviders.remove(p.getComponentName()); 11284 if (DEBUG_SHOW_INFO) { 11285 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11286 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11287 Log.v(TAG, " Class=" + p.info.name); 11288 } 11289 final int NI = p.intents.size(); 11290 int j; 11291 for (j = 0; j < NI; j++) { 11292 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11293 if (DEBUG_SHOW_INFO) { 11294 Log.v(TAG, " IntentFilter:"); 11295 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11296 } 11297 removeFilter(intent); 11298 } 11299 } 11300 11301 @Override 11302 protected boolean allowFilterResult( 11303 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11304 ProviderInfo filterPi = filter.provider.info; 11305 for (int i = dest.size() - 1; i >= 0; i--) { 11306 ProviderInfo destPi = dest.get(i).providerInfo; 11307 if (destPi.name == filterPi.name 11308 && destPi.packageName == filterPi.packageName) { 11309 return false; 11310 } 11311 } 11312 return true; 11313 } 11314 11315 @Override 11316 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11317 return new PackageParser.ProviderIntentInfo[size]; 11318 } 11319 11320 @Override 11321 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11322 if (!sUserManager.exists(userId)) 11323 return true; 11324 PackageParser.Package p = filter.provider.owner; 11325 if (p != null) { 11326 PackageSetting ps = (PackageSetting) p.mExtras; 11327 if (ps != null) { 11328 // System apps are never considered stopped for purposes of 11329 // filtering, because there may be no way for the user to 11330 // actually re-launch them. 11331 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11332 && ps.getStopped(userId); 11333 } 11334 } 11335 return false; 11336 } 11337 11338 @Override 11339 protected boolean isPackageForFilter(String packageName, 11340 PackageParser.ProviderIntentInfo info) { 11341 return packageName.equals(info.provider.owner.packageName); 11342 } 11343 11344 @Override 11345 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11346 int match, int userId) { 11347 if (!sUserManager.exists(userId)) 11348 return null; 11349 final PackageParser.ProviderIntentInfo info = filter; 11350 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11351 return null; 11352 } 11353 final PackageParser.Provider provider = info.provider; 11354 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11355 if (ps == null) { 11356 return null; 11357 } 11358 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11359 ps.readUserState(userId), userId); 11360 if (pi == null) { 11361 return null; 11362 } 11363 final ResolveInfo res = new ResolveInfo(); 11364 res.providerInfo = pi; 11365 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11366 res.filter = filter; 11367 } 11368 res.priority = info.getPriority(); 11369 res.preferredOrder = provider.owner.mPreferredOrder; 11370 res.match = match; 11371 res.isDefault = info.hasDefault; 11372 res.labelRes = info.labelRes; 11373 res.nonLocalizedLabel = info.nonLocalizedLabel; 11374 res.icon = info.icon; 11375 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11376 return res; 11377 } 11378 11379 @Override 11380 protected void sortResults(List<ResolveInfo> results) { 11381 Collections.sort(results, mResolvePrioritySorter); 11382 } 11383 11384 @Override 11385 protected void dumpFilter(PrintWriter out, String prefix, 11386 PackageParser.ProviderIntentInfo filter) { 11387 out.print(prefix); 11388 out.print( 11389 Integer.toHexString(System.identityHashCode(filter.provider))); 11390 out.print(' '); 11391 filter.provider.printComponentShortName(out); 11392 out.print(" filter "); 11393 out.println(Integer.toHexString(System.identityHashCode(filter))); 11394 } 11395 11396 @Override 11397 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11398 return filter.provider; 11399 } 11400 11401 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11402 PackageParser.Provider provider = (PackageParser.Provider)label; 11403 out.print(prefix); out.print( 11404 Integer.toHexString(System.identityHashCode(provider))); 11405 out.print(' '); 11406 provider.printComponentShortName(out); 11407 if (count > 1) { 11408 out.print(" ("); out.print(count); out.print(" filters)"); 11409 } 11410 out.println(); 11411 } 11412 11413 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11414 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11415 private int mFlags; 11416 } 11417 11418 static final class EphemeralIntentResolver 11419 extends IntentResolver<EphemeralResponse, EphemeralResponse> { 11420 /** 11421 * The result that has the highest defined order. Ordering applies on a 11422 * per-package basis. Mapping is from package name to Pair of order and 11423 * EphemeralResolveInfo. 11424 * <p> 11425 * NOTE: This is implemented as a field variable for convenience and efficiency. 11426 * By having a field variable, we're able to track filter ordering as soon as 11427 * a non-zero order is defined. Otherwise, multiple loops across the result set 11428 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11429 * this needs to be contained entirely within {@link #filterResults()}. 11430 */ 11431 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11432 11433 @Override 11434 protected EphemeralResponse[] newArray(int size) { 11435 return new EphemeralResponse[size]; 11436 } 11437 11438 @Override 11439 protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) { 11440 return true; 11441 } 11442 11443 @Override 11444 protected EphemeralResponse newResult(EphemeralResponse responseObj, int match, 11445 int userId) { 11446 if (!sUserManager.exists(userId)) { 11447 return null; 11448 } 11449 final String packageName = responseObj.resolveInfo.getPackageName(); 11450 final Integer order = responseObj.getOrder(); 11451 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11452 mOrderResult.get(packageName); 11453 // ordering is enabled and this item's order isn't high enough 11454 if (lastOrderResult != null && lastOrderResult.first >= order) { 11455 return null; 11456 } 11457 final EphemeralResolveInfo res = responseObj.resolveInfo; 11458 if (order > 0) { 11459 // non-zero order, enable ordering 11460 mOrderResult.put(packageName, new Pair<>(order, res)); 11461 } 11462 return responseObj; 11463 } 11464 11465 @Override 11466 protected void filterResults(List<EphemeralResponse> results) { 11467 // only do work if ordering is enabled [most of the time it won't be] 11468 if (mOrderResult.size() == 0) { 11469 return; 11470 } 11471 int resultSize = results.size(); 11472 for (int i = 0; i < resultSize; i++) { 11473 final EphemeralResolveInfo info = results.get(i).resolveInfo; 11474 final String packageName = info.getPackageName(); 11475 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11476 if (savedInfo == null) { 11477 // package doesn't having ordering 11478 continue; 11479 } 11480 if (savedInfo.second == info) { 11481 // circled back to the highest ordered item; remove from order list 11482 mOrderResult.remove(savedInfo); 11483 if (mOrderResult.size() == 0) { 11484 // no more ordered items 11485 break; 11486 } 11487 continue; 11488 } 11489 // item has a worse order, remove it from the result list 11490 results.remove(i); 11491 resultSize--; 11492 i--; 11493 } 11494 } 11495 } 11496 11497 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11498 new Comparator<ResolveInfo>() { 11499 public int compare(ResolveInfo r1, ResolveInfo r2) { 11500 int v1 = r1.priority; 11501 int v2 = r2.priority; 11502 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11503 if (v1 != v2) { 11504 return (v1 > v2) ? -1 : 1; 11505 } 11506 v1 = r1.preferredOrder; 11507 v2 = r2.preferredOrder; 11508 if (v1 != v2) { 11509 return (v1 > v2) ? -1 : 1; 11510 } 11511 if (r1.isDefault != r2.isDefault) { 11512 return r1.isDefault ? -1 : 1; 11513 } 11514 v1 = r1.match; 11515 v2 = r2.match; 11516 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11517 if (v1 != v2) { 11518 return (v1 > v2) ? -1 : 1; 11519 } 11520 if (r1.system != r2.system) { 11521 return r1.system ? -1 : 1; 11522 } 11523 if (r1.activityInfo != null) { 11524 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11525 } 11526 if (r1.serviceInfo != null) { 11527 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11528 } 11529 if (r1.providerInfo != null) { 11530 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11531 } 11532 return 0; 11533 } 11534 }; 11535 11536 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11537 new Comparator<ProviderInfo>() { 11538 public int compare(ProviderInfo p1, ProviderInfo p2) { 11539 final int v1 = p1.initOrder; 11540 final int v2 = p2.initOrder; 11541 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11542 } 11543 }; 11544 11545 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11546 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11547 final int[] userIds) { 11548 mHandler.post(new Runnable() { 11549 @Override 11550 public void run() { 11551 try { 11552 final IActivityManager am = ActivityManagerNative.getDefault(); 11553 if (am == null) return; 11554 final int[] resolvedUserIds; 11555 if (userIds == null) { 11556 resolvedUserIds = am.getRunningUserIds(); 11557 } else { 11558 resolvedUserIds = userIds; 11559 } 11560 for (int id : resolvedUserIds) { 11561 final Intent intent = new Intent(action, 11562 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11563 if (extras != null) { 11564 intent.putExtras(extras); 11565 } 11566 if (targetPkg != null) { 11567 intent.setPackage(targetPkg); 11568 } 11569 // Modify the UID when posting to other users 11570 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11571 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11572 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11573 intent.putExtra(Intent.EXTRA_UID, uid); 11574 } 11575 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11576 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11577 if (DEBUG_BROADCASTS) { 11578 RuntimeException here = new RuntimeException("here"); 11579 here.fillInStackTrace(); 11580 Slog.d(TAG, "Sending to user " + id + ": " 11581 + intent.toShortString(false, true, false, false) 11582 + " " + intent.getExtras(), here); 11583 } 11584 am.broadcastIntent(null, intent, null, finishedReceiver, 11585 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11586 null, finishedReceiver != null, false, id); 11587 } 11588 } catch (RemoteException ex) { 11589 } 11590 } 11591 }); 11592 } 11593 11594 /** 11595 * Check if the external storage media is available. This is true if there 11596 * is a mounted external storage medium or if the external storage is 11597 * emulated. 11598 */ 11599 private boolean isExternalMediaAvailable() { 11600 return mMediaMounted || Environment.isExternalStorageEmulated(); 11601 } 11602 11603 @Override 11604 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11605 // writer 11606 synchronized (mPackages) { 11607 if (!isExternalMediaAvailable()) { 11608 // If the external storage is no longer mounted at this point, 11609 // the caller may not have been able to delete all of this 11610 // packages files and can not delete any more. Bail. 11611 return null; 11612 } 11613 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11614 if (lastPackage != null) { 11615 pkgs.remove(lastPackage); 11616 } 11617 if (pkgs.size() > 0) { 11618 return pkgs.get(0); 11619 } 11620 } 11621 return null; 11622 } 11623 11624 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11625 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11626 userId, andCode ? 1 : 0, packageName); 11627 if (mSystemReady) { 11628 msg.sendToTarget(); 11629 } else { 11630 if (mPostSystemReadyMessages == null) { 11631 mPostSystemReadyMessages = new ArrayList<>(); 11632 } 11633 mPostSystemReadyMessages.add(msg); 11634 } 11635 } 11636 11637 void startCleaningPackages() { 11638 // reader 11639 if (!isExternalMediaAvailable()) { 11640 return; 11641 } 11642 synchronized (mPackages) { 11643 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11644 return; 11645 } 11646 } 11647 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11648 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11649 IActivityManager am = ActivityManagerNative.getDefault(); 11650 if (am != null) { 11651 try { 11652 am.startService(null, intent, null, mContext.getOpPackageName(), 11653 UserHandle.USER_SYSTEM); 11654 } catch (RemoteException e) { 11655 } 11656 } 11657 } 11658 11659 @Override 11660 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11661 int installFlags, String installerPackageName, int userId) { 11662 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11663 11664 final int callingUid = Binder.getCallingUid(); 11665 enforceCrossUserPermission(callingUid, userId, 11666 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11667 11668 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11669 try { 11670 if (observer != null) { 11671 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11672 } 11673 } catch (RemoteException re) { 11674 } 11675 return; 11676 } 11677 11678 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11679 installFlags |= PackageManager.INSTALL_FROM_ADB; 11680 11681 } else { 11682 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11683 // about installerPackageName. 11684 11685 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11686 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11687 } 11688 11689 UserHandle user; 11690 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11691 user = UserHandle.ALL; 11692 } else { 11693 user = new UserHandle(userId); 11694 } 11695 11696 // Only system components can circumvent runtime permissions when installing. 11697 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11698 && mContext.checkCallingOrSelfPermission(Manifest.permission 11699 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11700 throw new SecurityException("You need the " 11701 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11702 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11703 } 11704 11705 final File originFile = new File(originPath); 11706 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11707 11708 final Message msg = mHandler.obtainMessage(INIT_COPY); 11709 final VerificationInfo verificationInfo = new VerificationInfo( 11710 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11711 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11712 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11713 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11714 null /*certificates*/); 11715 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11716 msg.obj = params; 11717 11718 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11719 System.identityHashCode(msg.obj)); 11720 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11721 System.identityHashCode(msg.obj)); 11722 11723 mHandler.sendMessage(msg); 11724 } 11725 11726 void installStage(String packageName, File stagedDir, String stagedCid, 11727 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11728 String installerPackageName, int installerUid, UserHandle user, 11729 Certificate[][] certificates) { 11730 if (DEBUG_EPHEMERAL) { 11731 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11732 Slog.d(TAG, "Ephemeral install of " + packageName); 11733 } 11734 } 11735 final VerificationInfo verificationInfo = new VerificationInfo( 11736 sessionParams.originatingUri, sessionParams.referrerUri, 11737 sessionParams.originatingUid, installerUid); 11738 11739 final OriginInfo origin; 11740 if (stagedDir != null) { 11741 origin = OriginInfo.fromStagedFile(stagedDir); 11742 } else { 11743 origin = OriginInfo.fromStagedContainer(stagedCid); 11744 } 11745 11746 final Message msg = mHandler.obtainMessage(INIT_COPY); 11747 final InstallParams params = new InstallParams(origin, null, observer, 11748 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11749 verificationInfo, user, sessionParams.abiOverride, 11750 sessionParams.grantedRuntimePermissions, certificates); 11751 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11752 msg.obj = params; 11753 11754 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11755 System.identityHashCode(msg.obj)); 11756 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11757 System.identityHashCode(msg.obj)); 11758 11759 mHandler.sendMessage(msg); 11760 } 11761 11762 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11763 int userId) { 11764 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11765 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 11766 } 11767 11768 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 11769 int appId, int... userIds) { 11770 if (ArrayUtils.isEmpty(userIds)) { 11771 return; 11772 } 11773 Bundle extras = new Bundle(1); 11774 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 11775 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 11776 11777 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11778 packageName, extras, 0, null, null, userIds); 11779 if (isSystem) { 11780 mHandler.post(() -> { 11781 for (int userId : userIds) { 11782 sendBootCompletedBroadcastToSystemApp(packageName, userId); 11783 } 11784 } 11785 ); 11786 } 11787 } 11788 11789 /** 11790 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 11791 * automatically without needing an explicit launch. 11792 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 11793 */ 11794 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 11795 // If user is not running, the app didn't miss any broadcast 11796 if (!mUserManagerInternal.isUserRunning(userId)) { 11797 return; 11798 } 11799 final IActivityManager am = ActivityManagerNative.getDefault(); 11800 try { 11801 // Deliver LOCKED_BOOT_COMPLETED first 11802 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 11803 .setPackage(packageName); 11804 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 11805 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 11806 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11807 11808 // Deliver BOOT_COMPLETED only if user is unlocked 11809 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 11810 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 11811 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 11812 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11813 } 11814 } catch (RemoteException e) { 11815 throw e.rethrowFromSystemServer(); 11816 } 11817 } 11818 11819 @Override 11820 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11821 int userId) { 11822 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11823 PackageSetting pkgSetting; 11824 final int uid = Binder.getCallingUid(); 11825 enforceCrossUserPermission(uid, userId, 11826 true /* requireFullPermission */, true /* checkShell */, 11827 "setApplicationHiddenSetting for user " + userId); 11828 11829 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11830 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11831 return false; 11832 } 11833 11834 long callingId = Binder.clearCallingIdentity(); 11835 try { 11836 boolean sendAdded = false; 11837 boolean sendRemoved = false; 11838 // writer 11839 synchronized (mPackages) { 11840 pkgSetting = mSettings.mPackages.get(packageName); 11841 if (pkgSetting == null) { 11842 return false; 11843 } 11844 // Do not allow "android" is being disabled 11845 if ("android".equals(packageName)) { 11846 Slog.w(TAG, "Cannot hide package: android"); 11847 return false; 11848 } 11849 // Only allow protected packages to hide themselves. 11850 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11851 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11852 Slog.w(TAG, "Not hiding protected package: " + packageName); 11853 return false; 11854 } 11855 11856 if (pkgSetting.getHidden(userId) != hidden) { 11857 pkgSetting.setHidden(hidden, userId); 11858 mSettings.writePackageRestrictionsLPr(userId); 11859 if (hidden) { 11860 sendRemoved = true; 11861 } else { 11862 sendAdded = true; 11863 } 11864 } 11865 } 11866 if (sendAdded) { 11867 sendPackageAddedForUser(packageName, pkgSetting, userId); 11868 return true; 11869 } 11870 if (sendRemoved) { 11871 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11872 "hiding pkg"); 11873 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11874 return true; 11875 } 11876 } finally { 11877 Binder.restoreCallingIdentity(callingId); 11878 } 11879 return false; 11880 } 11881 11882 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11883 int userId) { 11884 final PackageRemovedInfo info = new PackageRemovedInfo(); 11885 info.removedPackage = packageName; 11886 info.removedUsers = new int[] {userId}; 11887 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11888 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11889 } 11890 11891 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11892 if (pkgList.length > 0) { 11893 Bundle extras = new Bundle(1); 11894 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11895 11896 sendPackageBroadcast( 11897 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11898 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11899 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11900 new int[] {userId}); 11901 } 11902 } 11903 11904 /** 11905 * Returns true if application is not found or there was an error. Otherwise it returns 11906 * the hidden state of the package for the given user. 11907 */ 11908 @Override 11909 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11910 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11911 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11912 true /* requireFullPermission */, false /* checkShell */, 11913 "getApplicationHidden for user " + userId); 11914 PackageSetting pkgSetting; 11915 long callingId = Binder.clearCallingIdentity(); 11916 try { 11917 // writer 11918 synchronized (mPackages) { 11919 pkgSetting = mSettings.mPackages.get(packageName); 11920 if (pkgSetting == null) { 11921 return true; 11922 } 11923 return pkgSetting.getHidden(userId); 11924 } 11925 } finally { 11926 Binder.restoreCallingIdentity(callingId); 11927 } 11928 } 11929 11930 /** 11931 * @hide 11932 */ 11933 @Override 11934 public int installExistingPackageAsUser(String packageName, int userId) { 11935 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11936 null); 11937 PackageSetting pkgSetting; 11938 final int uid = Binder.getCallingUid(); 11939 enforceCrossUserPermission(uid, userId, 11940 true /* requireFullPermission */, true /* checkShell */, 11941 "installExistingPackage for user " + userId); 11942 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11943 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11944 } 11945 11946 long callingId = Binder.clearCallingIdentity(); 11947 try { 11948 boolean installed = false; 11949 11950 // writer 11951 synchronized (mPackages) { 11952 pkgSetting = mSettings.mPackages.get(packageName); 11953 if (pkgSetting == null) { 11954 return PackageManager.INSTALL_FAILED_INVALID_URI; 11955 } 11956 if (!pkgSetting.getInstalled(userId)) { 11957 pkgSetting.setInstalled(true, userId); 11958 pkgSetting.setHidden(false, userId); 11959 mSettings.writePackageRestrictionsLPr(userId); 11960 installed = true; 11961 } 11962 } 11963 11964 if (installed) { 11965 if (pkgSetting.pkg != null) { 11966 synchronized (mInstallLock) { 11967 // We don't need to freeze for a brand new install 11968 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11969 } 11970 } 11971 sendPackageAddedForUser(packageName, pkgSetting, userId); 11972 } 11973 } finally { 11974 Binder.restoreCallingIdentity(callingId); 11975 } 11976 11977 return PackageManager.INSTALL_SUCCEEDED; 11978 } 11979 11980 boolean isUserRestricted(int userId, String restrictionKey) { 11981 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11982 if (restrictions.getBoolean(restrictionKey, false)) { 11983 Log.w(TAG, "User is restricted: " + restrictionKey); 11984 return true; 11985 } 11986 return false; 11987 } 11988 11989 @Override 11990 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11991 int userId) { 11992 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11993 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11994 true /* requireFullPermission */, true /* checkShell */, 11995 "setPackagesSuspended for user " + userId); 11996 11997 if (ArrayUtils.isEmpty(packageNames)) { 11998 return packageNames; 11999 } 12000 12001 // List of package names for whom the suspended state has changed. 12002 List<String> changedPackages = new ArrayList<>(packageNames.length); 12003 // List of package names for whom the suspended state is not set as requested in this 12004 // method. 12005 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 12006 long callingId = Binder.clearCallingIdentity(); 12007 try { 12008 for (int i = 0; i < packageNames.length; i++) { 12009 String packageName = packageNames[i]; 12010 boolean changed = false; 12011 final int appId; 12012 synchronized (mPackages) { 12013 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12014 if (pkgSetting == null) { 12015 Slog.w(TAG, "Could not find package setting for package \"" + packageName 12016 + "\". Skipping suspending/un-suspending."); 12017 unactionedPackages.add(packageName); 12018 continue; 12019 } 12020 appId = pkgSetting.appId; 12021 if (pkgSetting.getSuspended(userId) != suspended) { 12022 if (!canSuspendPackageForUserLocked(packageName, userId)) { 12023 unactionedPackages.add(packageName); 12024 continue; 12025 } 12026 pkgSetting.setSuspended(suspended, userId); 12027 mSettings.writePackageRestrictionsLPr(userId); 12028 changed = true; 12029 changedPackages.add(packageName); 12030 } 12031 } 12032 12033 if (changed && suspended) { 12034 killApplication(packageName, UserHandle.getUid(userId, appId), 12035 "suspending package"); 12036 } 12037 } 12038 } finally { 12039 Binder.restoreCallingIdentity(callingId); 12040 } 12041 12042 if (!changedPackages.isEmpty()) { 12043 sendPackagesSuspendedForUser(changedPackages.toArray( 12044 new String[changedPackages.size()]), userId, suspended); 12045 } 12046 12047 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 12048 } 12049 12050 @Override 12051 public boolean isPackageSuspendedForUser(String packageName, int userId) { 12052 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12053 true /* requireFullPermission */, false /* checkShell */, 12054 "isPackageSuspendedForUser for user " + userId); 12055 synchronized (mPackages) { 12056 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12057 if (pkgSetting == null) { 12058 throw new IllegalArgumentException("Unknown target package: " + packageName); 12059 } 12060 return pkgSetting.getSuspended(userId); 12061 } 12062 } 12063 12064 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 12065 if (isPackageDeviceAdmin(packageName, userId)) { 12066 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12067 + "\": has an active device admin"); 12068 return false; 12069 } 12070 12071 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 12072 if (packageName.equals(activeLauncherPackageName)) { 12073 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12074 + "\": contains the active launcher"); 12075 return false; 12076 } 12077 12078 if (packageName.equals(mRequiredInstallerPackage)) { 12079 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12080 + "\": required for package installation"); 12081 return false; 12082 } 12083 12084 if (packageName.equals(mRequiredUninstallerPackage)) { 12085 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12086 + "\": required for package uninstallation"); 12087 return false; 12088 } 12089 12090 if (packageName.equals(mRequiredVerifierPackage)) { 12091 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12092 + "\": required for package verification"); 12093 return false; 12094 } 12095 12096 if (packageName.equals(getDefaultDialerPackageName(userId))) { 12097 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12098 + "\": is the default dialer"); 12099 return false; 12100 } 12101 12102 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12103 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12104 + "\": protected package"); 12105 return false; 12106 } 12107 12108 return true; 12109 } 12110 12111 private String getActiveLauncherPackageName(int userId) { 12112 Intent intent = new Intent(Intent.ACTION_MAIN); 12113 intent.addCategory(Intent.CATEGORY_HOME); 12114 ResolveInfo resolveInfo = resolveIntent( 12115 intent, 12116 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 12117 PackageManager.MATCH_DEFAULT_ONLY, 12118 userId); 12119 12120 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 12121 } 12122 12123 private String getDefaultDialerPackageName(int userId) { 12124 synchronized (mPackages) { 12125 return mSettings.getDefaultDialerPackageNameLPw(userId); 12126 } 12127 } 12128 12129 @Override 12130 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 12131 mContext.enforceCallingOrSelfPermission( 12132 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12133 "Only package verification agents can verify applications"); 12134 12135 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12136 final PackageVerificationResponse response = new PackageVerificationResponse( 12137 verificationCode, Binder.getCallingUid()); 12138 msg.arg1 = id; 12139 msg.obj = response; 12140 mHandler.sendMessage(msg); 12141 } 12142 12143 @Override 12144 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12145 long millisecondsToDelay) { 12146 mContext.enforceCallingOrSelfPermission( 12147 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12148 "Only package verification agents can extend verification timeouts"); 12149 12150 final PackageVerificationState state = mPendingVerification.get(id); 12151 final PackageVerificationResponse response = new PackageVerificationResponse( 12152 verificationCodeAtTimeout, Binder.getCallingUid()); 12153 12154 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12155 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12156 } 12157 if (millisecondsToDelay < 0) { 12158 millisecondsToDelay = 0; 12159 } 12160 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12161 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12162 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12163 } 12164 12165 if ((state != null) && !state.timeoutExtended()) { 12166 state.extendTimeout(); 12167 12168 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12169 msg.arg1 = id; 12170 msg.obj = response; 12171 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12172 } 12173 } 12174 12175 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12176 int verificationCode, UserHandle user) { 12177 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12178 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12179 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12180 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12181 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12182 12183 mContext.sendBroadcastAsUser(intent, user, 12184 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12185 } 12186 12187 private ComponentName matchComponentForVerifier(String packageName, 12188 List<ResolveInfo> receivers) { 12189 ActivityInfo targetReceiver = null; 12190 12191 final int NR = receivers.size(); 12192 for (int i = 0; i < NR; i++) { 12193 final ResolveInfo info = receivers.get(i); 12194 if (info.activityInfo == null) { 12195 continue; 12196 } 12197 12198 if (packageName.equals(info.activityInfo.packageName)) { 12199 targetReceiver = info.activityInfo; 12200 break; 12201 } 12202 } 12203 12204 if (targetReceiver == null) { 12205 return null; 12206 } 12207 12208 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12209 } 12210 12211 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12212 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12213 if (pkgInfo.verifiers.length == 0) { 12214 return null; 12215 } 12216 12217 final int N = pkgInfo.verifiers.length; 12218 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12219 for (int i = 0; i < N; i++) { 12220 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12221 12222 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12223 receivers); 12224 if (comp == null) { 12225 continue; 12226 } 12227 12228 final int verifierUid = getUidForVerifier(verifierInfo); 12229 if (verifierUid == -1) { 12230 continue; 12231 } 12232 12233 if (DEBUG_VERIFY) { 12234 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12235 + " with the correct signature"); 12236 } 12237 sufficientVerifiers.add(comp); 12238 verificationState.addSufficientVerifier(verifierUid); 12239 } 12240 12241 return sufficientVerifiers; 12242 } 12243 12244 private int getUidForVerifier(VerifierInfo verifierInfo) { 12245 synchronized (mPackages) { 12246 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12247 if (pkg == null) { 12248 return -1; 12249 } else if (pkg.mSignatures.length != 1) { 12250 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12251 + " has more than one signature; ignoring"); 12252 return -1; 12253 } 12254 12255 /* 12256 * If the public key of the package's signature does not match 12257 * our expected public key, then this is a different package and 12258 * we should skip. 12259 */ 12260 12261 final byte[] expectedPublicKey; 12262 try { 12263 final Signature verifierSig = pkg.mSignatures[0]; 12264 final PublicKey publicKey = verifierSig.getPublicKey(); 12265 expectedPublicKey = publicKey.getEncoded(); 12266 } catch (CertificateException e) { 12267 return -1; 12268 } 12269 12270 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12271 12272 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12273 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12274 + " does not have the expected public key; ignoring"); 12275 return -1; 12276 } 12277 12278 return pkg.applicationInfo.uid; 12279 } 12280 } 12281 12282 @Override 12283 public void finishPackageInstall(int token, boolean didLaunch) { 12284 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12285 12286 if (DEBUG_INSTALL) { 12287 Slog.v(TAG, "BM finishing package install for " + token); 12288 } 12289 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12290 12291 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12292 mHandler.sendMessage(msg); 12293 } 12294 12295 /** 12296 * Get the verification agent timeout. 12297 * 12298 * @return verification timeout in milliseconds 12299 */ 12300 private long getVerificationTimeout() { 12301 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12302 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12303 DEFAULT_VERIFICATION_TIMEOUT); 12304 } 12305 12306 /** 12307 * Get the default verification agent response code. 12308 * 12309 * @return default verification response code 12310 */ 12311 private int getDefaultVerificationResponse() { 12312 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12313 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12314 DEFAULT_VERIFICATION_RESPONSE); 12315 } 12316 12317 /** 12318 * Check whether or not package verification has been enabled. 12319 * 12320 * @return true if verification should be performed 12321 */ 12322 private boolean isVerificationEnabled(int userId, int installFlags) { 12323 if (!DEFAULT_VERIFY_ENABLE) { 12324 return false; 12325 } 12326 // Ephemeral apps don't get the full verification treatment 12327 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12328 if (DEBUG_EPHEMERAL) { 12329 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12330 } 12331 return false; 12332 } 12333 12334 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12335 12336 // Check if installing from ADB 12337 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12338 // Do not run verification in a test harness environment 12339 if (ActivityManager.isRunningInTestHarness()) { 12340 return false; 12341 } 12342 if (ensureVerifyAppsEnabled) { 12343 return true; 12344 } 12345 // Check if the developer does not want package verification for ADB installs 12346 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12347 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12348 return false; 12349 } 12350 } 12351 12352 if (ensureVerifyAppsEnabled) { 12353 return true; 12354 } 12355 12356 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12357 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12358 } 12359 12360 @Override 12361 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12362 throws RemoteException { 12363 mContext.enforceCallingOrSelfPermission( 12364 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12365 "Only intentfilter verification agents can verify applications"); 12366 12367 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12368 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12369 Binder.getCallingUid(), verificationCode, failedDomains); 12370 msg.arg1 = id; 12371 msg.obj = response; 12372 mHandler.sendMessage(msg); 12373 } 12374 12375 @Override 12376 public int getIntentVerificationStatus(String packageName, int userId) { 12377 synchronized (mPackages) { 12378 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12379 } 12380 } 12381 12382 @Override 12383 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12384 mContext.enforceCallingOrSelfPermission( 12385 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12386 12387 boolean result = false; 12388 synchronized (mPackages) { 12389 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12390 } 12391 if (result) { 12392 scheduleWritePackageRestrictionsLocked(userId); 12393 } 12394 return result; 12395 } 12396 12397 @Override 12398 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12399 String packageName) { 12400 synchronized (mPackages) { 12401 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12402 } 12403 } 12404 12405 @Override 12406 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12407 if (TextUtils.isEmpty(packageName)) { 12408 return ParceledListSlice.emptyList(); 12409 } 12410 synchronized (mPackages) { 12411 PackageParser.Package pkg = mPackages.get(packageName); 12412 if (pkg == null || pkg.activities == null) { 12413 return ParceledListSlice.emptyList(); 12414 } 12415 final int count = pkg.activities.size(); 12416 ArrayList<IntentFilter> result = new ArrayList<>(); 12417 for (int n=0; n<count; n++) { 12418 PackageParser.Activity activity = pkg.activities.get(n); 12419 if (activity.intents != null && activity.intents.size() > 0) { 12420 result.addAll(activity.intents); 12421 } 12422 } 12423 return new ParceledListSlice<>(result); 12424 } 12425 } 12426 12427 @Override 12428 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12429 mContext.enforceCallingOrSelfPermission( 12430 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12431 12432 synchronized (mPackages) { 12433 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12434 if (packageName != null) { 12435 result |= updateIntentVerificationStatus(packageName, 12436 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12437 userId); 12438 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12439 packageName, userId); 12440 } 12441 return result; 12442 } 12443 } 12444 12445 @Override 12446 public String getDefaultBrowserPackageName(int userId) { 12447 synchronized (mPackages) { 12448 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12449 } 12450 } 12451 12452 /** 12453 * Get the "allow unknown sources" setting. 12454 * 12455 * @return the current "allow unknown sources" setting 12456 */ 12457 private int getUnknownSourcesSettings() { 12458 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12459 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12460 -1); 12461 } 12462 12463 @Override 12464 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12465 final int uid = Binder.getCallingUid(); 12466 // writer 12467 synchronized (mPackages) { 12468 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12469 if (targetPackageSetting == null) { 12470 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12471 } 12472 12473 PackageSetting installerPackageSetting; 12474 if (installerPackageName != null) { 12475 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12476 if (installerPackageSetting == null) { 12477 throw new IllegalArgumentException("Unknown installer package: " 12478 + installerPackageName); 12479 } 12480 } else { 12481 installerPackageSetting = null; 12482 } 12483 12484 Signature[] callerSignature; 12485 Object obj = mSettings.getUserIdLPr(uid); 12486 if (obj != null) { 12487 if (obj instanceof SharedUserSetting) { 12488 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12489 } else if (obj instanceof PackageSetting) { 12490 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12491 } else { 12492 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12493 } 12494 } else { 12495 throw new SecurityException("Unknown calling UID: " + uid); 12496 } 12497 12498 // Verify: can't set installerPackageName to a package that is 12499 // not signed with the same cert as the caller. 12500 if (installerPackageSetting != null) { 12501 if (compareSignatures(callerSignature, 12502 installerPackageSetting.signatures.mSignatures) 12503 != PackageManager.SIGNATURE_MATCH) { 12504 throw new SecurityException( 12505 "Caller does not have same cert as new installer package " 12506 + installerPackageName); 12507 } 12508 } 12509 12510 // Verify: if target already has an installer package, it must 12511 // be signed with the same cert as the caller. 12512 if (targetPackageSetting.installerPackageName != null) { 12513 PackageSetting setting = mSettings.mPackages.get( 12514 targetPackageSetting.installerPackageName); 12515 // If the currently set package isn't valid, then it's always 12516 // okay to change it. 12517 if (setting != null) { 12518 if (compareSignatures(callerSignature, 12519 setting.signatures.mSignatures) 12520 != PackageManager.SIGNATURE_MATCH) { 12521 throw new SecurityException( 12522 "Caller does not have same cert as old installer package " 12523 + targetPackageSetting.installerPackageName); 12524 } 12525 } 12526 } 12527 12528 // Okay! 12529 targetPackageSetting.installerPackageName = installerPackageName; 12530 if (installerPackageName != null) { 12531 mSettings.mInstallerPackages.add(installerPackageName); 12532 } 12533 scheduleWriteSettingsLocked(); 12534 } 12535 } 12536 12537 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12538 // Queue up an async operation since the package installation may take a little while. 12539 mHandler.post(new Runnable() { 12540 public void run() { 12541 mHandler.removeCallbacks(this); 12542 // Result object to be returned 12543 PackageInstalledInfo res = new PackageInstalledInfo(); 12544 res.setReturnCode(currentStatus); 12545 res.uid = -1; 12546 res.pkg = null; 12547 res.removedInfo = null; 12548 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12549 args.doPreInstall(res.returnCode); 12550 synchronized (mInstallLock) { 12551 installPackageTracedLI(args, res); 12552 } 12553 args.doPostInstall(res.returnCode, res.uid); 12554 } 12555 12556 // A restore should be performed at this point if (a) the install 12557 // succeeded, (b) the operation is not an update, and (c) the new 12558 // package has not opted out of backup participation. 12559 final boolean update = res.removedInfo != null 12560 && res.removedInfo.removedPackage != null; 12561 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12562 boolean doRestore = !update 12563 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12564 12565 // Set up the post-install work request bookkeeping. This will be used 12566 // and cleaned up by the post-install event handling regardless of whether 12567 // there's a restore pass performed. Token values are >= 1. 12568 int token; 12569 if (mNextInstallToken < 0) mNextInstallToken = 1; 12570 token = mNextInstallToken++; 12571 12572 PostInstallData data = new PostInstallData(args, res); 12573 mRunningInstalls.put(token, data); 12574 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12575 12576 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12577 // Pass responsibility to the Backup Manager. It will perform a 12578 // restore if appropriate, then pass responsibility back to the 12579 // Package Manager to run the post-install observer callbacks 12580 // and broadcasts. 12581 IBackupManager bm = IBackupManager.Stub.asInterface( 12582 ServiceManager.getService(Context.BACKUP_SERVICE)); 12583 if (bm != null) { 12584 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12585 + " to BM for possible restore"); 12586 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12587 try { 12588 // TODO: http://b/22388012 12589 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12590 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12591 } else { 12592 doRestore = false; 12593 } 12594 } catch (RemoteException e) { 12595 // can't happen; the backup manager is local 12596 } catch (Exception e) { 12597 Slog.e(TAG, "Exception trying to enqueue restore", e); 12598 doRestore = false; 12599 } 12600 } else { 12601 Slog.e(TAG, "Backup Manager not found!"); 12602 doRestore = false; 12603 } 12604 } 12605 12606 if (!doRestore) { 12607 // No restore possible, or the Backup Manager was mysteriously not 12608 // available -- just fire the post-install work request directly. 12609 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12610 12611 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12612 12613 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12614 mHandler.sendMessage(msg); 12615 } 12616 } 12617 }); 12618 } 12619 12620 /** 12621 * Callback from PackageSettings whenever an app is first transitioned out of the 12622 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12623 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12624 * here whether the app is the target of an ongoing install, and only send the 12625 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12626 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12627 * handling. 12628 */ 12629 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12630 // Serialize this with the rest of the install-process message chain. In the 12631 // restore-at-install case, this Runnable will necessarily run before the 12632 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12633 // are coherent. In the non-restore case, the app has already completed install 12634 // and been launched through some other means, so it is not in a problematic 12635 // state for observers to see the FIRST_LAUNCH signal. 12636 mHandler.post(new Runnable() { 12637 @Override 12638 public void run() { 12639 for (int i = 0; i < mRunningInstalls.size(); i++) { 12640 final PostInstallData data = mRunningInstalls.valueAt(i); 12641 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12642 continue; 12643 } 12644 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12645 // right package; but is it for the right user? 12646 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12647 if (userId == data.res.newUsers[uIndex]) { 12648 if (DEBUG_BACKUP) { 12649 Slog.i(TAG, "Package " + pkgName 12650 + " being restored so deferring FIRST_LAUNCH"); 12651 } 12652 return; 12653 } 12654 } 12655 } 12656 } 12657 // didn't find it, so not being restored 12658 if (DEBUG_BACKUP) { 12659 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12660 } 12661 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12662 } 12663 }); 12664 } 12665 12666 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12667 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12668 installerPkg, null, userIds); 12669 } 12670 12671 private abstract class HandlerParams { 12672 private static final int MAX_RETRIES = 4; 12673 12674 /** 12675 * Number of times startCopy() has been attempted and had a non-fatal 12676 * error. 12677 */ 12678 private int mRetries = 0; 12679 12680 /** User handle for the user requesting the information or installation. */ 12681 private final UserHandle mUser; 12682 String traceMethod; 12683 int traceCookie; 12684 12685 HandlerParams(UserHandle user) { 12686 mUser = user; 12687 } 12688 12689 UserHandle getUser() { 12690 return mUser; 12691 } 12692 12693 HandlerParams setTraceMethod(String traceMethod) { 12694 this.traceMethod = traceMethod; 12695 return this; 12696 } 12697 12698 HandlerParams setTraceCookie(int traceCookie) { 12699 this.traceCookie = traceCookie; 12700 return this; 12701 } 12702 12703 final boolean startCopy() { 12704 boolean res; 12705 try { 12706 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12707 12708 if (++mRetries > MAX_RETRIES) { 12709 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12710 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12711 handleServiceError(); 12712 return false; 12713 } else { 12714 handleStartCopy(); 12715 res = true; 12716 } 12717 } catch (RemoteException e) { 12718 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12719 mHandler.sendEmptyMessage(MCS_RECONNECT); 12720 res = false; 12721 } 12722 handleReturnCode(); 12723 return res; 12724 } 12725 12726 final void serviceError() { 12727 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12728 handleServiceError(); 12729 handleReturnCode(); 12730 } 12731 12732 abstract void handleStartCopy() throws RemoteException; 12733 abstract void handleServiceError(); 12734 abstract void handleReturnCode(); 12735 } 12736 12737 class MeasureParams extends HandlerParams { 12738 private final PackageStats mStats; 12739 private boolean mSuccess; 12740 12741 private final IPackageStatsObserver mObserver; 12742 12743 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12744 super(new UserHandle(stats.userHandle)); 12745 mObserver = observer; 12746 mStats = stats; 12747 } 12748 12749 @Override 12750 public String toString() { 12751 return "MeasureParams{" 12752 + Integer.toHexString(System.identityHashCode(this)) 12753 + " " + mStats.packageName + "}"; 12754 } 12755 12756 @Override 12757 void handleStartCopy() throws RemoteException { 12758 synchronized (mInstallLock) { 12759 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12760 } 12761 12762 if (mSuccess) { 12763 boolean mounted = false; 12764 try { 12765 final String status = Environment.getExternalStorageState(); 12766 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12767 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12768 } catch (Exception e) { 12769 } 12770 12771 if (mounted) { 12772 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12773 12774 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12775 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12776 12777 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12778 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12779 12780 // Always subtract cache size, since it's a subdirectory 12781 mStats.externalDataSize -= mStats.externalCacheSize; 12782 12783 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12784 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12785 12786 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12787 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12788 } 12789 } 12790 } 12791 12792 @Override 12793 void handleReturnCode() { 12794 if (mObserver != null) { 12795 try { 12796 mObserver.onGetStatsCompleted(mStats, mSuccess); 12797 } catch (RemoteException e) { 12798 Slog.i(TAG, "Observer no longer exists."); 12799 } 12800 } 12801 } 12802 12803 @Override 12804 void handleServiceError() { 12805 Slog.e(TAG, "Could not measure application " + mStats.packageName 12806 + " external storage"); 12807 } 12808 } 12809 12810 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12811 throws RemoteException { 12812 long result = 0; 12813 for (File path : paths) { 12814 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12815 } 12816 return result; 12817 } 12818 12819 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12820 for (File path : paths) { 12821 try { 12822 mcs.clearDirectory(path.getAbsolutePath()); 12823 } catch (RemoteException e) { 12824 } 12825 } 12826 } 12827 12828 static class OriginInfo { 12829 /** 12830 * Location where install is coming from, before it has been 12831 * copied/renamed into place. This could be a single monolithic APK 12832 * file, or a cluster directory. This location may be untrusted. 12833 */ 12834 final File file; 12835 final String cid; 12836 12837 /** 12838 * Flag indicating that {@link #file} or {@link #cid} has already been 12839 * staged, meaning downstream users don't need to defensively copy the 12840 * contents. 12841 */ 12842 final boolean staged; 12843 12844 /** 12845 * Flag indicating that {@link #file} or {@link #cid} is an already 12846 * installed app that is being moved. 12847 */ 12848 final boolean existing; 12849 12850 final String resolvedPath; 12851 final File resolvedFile; 12852 12853 static OriginInfo fromNothing() { 12854 return new OriginInfo(null, null, false, false); 12855 } 12856 12857 static OriginInfo fromUntrustedFile(File file) { 12858 return new OriginInfo(file, null, false, false); 12859 } 12860 12861 static OriginInfo fromExistingFile(File file) { 12862 return new OriginInfo(file, null, false, true); 12863 } 12864 12865 static OriginInfo fromStagedFile(File file) { 12866 return new OriginInfo(file, null, true, false); 12867 } 12868 12869 static OriginInfo fromStagedContainer(String cid) { 12870 return new OriginInfo(null, cid, true, false); 12871 } 12872 12873 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12874 this.file = file; 12875 this.cid = cid; 12876 this.staged = staged; 12877 this.existing = existing; 12878 12879 if (cid != null) { 12880 resolvedPath = PackageHelper.getSdDir(cid); 12881 resolvedFile = new File(resolvedPath); 12882 } else if (file != null) { 12883 resolvedPath = file.getAbsolutePath(); 12884 resolvedFile = file; 12885 } else { 12886 resolvedPath = null; 12887 resolvedFile = null; 12888 } 12889 } 12890 } 12891 12892 static class MoveInfo { 12893 final int moveId; 12894 final String fromUuid; 12895 final String toUuid; 12896 final String packageName; 12897 final String dataAppName; 12898 final int appId; 12899 final String seinfo; 12900 final int targetSdkVersion; 12901 12902 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12903 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12904 this.moveId = moveId; 12905 this.fromUuid = fromUuid; 12906 this.toUuid = toUuid; 12907 this.packageName = packageName; 12908 this.dataAppName = dataAppName; 12909 this.appId = appId; 12910 this.seinfo = seinfo; 12911 this.targetSdkVersion = targetSdkVersion; 12912 } 12913 } 12914 12915 static class VerificationInfo { 12916 /** A constant used to indicate that a uid value is not present. */ 12917 public static final int NO_UID = -1; 12918 12919 /** URI referencing where the package was downloaded from. */ 12920 final Uri originatingUri; 12921 12922 /** HTTP referrer URI associated with the originatingURI. */ 12923 final Uri referrer; 12924 12925 /** UID of the application that the install request originated from. */ 12926 final int originatingUid; 12927 12928 /** UID of application requesting the install */ 12929 final int installerUid; 12930 12931 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12932 this.originatingUri = originatingUri; 12933 this.referrer = referrer; 12934 this.originatingUid = originatingUid; 12935 this.installerUid = installerUid; 12936 } 12937 } 12938 12939 class InstallParams extends HandlerParams { 12940 final OriginInfo origin; 12941 final MoveInfo move; 12942 final IPackageInstallObserver2 observer; 12943 int installFlags; 12944 final String installerPackageName; 12945 final String volumeUuid; 12946 private InstallArgs mArgs; 12947 private int mRet; 12948 final String packageAbiOverride; 12949 final String[] grantedRuntimePermissions; 12950 final VerificationInfo verificationInfo; 12951 final Certificate[][] certificates; 12952 12953 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12954 int installFlags, String installerPackageName, String volumeUuid, 12955 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12956 String[] grantedPermissions, Certificate[][] certificates) { 12957 super(user); 12958 this.origin = origin; 12959 this.move = move; 12960 this.observer = observer; 12961 this.installFlags = installFlags; 12962 this.installerPackageName = installerPackageName; 12963 this.volumeUuid = volumeUuid; 12964 this.verificationInfo = verificationInfo; 12965 this.packageAbiOverride = packageAbiOverride; 12966 this.grantedRuntimePermissions = grantedPermissions; 12967 this.certificates = certificates; 12968 } 12969 12970 @Override 12971 public String toString() { 12972 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12973 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12974 } 12975 12976 private int installLocationPolicy(PackageInfoLite pkgLite) { 12977 String packageName = pkgLite.packageName; 12978 int installLocation = pkgLite.installLocation; 12979 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12980 // reader 12981 synchronized (mPackages) { 12982 // Currently installed package which the new package is attempting to replace or 12983 // null if no such package is installed. 12984 PackageParser.Package installedPkg = mPackages.get(packageName); 12985 // Package which currently owns the data which the new package will own if installed. 12986 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12987 // will be null whereas dataOwnerPkg will contain information about the package 12988 // which was uninstalled while keeping its data. 12989 PackageParser.Package dataOwnerPkg = installedPkg; 12990 if (dataOwnerPkg == null) { 12991 PackageSetting ps = mSettings.mPackages.get(packageName); 12992 if (ps != null) { 12993 dataOwnerPkg = ps.pkg; 12994 } 12995 } 12996 12997 if (dataOwnerPkg != null) { 12998 // If installed, the package will get access to data left on the device by its 12999 // predecessor. As a security measure, this is permited only if this is not a 13000 // version downgrade or if the predecessor package is marked as debuggable and 13001 // a downgrade is explicitly requested. 13002 // 13003 // On debuggable platform builds, downgrades are permitted even for 13004 // non-debuggable packages to make testing easier. Debuggable platform builds do 13005 // not offer security guarantees and thus it's OK to disable some security 13006 // mechanisms to make debugging/testing easier on those builds. However, even on 13007 // debuggable builds downgrades of packages are permitted only if requested via 13008 // installFlags. This is because we aim to keep the behavior of debuggable 13009 // platform builds as close as possible to the behavior of non-debuggable 13010 // platform builds. 13011 final boolean downgradeRequested = 13012 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 13013 final boolean packageDebuggable = 13014 (dataOwnerPkg.applicationInfo.flags 13015 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 13016 final boolean downgradePermitted = 13017 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 13018 if (!downgradePermitted) { 13019 try { 13020 checkDowngrade(dataOwnerPkg, pkgLite); 13021 } catch (PackageManagerException e) { 13022 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 13023 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 13024 } 13025 } 13026 } 13027 13028 if (installedPkg != null) { 13029 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13030 // Check for updated system application. 13031 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13032 if (onSd) { 13033 Slog.w(TAG, "Cannot install update to system app on sdcard"); 13034 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 13035 } 13036 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13037 } else { 13038 if (onSd) { 13039 // Install flag overrides everything. 13040 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13041 } 13042 // If current upgrade specifies particular preference 13043 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 13044 // Application explicitly specified internal. 13045 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13046 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 13047 // App explictly prefers external. Let policy decide 13048 } else { 13049 // Prefer previous location 13050 if (isExternal(installedPkg)) { 13051 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13052 } 13053 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13054 } 13055 } 13056 } else { 13057 // Invalid install. Return error code 13058 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 13059 } 13060 } 13061 } 13062 // All the special cases have been taken care of. 13063 // Return result based on recommended install location. 13064 if (onSd) { 13065 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13066 } 13067 return pkgLite.recommendedInstallLocation; 13068 } 13069 13070 /* 13071 * Invoke remote method to get package information and install 13072 * location values. Override install location based on default 13073 * policy if needed and then create install arguments based 13074 * on the install location. 13075 */ 13076 public void handleStartCopy() throws RemoteException { 13077 int ret = PackageManager.INSTALL_SUCCEEDED; 13078 13079 // If we're already staged, we've firmly committed to an install location 13080 if (origin.staged) { 13081 if (origin.file != null) { 13082 installFlags |= PackageManager.INSTALL_INTERNAL; 13083 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13084 } else if (origin.cid != null) { 13085 installFlags |= PackageManager.INSTALL_EXTERNAL; 13086 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13087 } else { 13088 throw new IllegalStateException("Invalid stage location"); 13089 } 13090 } 13091 13092 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13093 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 13094 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13095 PackageInfoLite pkgLite = null; 13096 13097 if (onInt && onSd) { 13098 // Check if both bits are set. 13099 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 13100 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13101 } else if (onSd && ephemeral) { 13102 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 13103 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13104 } else { 13105 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 13106 packageAbiOverride); 13107 13108 if (DEBUG_EPHEMERAL && ephemeral) { 13109 Slog.v(TAG, "pkgLite for install: " + pkgLite); 13110 } 13111 13112 /* 13113 * If we have too little free space, try to free cache 13114 * before giving up. 13115 */ 13116 if (!origin.staged && pkgLite.recommendedInstallLocation 13117 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13118 // TODO: focus freeing disk space on the target device 13119 final StorageManager storage = StorageManager.from(mContext); 13120 final long lowThreshold = storage.getStorageLowBytes( 13121 Environment.getDataDirectory()); 13122 13123 final long sizeBytes = mContainerService.calculateInstalledSize( 13124 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 13125 13126 try { 13127 mInstaller.freeCache(null, sizeBytes + lowThreshold); 13128 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 13129 installFlags, packageAbiOverride); 13130 } catch (InstallerException e) { 13131 Slog.w(TAG, "Failed to free cache", e); 13132 } 13133 13134 /* 13135 * The cache free must have deleted the file we 13136 * downloaded to install. 13137 * 13138 * TODO: fix the "freeCache" call to not delete 13139 * the file we care about. 13140 */ 13141 if (pkgLite.recommendedInstallLocation 13142 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13143 pkgLite.recommendedInstallLocation 13144 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 13145 } 13146 } 13147 } 13148 13149 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13150 int loc = pkgLite.recommendedInstallLocation; 13151 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13152 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13153 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13154 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13155 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13156 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13157 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13158 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13159 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13160 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13161 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13162 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13163 } else { 13164 // Override with defaults if needed. 13165 loc = installLocationPolicy(pkgLite); 13166 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13167 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13168 } else if (!onSd && !onInt) { 13169 // Override install location with flags 13170 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13171 // Set the flag to install on external media. 13172 installFlags |= PackageManager.INSTALL_EXTERNAL; 13173 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13174 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13175 if (DEBUG_EPHEMERAL) { 13176 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13177 } 13178 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13179 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13180 |PackageManager.INSTALL_INTERNAL); 13181 } else { 13182 // Make sure the flag for installing on external 13183 // media is unset 13184 installFlags |= PackageManager.INSTALL_INTERNAL; 13185 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13186 } 13187 } 13188 } 13189 } 13190 13191 final InstallArgs args = createInstallArgs(this); 13192 mArgs = args; 13193 13194 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13195 // TODO: http://b/22976637 13196 // Apps installed for "all" users use the device owner to verify the app 13197 UserHandle verifierUser = getUser(); 13198 if (verifierUser == UserHandle.ALL) { 13199 verifierUser = UserHandle.SYSTEM; 13200 } 13201 13202 /* 13203 * Determine if we have any installed package verifiers. If we 13204 * do, then we'll defer to them to verify the packages. 13205 */ 13206 final int requiredUid = mRequiredVerifierPackage == null ? -1 13207 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13208 verifierUser.getIdentifier()); 13209 if (!origin.existing && requiredUid != -1 13210 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13211 final Intent verification = new Intent( 13212 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13213 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13214 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13215 PACKAGE_MIME_TYPE); 13216 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13217 13218 // Query all live verifiers based on current user state 13219 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13220 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13221 13222 if (DEBUG_VERIFY) { 13223 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13224 + verification.toString() + " with " + pkgLite.verifiers.length 13225 + " optional verifiers"); 13226 } 13227 13228 final int verificationId = mPendingVerificationToken++; 13229 13230 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13231 13232 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13233 installerPackageName); 13234 13235 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13236 installFlags); 13237 13238 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13239 pkgLite.packageName); 13240 13241 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13242 pkgLite.versionCode); 13243 13244 if (verificationInfo != null) { 13245 if (verificationInfo.originatingUri != null) { 13246 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13247 verificationInfo.originatingUri); 13248 } 13249 if (verificationInfo.referrer != null) { 13250 verification.putExtra(Intent.EXTRA_REFERRER, 13251 verificationInfo.referrer); 13252 } 13253 if (verificationInfo.originatingUid >= 0) { 13254 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13255 verificationInfo.originatingUid); 13256 } 13257 if (verificationInfo.installerUid >= 0) { 13258 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13259 verificationInfo.installerUid); 13260 } 13261 } 13262 13263 final PackageVerificationState verificationState = new PackageVerificationState( 13264 requiredUid, args); 13265 13266 mPendingVerification.append(verificationId, verificationState); 13267 13268 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13269 receivers, verificationState); 13270 13271 /* 13272 * If any sufficient verifiers were listed in the package 13273 * manifest, attempt to ask them. 13274 */ 13275 if (sufficientVerifiers != null) { 13276 final int N = sufficientVerifiers.size(); 13277 if (N == 0) { 13278 Slog.i(TAG, "Additional verifiers required, but none installed."); 13279 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13280 } else { 13281 for (int i = 0; i < N; i++) { 13282 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13283 13284 final Intent sufficientIntent = new Intent(verification); 13285 sufficientIntent.setComponent(verifierComponent); 13286 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13287 } 13288 } 13289 } 13290 13291 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13292 mRequiredVerifierPackage, receivers); 13293 if (ret == PackageManager.INSTALL_SUCCEEDED 13294 && mRequiredVerifierPackage != null) { 13295 Trace.asyncTraceBegin( 13296 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13297 /* 13298 * Send the intent to the required verification agent, 13299 * but only start the verification timeout after the 13300 * target BroadcastReceivers have run. 13301 */ 13302 verification.setComponent(requiredVerifierComponent); 13303 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13304 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13305 new BroadcastReceiver() { 13306 @Override 13307 public void onReceive(Context context, Intent intent) { 13308 final Message msg = mHandler 13309 .obtainMessage(CHECK_PENDING_VERIFICATION); 13310 msg.arg1 = verificationId; 13311 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13312 } 13313 }, null, 0, null, null); 13314 13315 /* 13316 * We don't want the copy to proceed until verification 13317 * succeeds, so null out this field. 13318 */ 13319 mArgs = null; 13320 } 13321 } else { 13322 /* 13323 * No package verification is enabled, so immediately start 13324 * the remote call to initiate copy using temporary file. 13325 */ 13326 ret = args.copyApk(mContainerService, true); 13327 } 13328 } 13329 13330 mRet = ret; 13331 } 13332 13333 @Override 13334 void handleReturnCode() { 13335 // If mArgs is null, then MCS couldn't be reached. When it 13336 // reconnects, it will try again to install. At that point, this 13337 // will succeed. 13338 if (mArgs != null) { 13339 processPendingInstall(mArgs, mRet); 13340 } 13341 } 13342 13343 @Override 13344 void handleServiceError() { 13345 mArgs = createInstallArgs(this); 13346 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13347 } 13348 13349 public boolean isForwardLocked() { 13350 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13351 } 13352 } 13353 13354 /** 13355 * Used during creation of InstallArgs 13356 * 13357 * @param installFlags package installation flags 13358 * @return true if should be installed on external storage 13359 */ 13360 private static boolean installOnExternalAsec(int installFlags) { 13361 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13362 return false; 13363 } 13364 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13365 return true; 13366 } 13367 return false; 13368 } 13369 13370 /** 13371 * Used during creation of InstallArgs 13372 * 13373 * @param installFlags package installation flags 13374 * @return true if should be installed as forward locked 13375 */ 13376 private static boolean installForwardLocked(int installFlags) { 13377 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13378 } 13379 13380 private InstallArgs createInstallArgs(InstallParams params) { 13381 if (params.move != null) { 13382 return new MoveInstallArgs(params); 13383 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13384 return new AsecInstallArgs(params); 13385 } else { 13386 return new FileInstallArgs(params); 13387 } 13388 } 13389 13390 /** 13391 * Create args that describe an existing installed package. Typically used 13392 * when cleaning up old installs, or used as a move source. 13393 */ 13394 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13395 String resourcePath, String[] instructionSets) { 13396 final boolean isInAsec; 13397 if (installOnExternalAsec(installFlags)) { 13398 /* Apps on SD card are always in ASEC containers. */ 13399 isInAsec = true; 13400 } else if (installForwardLocked(installFlags) 13401 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13402 /* 13403 * Forward-locked apps are only in ASEC containers if they're the 13404 * new style 13405 */ 13406 isInAsec = true; 13407 } else { 13408 isInAsec = false; 13409 } 13410 13411 if (isInAsec) { 13412 return new AsecInstallArgs(codePath, instructionSets, 13413 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13414 } else { 13415 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13416 } 13417 } 13418 13419 static abstract class InstallArgs { 13420 /** @see InstallParams#origin */ 13421 final OriginInfo origin; 13422 /** @see InstallParams#move */ 13423 final MoveInfo move; 13424 13425 final IPackageInstallObserver2 observer; 13426 // Always refers to PackageManager flags only 13427 final int installFlags; 13428 final String installerPackageName; 13429 final String volumeUuid; 13430 final UserHandle user; 13431 final String abiOverride; 13432 final String[] installGrantPermissions; 13433 /** If non-null, drop an async trace when the install completes */ 13434 final String traceMethod; 13435 final int traceCookie; 13436 final Certificate[][] certificates; 13437 13438 // The list of instruction sets supported by this app. This is currently 13439 // only used during the rmdex() phase to clean up resources. We can get rid of this 13440 // if we move dex files under the common app path. 13441 /* nullable */ String[] instructionSets; 13442 13443 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13444 int installFlags, String installerPackageName, String volumeUuid, 13445 UserHandle user, String[] instructionSets, 13446 String abiOverride, String[] installGrantPermissions, 13447 String traceMethod, int traceCookie, Certificate[][] certificates) { 13448 this.origin = origin; 13449 this.move = move; 13450 this.installFlags = installFlags; 13451 this.observer = observer; 13452 this.installerPackageName = installerPackageName; 13453 this.volumeUuid = volumeUuid; 13454 this.user = user; 13455 this.instructionSets = instructionSets; 13456 this.abiOverride = abiOverride; 13457 this.installGrantPermissions = installGrantPermissions; 13458 this.traceMethod = traceMethod; 13459 this.traceCookie = traceCookie; 13460 this.certificates = certificates; 13461 } 13462 13463 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13464 abstract int doPreInstall(int status); 13465 13466 /** 13467 * Rename package into final resting place. All paths on the given 13468 * scanned package should be updated to reflect the rename. 13469 */ 13470 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13471 abstract int doPostInstall(int status, int uid); 13472 13473 /** @see PackageSettingBase#codePathString */ 13474 abstract String getCodePath(); 13475 /** @see PackageSettingBase#resourcePathString */ 13476 abstract String getResourcePath(); 13477 13478 // Need installer lock especially for dex file removal. 13479 abstract void cleanUpResourcesLI(); 13480 abstract boolean doPostDeleteLI(boolean delete); 13481 13482 /** 13483 * Called before the source arguments are copied. This is used mostly 13484 * for MoveParams when it needs to read the source file to put it in the 13485 * destination. 13486 */ 13487 int doPreCopy() { 13488 return PackageManager.INSTALL_SUCCEEDED; 13489 } 13490 13491 /** 13492 * Called after the source arguments are copied. This is used mostly for 13493 * MoveParams when it needs to read the source file to put it in the 13494 * destination. 13495 */ 13496 int doPostCopy(int uid) { 13497 return PackageManager.INSTALL_SUCCEEDED; 13498 } 13499 13500 protected boolean isFwdLocked() { 13501 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13502 } 13503 13504 protected boolean isExternalAsec() { 13505 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13506 } 13507 13508 protected boolean isEphemeral() { 13509 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13510 } 13511 13512 UserHandle getUser() { 13513 return user; 13514 } 13515 } 13516 13517 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13518 if (!allCodePaths.isEmpty()) { 13519 if (instructionSets == null) { 13520 throw new IllegalStateException("instructionSet == null"); 13521 } 13522 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13523 for (String codePath : allCodePaths) { 13524 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13525 try { 13526 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13527 } catch (InstallerException ignored) { 13528 } 13529 } 13530 } 13531 } 13532 } 13533 13534 /** 13535 * Logic to handle installation of non-ASEC applications, including copying 13536 * and renaming logic. 13537 */ 13538 class FileInstallArgs extends InstallArgs { 13539 private File codeFile; 13540 private File resourceFile; 13541 13542 // Example topology: 13543 // /data/app/com.example/base.apk 13544 // /data/app/com.example/split_foo.apk 13545 // /data/app/com.example/lib/arm/libfoo.so 13546 // /data/app/com.example/lib/arm64/libfoo.so 13547 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13548 13549 /** New install */ 13550 FileInstallArgs(InstallParams params) { 13551 super(params.origin, params.move, params.observer, params.installFlags, 13552 params.installerPackageName, params.volumeUuid, 13553 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13554 params.grantedRuntimePermissions, 13555 params.traceMethod, params.traceCookie, params.certificates); 13556 if (isFwdLocked()) { 13557 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13558 } 13559 } 13560 13561 /** Existing install */ 13562 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13563 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13564 null, null, null, 0, null /*certificates*/); 13565 this.codeFile = (codePath != null) ? new File(codePath) : null; 13566 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13567 } 13568 13569 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13570 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13571 try { 13572 return doCopyApk(imcs, temp); 13573 } finally { 13574 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13575 } 13576 } 13577 13578 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13579 if (origin.staged) { 13580 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13581 codeFile = origin.file; 13582 resourceFile = origin.file; 13583 return PackageManager.INSTALL_SUCCEEDED; 13584 } 13585 13586 try { 13587 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13588 final File tempDir = 13589 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13590 codeFile = tempDir; 13591 resourceFile = tempDir; 13592 } catch (IOException e) { 13593 Slog.w(TAG, "Failed to create copy file: " + e); 13594 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13595 } 13596 13597 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13598 @Override 13599 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13600 if (!FileUtils.isValidExtFilename(name)) { 13601 throw new IllegalArgumentException("Invalid filename: " + name); 13602 } 13603 try { 13604 final File file = new File(codeFile, name); 13605 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13606 O_RDWR | O_CREAT, 0644); 13607 Os.chmod(file.getAbsolutePath(), 0644); 13608 return new ParcelFileDescriptor(fd); 13609 } catch (ErrnoException e) { 13610 throw new RemoteException("Failed to open: " + e.getMessage()); 13611 } 13612 } 13613 }; 13614 13615 int ret = PackageManager.INSTALL_SUCCEEDED; 13616 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13617 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13618 Slog.e(TAG, "Failed to copy package"); 13619 return ret; 13620 } 13621 13622 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13623 NativeLibraryHelper.Handle handle = null; 13624 try { 13625 handle = NativeLibraryHelper.Handle.create(codeFile); 13626 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13627 abiOverride); 13628 } catch (IOException e) { 13629 Slog.e(TAG, "Copying native libraries failed", e); 13630 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13631 } finally { 13632 IoUtils.closeQuietly(handle); 13633 } 13634 13635 return ret; 13636 } 13637 13638 int doPreInstall(int status) { 13639 if (status != PackageManager.INSTALL_SUCCEEDED) { 13640 cleanUp(); 13641 } 13642 return status; 13643 } 13644 13645 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13646 if (status != PackageManager.INSTALL_SUCCEEDED) { 13647 cleanUp(); 13648 return false; 13649 } 13650 13651 final File targetDir = codeFile.getParentFile(); 13652 final File beforeCodeFile = codeFile; 13653 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13654 13655 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13656 try { 13657 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13658 } catch (ErrnoException e) { 13659 Slog.w(TAG, "Failed to rename", e); 13660 return false; 13661 } 13662 13663 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13664 Slog.w(TAG, "Failed to restorecon"); 13665 return false; 13666 } 13667 13668 // Reflect the rename internally 13669 codeFile = afterCodeFile; 13670 resourceFile = afterCodeFile; 13671 13672 // Reflect the rename in scanned details 13673 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13674 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13675 afterCodeFile, pkg.baseCodePath)); 13676 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13677 afterCodeFile, pkg.splitCodePaths)); 13678 13679 // Reflect the rename in app info 13680 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13681 pkg.setApplicationInfoCodePath(pkg.codePath); 13682 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13683 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13684 pkg.setApplicationInfoResourcePath(pkg.codePath); 13685 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13686 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13687 13688 return true; 13689 } 13690 13691 int doPostInstall(int status, int uid) { 13692 if (status != PackageManager.INSTALL_SUCCEEDED) { 13693 cleanUp(); 13694 } 13695 return status; 13696 } 13697 13698 @Override 13699 String getCodePath() { 13700 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13701 } 13702 13703 @Override 13704 String getResourcePath() { 13705 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13706 } 13707 13708 private boolean cleanUp() { 13709 if (codeFile == null || !codeFile.exists()) { 13710 return false; 13711 } 13712 13713 removeCodePathLI(codeFile); 13714 13715 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13716 resourceFile.delete(); 13717 } 13718 13719 return true; 13720 } 13721 13722 void cleanUpResourcesLI() { 13723 // Try enumerating all code paths before deleting 13724 List<String> allCodePaths = Collections.EMPTY_LIST; 13725 if (codeFile != null && codeFile.exists()) { 13726 try { 13727 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13728 allCodePaths = pkg.getAllCodePaths(); 13729 } catch (PackageParserException e) { 13730 // Ignored; we tried our best 13731 } 13732 } 13733 13734 cleanUp(); 13735 removeDexFiles(allCodePaths, instructionSets); 13736 } 13737 13738 boolean doPostDeleteLI(boolean delete) { 13739 // XXX err, shouldn't we respect the delete flag? 13740 cleanUpResourcesLI(); 13741 return true; 13742 } 13743 } 13744 13745 private boolean isAsecExternal(String cid) { 13746 final String asecPath = PackageHelper.getSdFilesystem(cid); 13747 return !asecPath.startsWith(mAsecInternalPath); 13748 } 13749 13750 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13751 PackageManagerException { 13752 if (copyRet < 0) { 13753 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13754 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13755 throw new PackageManagerException(copyRet, message); 13756 } 13757 } 13758 } 13759 13760 /** 13761 * Extract the MountService "container ID" from the full code path of an 13762 * .apk. 13763 */ 13764 static String cidFromCodePath(String fullCodePath) { 13765 int eidx = fullCodePath.lastIndexOf("/"); 13766 String subStr1 = fullCodePath.substring(0, eidx); 13767 int sidx = subStr1.lastIndexOf("/"); 13768 return subStr1.substring(sidx+1, eidx); 13769 } 13770 13771 /** 13772 * Logic to handle installation of ASEC applications, including copying and 13773 * renaming logic. 13774 */ 13775 class AsecInstallArgs extends InstallArgs { 13776 static final String RES_FILE_NAME = "pkg.apk"; 13777 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13778 13779 String cid; 13780 String packagePath; 13781 String resourcePath; 13782 13783 /** New install */ 13784 AsecInstallArgs(InstallParams params) { 13785 super(params.origin, params.move, params.observer, params.installFlags, 13786 params.installerPackageName, params.volumeUuid, 13787 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13788 params.grantedRuntimePermissions, 13789 params.traceMethod, params.traceCookie, params.certificates); 13790 } 13791 13792 /** Existing install */ 13793 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13794 boolean isExternal, boolean isForwardLocked) { 13795 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13796 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13797 instructionSets, null, null, null, 0, null /*certificates*/); 13798 // Hackily pretend we're still looking at a full code path 13799 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13800 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13801 } 13802 13803 // Extract cid from fullCodePath 13804 int eidx = fullCodePath.lastIndexOf("/"); 13805 String subStr1 = fullCodePath.substring(0, eidx); 13806 int sidx = subStr1.lastIndexOf("/"); 13807 cid = subStr1.substring(sidx+1, eidx); 13808 setMountPath(subStr1); 13809 } 13810 13811 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13812 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13813 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13814 instructionSets, null, null, null, 0, null /*certificates*/); 13815 this.cid = cid; 13816 setMountPath(PackageHelper.getSdDir(cid)); 13817 } 13818 13819 void createCopyFile() { 13820 cid = mInstallerService.allocateExternalStageCidLegacy(); 13821 } 13822 13823 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13824 if (origin.staged && origin.cid != null) { 13825 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13826 cid = origin.cid; 13827 setMountPath(PackageHelper.getSdDir(cid)); 13828 return PackageManager.INSTALL_SUCCEEDED; 13829 } 13830 13831 if (temp) { 13832 createCopyFile(); 13833 } else { 13834 /* 13835 * Pre-emptively destroy the container since it's destroyed if 13836 * copying fails due to it existing anyway. 13837 */ 13838 PackageHelper.destroySdDir(cid); 13839 } 13840 13841 final String newMountPath = imcs.copyPackageToContainer( 13842 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13843 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13844 13845 if (newMountPath != null) { 13846 setMountPath(newMountPath); 13847 return PackageManager.INSTALL_SUCCEEDED; 13848 } else { 13849 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13850 } 13851 } 13852 13853 @Override 13854 String getCodePath() { 13855 return packagePath; 13856 } 13857 13858 @Override 13859 String getResourcePath() { 13860 return resourcePath; 13861 } 13862 13863 int doPreInstall(int status) { 13864 if (status != PackageManager.INSTALL_SUCCEEDED) { 13865 // Destroy container 13866 PackageHelper.destroySdDir(cid); 13867 } else { 13868 boolean mounted = PackageHelper.isContainerMounted(cid); 13869 if (!mounted) { 13870 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13871 Process.SYSTEM_UID); 13872 if (newMountPath != null) { 13873 setMountPath(newMountPath); 13874 } else { 13875 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13876 } 13877 } 13878 } 13879 return status; 13880 } 13881 13882 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13883 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13884 String newMountPath = null; 13885 if (PackageHelper.isContainerMounted(cid)) { 13886 // Unmount the container 13887 if (!PackageHelper.unMountSdDir(cid)) { 13888 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13889 return false; 13890 } 13891 } 13892 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13893 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13894 " which might be stale. Will try to clean up."); 13895 // Clean up the stale container and proceed to recreate. 13896 if (!PackageHelper.destroySdDir(newCacheId)) { 13897 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13898 return false; 13899 } 13900 // Successfully cleaned up stale container. Try to rename again. 13901 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13902 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13903 + " inspite of cleaning it up."); 13904 return false; 13905 } 13906 } 13907 if (!PackageHelper.isContainerMounted(newCacheId)) { 13908 Slog.w(TAG, "Mounting container " + newCacheId); 13909 newMountPath = PackageHelper.mountSdDir(newCacheId, 13910 getEncryptKey(), Process.SYSTEM_UID); 13911 } else { 13912 newMountPath = PackageHelper.getSdDir(newCacheId); 13913 } 13914 if (newMountPath == null) { 13915 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13916 return false; 13917 } 13918 Log.i(TAG, "Succesfully renamed " + cid + 13919 " to " + newCacheId + 13920 " at new path: " + newMountPath); 13921 cid = newCacheId; 13922 13923 final File beforeCodeFile = new File(packagePath); 13924 setMountPath(newMountPath); 13925 final File afterCodeFile = new File(packagePath); 13926 13927 // Reflect the rename in scanned details 13928 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13929 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13930 afterCodeFile, pkg.baseCodePath)); 13931 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13932 afterCodeFile, pkg.splitCodePaths)); 13933 13934 // Reflect the rename in app info 13935 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13936 pkg.setApplicationInfoCodePath(pkg.codePath); 13937 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13938 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13939 pkg.setApplicationInfoResourcePath(pkg.codePath); 13940 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13941 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13942 13943 return true; 13944 } 13945 13946 private void setMountPath(String mountPath) { 13947 final File mountFile = new File(mountPath); 13948 13949 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13950 if (monolithicFile.exists()) { 13951 packagePath = monolithicFile.getAbsolutePath(); 13952 if (isFwdLocked()) { 13953 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13954 } else { 13955 resourcePath = packagePath; 13956 } 13957 } else { 13958 packagePath = mountFile.getAbsolutePath(); 13959 resourcePath = packagePath; 13960 } 13961 } 13962 13963 int doPostInstall(int status, int uid) { 13964 if (status != PackageManager.INSTALL_SUCCEEDED) { 13965 cleanUp(); 13966 } else { 13967 final int groupOwner; 13968 final String protectedFile; 13969 if (isFwdLocked()) { 13970 groupOwner = UserHandle.getSharedAppGid(uid); 13971 protectedFile = RES_FILE_NAME; 13972 } else { 13973 groupOwner = -1; 13974 protectedFile = null; 13975 } 13976 13977 if (uid < Process.FIRST_APPLICATION_UID 13978 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13979 Slog.e(TAG, "Failed to finalize " + cid); 13980 PackageHelper.destroySdDir(cid); 13981 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13982 } 13983 13984 boolean mounted = PackageHelper.isContainerMounted(cid); 13985 if (!mounted) { 13986 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13987 } 13988 } 13989 return status; 13990 } 13991 13992 private void cleanUp() { 13993 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13994 13995 // Destroy secure container 13996 PackageHelper.destroySdDir(cid); 13997 } 13998 13999 private List<String> getAllCodePaths() { 14000 final File codeFile = new File(getCodePath()); 14001 if (codeFile != null && codeFile.exists()) { 14002 try { 14003 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14004 return pkg.getAllCodePaths(); 14005 } catch (PackageParserException e) { 14006 // Ignored; we tried our best 14007 } 14008 } 14009 return Collections.EMPTY_LIST; 14010 } 14011 14012 void cleanUpResourcesLI() { 14013 // Enumerate all code paths before deleting 14014 cleanUpResourcesLI(getAllCodePaths()); 14015 } 14016 14017 private void cleanUpResourcesLI(List<String> allCodePaths) { 14018 cleanUp(); 14019 removeDexFiles(allCodePaths, instructionSets); 14020 } 14021 14022 String getPackageName() { 14023 return getAsecPackageName(cid); 14024 } 14025 14026 boolean doPostDeleteLI(boolean delete) { 14027 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 14028 final List<String> allCodePaths = getAllCodePaths(); 14029 boolean mounted = PackageHelper.isContainerMounted(cid); 14030 if (mounted) { 14031 // Unmount first 14032 if (PackageHelper.unMountSdDir(cid)) { 14033 mounted = false; 14034 } 14035 } 14036 if (!mounted && delete) { 14037 cleanUpResourcesLI(allCodePaths); 14038 } 14039 return !mounted; 14040 } 14041 14042 @Override 14043 int doPreCopy() { 14044 if (isFwdLocked()) { 14045 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 14046 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 14047 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14048 } 14049 } 14050 14051 return PackageManager.INSTALL_SUCCEEDED; 14052 } 14053 14054 @Override 14055 int doPostCopy(int uid) { 14056 if (isFwdLocked()) { 14057 if (uid < Process.FIRST_APPLICATION_UID 14058 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 14059 RES_FILE_NAME)) { 14060 Slog.e(TAG, "Failed to finalize " + cid); 14061 PackageHelper.destroySdDir(cid); 14062 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14063 } 14064 } 14065 14066 return PackageManager.INSTALL_SUCCEEDED; 14067 } 14068 } 14069 14070 /** 14071 * Logic to handle movement of existing installed applications. 14072 */ 14073 class MoveInstallArgs extends InstallArgs { 14074 private File codeFile; 14075 private File resourceFile; 14076 14077 /** New install */ 14078 MoveInstallArgs(InstallParams params) { 14079 super(params.origin, params.move, params.observer, params.installFlags, 14080 params.installerPackageName, params.volumeUuid, 14081 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14082 params.grantedRuntimePermissions, 14083 params.traceMethod, params.traceCookie, params.certificates); 14084 } 14085 14086 int copyApk(IMediaContainerService imcs, boolean temp) { 14087 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 14088 + move.fromUuid + " to " + move.toUuid); 14089 synchronized (mInstaller) { 14090 try { 14091 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 14092 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 14093 } catch (InstallerException e) { 14094 Slog.w(TAG, "Failed to move app", e); 14095 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14096 } 14097 } 14098 14099 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 14100 resourceFile = codeFile; 14101 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 14102 14103 return PackageManager.INSTALL_SUCCEEDED; 14104 } 14105 14106 int doPreInstall(int status) { 14107 if (status != PackageManager.INSTALL_SUCCEEDED) { 14108 cleanUp(move.toUuid); 14109 } 14110 return status; 14111 } 14112 14113 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14114 if (status != PackageManager.INSTALL_SUCCEEDED) { 14115 cleanUp(move.toUuid); 14116 return false; 14117 } 14118 14119 // Reflect the move in app info 14120 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14121 pkg.setApplicationInfoCodePath(pkg.codePath); 14122 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14123 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14124 pkg.setApplicationInfoResourcePath(pkg.codePath); 14125 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14126 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14127 14128 return true; 14129 } 14130 14131 int doPostInstall(int status, int uid) { 14132 if (status == PackageManager.INSTALL_SUCCEEDED) { 14133 cleanUp(move.fromUuid); 14134 } else { 14135 cleanUp(move.toUuid); 14136 } 14137 return status; 14138 } 14139 14140 @Override 14141 String getCodePath() { 14142 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14143 } 14144 14145 @Override 14146 String getResourcePath() { 14147 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14148 } 14149 14150 private boolean cleanUp(String volumeUuid) { 14151 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14152 move.dataAppName); 14153 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14154 final int[] userIds = sUserManager.getUserIds(); 14155 synchronized (mInstallLock) { 14156 // Clean up both app data and code 14157 // All package moves are frozen until finished 14158 for (int userId : userIds) { 14159 try { 14160 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14161 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14162 } catch (InstallerException e) { 14163 Slog.w(TAG, String.valueOf(e)); 14164 } 14165 } 14166 removeCodePathLI(codeFile); 14167 } 14168 return true; 14169 } 14170 14171 void cleanUpResourcesLI() { 14172 throw new UnsupportedOperationException(); 14173 } 14174 14175 boolean doPostDeleteLI(boolean delete) { 14176 throw new UnsupportedOperationException(); 14177 } 14178 } 14179 14180 static String getAsecPackageName(String packageCid) { 14181 int idx = packageCid.lastIndexOf("-"); 14182 if (idx == -1) { 14183 return packageCid; 14184 } 14185 return packageCid.substring(0, idx); 14186 } 14187 14188 // Utility method used to create code paths based on package name and available index. 14189 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14190 String idxStr = ""; 14191 int idx = 1; 14192 // Fall back to default value of idx=1 if prefix is not 14193 // part of oldCodePath 14194 if (oldCodePath != null) { 14195 String subStr = oldCodePath; 14196 // Drop the suffix right away 14197 if (suffix != null && subStr.endsWith(suffix)) { 14198 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14199 } 14200 // If oldCodePath already contains prefix find out the 14201 // ending index to either increment or decrement. 14202 int sidx = subStr.lastIndexOf(prefix); 14203 if (sidx != -1) { 14204 subStr = subStr.substring(sidx + prefix.length()); 14205 if (subStr != null) { 14206 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14207 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14208 } 14209 try { 14210 idx = Integer.parseInt(subStr); 14211 if (idx <= 1) { 14212 idx++; 14213 } else { 14214 idx--; 14215 } 14216 } catch(NumberFormatException e) { 14217 } 14218 } 14219 } 14220 } 14221 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14222 return prefix + idxStr; 14223 } 14224 14225 private File getNextCodePath(File targetDir, String packageName) { 14226 int suffix = 1; 14227 File result; 14228 do { 14229 result = new File(targetDir, packageName + "-" + suffix); 14230 suffix++; 14231 } while (result.exists()); 14232 return result; 14233 } 14234 14235 // Utility method that returns the relative package path with respect 14236 // to the installation directory. Like say for /data/data/com.test-1.apk 14237 // string com.test-1 is returned. 14238 static String deriveCodePathName(String codePath) { 14239 if (codePath == null) { 14240 return null; 14241 } 14242 final File codeFile = new File(codePath); 14243 final String name = codeFile.getName(); 14244 if (codeFile.isDirectory()) { 14245 return name; 14246 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14247 final int lastDot = name.lastIndexOf('.'); 14248 return name.substring(0, lastDot); 14249 } else { 14250 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14251 return null; 14252 } 14253 } 14254 14255 static class PackageInstalledInfo { 14256 String name; 14257 int uid; 14258 // The set of users that originally had this package installed. 14259 int[] origUsers; 14260 // The set of users that now have this package installed. 14261 int[] newUsers; 14262 PackageParser.Package pkg; 14263 int returnCode; 14264 String returnMsg; 14265 PackageRemovedInfo removedInfo; 14266 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14267 14268 public void setError(int code, String msg) { 14269 setReturnCode(code); 14270 setReturnMessage(msg); 14271 Slog.w(TAG, msg); 14272 } 14273 14274 public void setError(String msg, PackageParserException e) { 14275 setReturnCode(e.error); 14276 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14277 Slog.w(TAG, msg, e); 14278 } 14279 14280 public void setError(String msg, PackageManagerException e) { 14281 returnCode = e.error; 14282 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14283 Slog.w(TAG, msg, e); 14284 } 14285 14286 public void setReturnCode(int returnCode) { 14287 this.returnCode = returnCode; 14288 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14289 for (int i = 0; i < childCount; i++) { 14290 addedChildPackages.valueAt(i).returnCode = returnCode; 14291 } 14292 } 14293 14294 private void setReturnMessage(String returnMsg) { 14295 this.returnMsg = returnMsg; 14296 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14297 for (int i = 0; i < childCount; i++) { 14298 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14299 } 14300 } 14301 14302 // In some error cases we want to convey more info back to the observer 14303 String origPackage; 14304 String origPermission; 14305 } 14306 14307 /* 14308 * Install a non-existing package. 14309 */ 14310 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14311 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14312 PackageInstalledInfo res) { 14313 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14314 14315 // Remember this for later, in case we need to rollback this install 14316 String pkgName = pkg.packageName; 14317 14318 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14319 14320 synchronized(mPackages) { 14321 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 14322 if (renamedPackage != null) { 14323 // A package with the same name is already installed, though 14324 // it has been renamed to an older name. The package we 14325 // are trying to install should be installed as an update to 14326 // the existing one, but that has not been requested, so bail. 14327 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14328 + " without first uninstalling package running as " 14329 + renamedPackage); 14330 return; 14331 } 14332 if (mPackages.containsKey(pkgName)) { 14333 // Don't allow installation over an existing package with the same name. 14334 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14335 + " without first uninstalling."); 14336 return; 14337 } 14338 } 14339 14340 try { 14341 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14342 System.currentTimeMillis(), user); 14343 14344 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14345 14346 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14347 prepareAppDataAfterInstallLIF(newPackage); 14348 14349 } else { 14350 // Remove package from internal structures, but keep around any 14351 // data that might have already existed 14352 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14353 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14354 } 14355 } catch (PackageManagerException e) { 14356 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14357 } 14358 14359 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14360 } 14361 14362 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14363 // Can't rotate keys during boot or if sharedUser. 14364 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14365 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14366 return false; 14367 } 14368 // app is using upgradeKeySets; make sure all are valid 14369 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14370 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14371 for (int i = 0; i < upgradeKeySets.length; i++) { 14372 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14373 Slog.wtf(TAG, "Package " 14374 + (oldPs.name != null ? oldPs.name : "<null>") 14375 + " contains upgrade-key-set reference to unknown key-set: " 14376 + upgradeKeySets[i] 14377 + " reverting to signatures check."); 14378 return false; 14379 } 14380 } 14381 return true; 14382 } 14383 14384 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14385 // Upgrade keysets are being used. Determine if new package has a superset of the 14386 // required keys. 14387 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14388 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14389 for (int i = 0; i < upgradeKeySets.length; i++) { 14390 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14391 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14392 return true; 14393 } 14394 } 14395 return false; 14396 } 14397 14398 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14399 try (DigestInputStream digestStream = 14400 new DigestInputStream(new FileInputStream(file), digest)) { 14401 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14402 } 14403 } 14404 14405 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14406 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14407 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14408 14409 final PackageParser.Package oldPackage; 14410 final String pkgName = pkg.packageName; 14411 final int[] allUsers; 14412 final int[] installedUsers; 14413 14414 synchronized(mPackages) { 14415 oldPackage = mPackages.get(pkgName); 14416 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14417 14418 // don't allow upgrade to target a release SDK from a pre-release SDK 14419 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14420 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14421 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14422 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14423 if (oldTargetsPreRelease 14424 && !newTargetsPreRelease 14425 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14426 Slog.w(TAG, "Can't install package targeting released sdk"); 14427 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14428 return; 14429 } 14430 14431 // don't allow an upgrade from full to ephemeral 14432 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14433 if (isEphemeral && !oldIsEphemeral) { 14434 // can't downgrade from full to ephemeral 14435 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14436 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14437 return; 14438 } 14439 14440 // verify signatures are valid 14441 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14442 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14443 if (!checkUpgradeKeySetLP(ps, pkg)) { 14444 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14445 "New package not signed by keys specified by upgrade-keysets: " 14446 + pkgName); 14447 return; 14448 } 14449 } else { 14450 // default to original signature matching 14451 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14452 != PackageManager.SIGNATURE_MATCH) { 14453 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14454 "New package has a different signature: " + pkgName); 14455 return; 14456 } 14457 } 14458 14459 // don't allow a system upgrade unless the upgrade hash matches 14460 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14461 byte[] digestBytes = null; 14462 try { 14463 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14464 updateDigest(digest, new File(pkg.baseCodePath)); 14465 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14466 for (String path : pkg.splitCodePaths) { 14467 updateDigest(digest, new File(path)); 14468 } 14469 } 14470 digestBytes = digest.digest(); 14471 } catch (NoSuchAlgorithmException | IOException e) { 14472 res.setError(INSTALL_FAILED_INVALID_APK, 14473 "Could not compute hash: " + pkgName); 14474 return; 14475 } 14476 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14477 res.setError(INSTALL_FAILED_INVALID_APK, 14478 "New package fails restrict-update check: " + pkgName); 14479 return; 14480 } 14481 // retain upgrade restriction 14482 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14483 } 14484 14485 // Check for shared user id changes 14486 String invalidPackageName = 14487 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14488 if (invalidPackageName != null) { 14489 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14490 "Package " + invalidPackageName + " tried to change user " 14491 + oldPackage.mSharedUserId); 14492 return; 14493 } 14494 14495 // In case of rollback, remember per-user/profile install state 14496 allUsers = sUserManager.getUserIds(); 14497 installedUsers = ps.queryInstalledUsers(allUsers, true); 14498 } 14499 14500 // Update what is removed 14501 res.removedInfo = new PackageRemovedInfo(); 14502 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14503 res.removedInfo.removedPackage = oldPackage.packageName; 14504 res.removedInfo.isUpdate = true; 14505 res.removedInfo.origUsers = installedUsers; 14506 final int childCount = (oldPackage.childPackages != null) 14507 ? oldPackage.childPackages.size() : 0; 14508 for (int i = 0; i < childCount; i++) { 14509 boolean childPackageUpdated = false; 14510 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14511 if (res.addedChildPackages != null) { 14512 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14513 if (childRes != null) { 14514 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14515 childRes.removedInfo.removedPackage = childPkg.packageName; 14516 childRes.removedInfo.isUpdate = true; 14517 childPackageUpdated = true; 14518 } 14519 } 14520 if (!childPackageUpdated) { 14521 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14522 childRemovedRes.removedPackage = childPkg.packageName; 14523 childRemovedRes.isUpdate = false; 14524 childRemovedRes.dataRemoved = true; 14525 synchronized (mPackages) { 14526 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 14527 if (childPs != null) { 14528 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14529 } 14530 } 14531 if (res.removedInfo.removedChildPackages == null) { 14532 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14533 } 14534 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14535 } 14536 } 14537 14538 boolean sysPkg = (isSystemApp(oldPackage)); 14539 if (sysPkg) { 14540 // Set the system/privileged flags as needed 14541 final boolean privileged = 14542 (oldPackage.applicationInfo.privateFlags 14543 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14544 final int systemPolicyFlags = policyFlags 14545 | PackageParser.PARSE_IS_SYSTEM 14546 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14547 14548 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14549 user, allUsers, installerPackageName, res); 14550 } else { 14551 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14552 user, allUsers, installerPackageName, res); 14553 } 14554 } 14555 14556 public List<String> getPreviousCodePaths(String packageName) { 14557 final PackageSetting ps = mSettings.mPackages.get(packageName); 14558 final List<String> result = new ArrayList<String>(); 14559 if (ps != null && ps.oldCodePaths != null) { 14560 result.addAll(ps.oldCodePaths); 14561 } 14562 return result; 14563 } 14564 14565 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14566 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14567 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14568 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14569 + deletedPackage); 14570 14571 String pkgName = deletedPackage.packageName; 14572 boolean deletedPkg = true; 14573 boolean addedPkg = false; 14574 boolean updatedSettings = false; 14575 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14576 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14577 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14578 14579 final long origUpdateTime = (pkg.mExtras != null) 14580 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14581 14582 // First delete the existing package while retaining the data directory 14583 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14584 res.removedInfo, true, pkg)) { 14585 // If the existing package wasn't successfully deleted 14586 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14587 deletedPkg = false; 14588 } else { 14589 // Successfully deleted the old package; proceed with replace. 14590 14591 // If deleted package lived in a container, give users a chance to 14592 // relinquish resources before killing. 14593 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14594 if (DEBUG_INSTALL) { 14595 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14596 } 14597 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14598 final ArrayList<String> pkgList = new ArrayList<String>(1); 14599 pkgList.add(deletedPackage.applicationInfo.packageName); 14600 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14601 } 14602 14603 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14604 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14605 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14606 14607 try { 14608 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14609 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14610 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14611 14612 // Update the in-memory copy of the previous code paths. 14613 PackageSetting ps = mSettings.mPackages.get(pkgName); 14614 if (!killApp) { 14615 if (ps.oldCodePaths == null) { 14616 ps.oldCodePaths = new ArraySet<>(); 14617 } 14618 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14619 if (deletedPackage.splitCodePaths != null) { 14620 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14621 } 14622 } else { 14623 ps.oldCodePaths = null; 14624 } 14625 if (ps.childPackageNames != null) { 14626 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14627 final String childPkgName = ps.childPackageNames.get(i); 14628 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14629 childPs.oldCodePaths = ps.oldCodePaths; 14630 } 14631 } 14632 prepareAppDataAfterInstallLIF(newPackage); 14633 addedPkg = true; 14634 } catch (PackageManagerException e) { 14635 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14636 } 14637 } 14638 14639 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14640 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14641 14642 // Revert all internal state mutations and added folders for the failed install 14643 if (addedPkg) { 14644 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14645 res.removedInfo, true, null); 14646 } 14647 14648 // Restore the old package 14649 if (deletedPkg) { 14650 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14651 File restoreFile = new File(deletedPackage.codePath); 14652 // Parse old package 14653 boolean oldExternal = isExternal(deletedPackage); 14654 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14655 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14656 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14657 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14658 try { 14659 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14660 null); 14661 } catch (PackageManagerException e) { 14662 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14663 + e.getMessage()); 14664 return; 14665 } 14666 14667 synchronized (mPackages) { 14668 // Ensure the installer package name up to date 14669 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14670 14671 // Update permissions for restored package 14672 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14673 14674 mSettings.writeLPr(); 14675 } 14676 14677 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14678 } 14679 } else { 14680 synchronized (mPackages) { 14681 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 14682 if (ps != null) { 14683 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14684 if (res.removedInfo.removedChildPackages != null) { 14685 final int childCount = res.removedInfo.removedChildPackages.size(); 14686 // Iterate in reverse as we may modify the collection 14687 for (int i = childCount - 1; i >= 0; i--) { 14688 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14689 if (res.addedChildPackages.containsKey(childPackageName)) { 14690 res.removedInfo.removedChildPackages.removeAt(i); 14691 } else { 14692 PackageRemovedInfo childInfo = res.removedInfo 14693 .removedChildPackages.valueAt(i); 14694 childInfo.removedForAllUsers = mPackages.get( 14695 childInfo.removedPackage) == null; 14696 } 14697 } 14698 } 14699 } 14700 } 14701 } 14702 } 14703 14704 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14705 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14706 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14707 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14708 + ", old=" + deletedPackage); 14709 14710 final boolean disabledSystem; 14711 14712 // Remove existing system package 14713 removePackageLI(deletedPackage, true); 14714 14715 synchronized (mPackages) { 14716 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14717 } 14718 if (!disabledSystem) { 14719 // We didn't need to disable the .apk as a current system package, 14720 // which means we are replacing another update that is already 14721 // installed. We need to make sure to delete the older one's .apk. 14722 res.removedInfo.args = createInstallArgsForExisting(0, 14723 deletedPackage.applicationInfo.getCodePath(), 14724 deletedPackage.applicationInfo.getResourcePath(), 14725 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14726 } else { 14727 res.removedInfo.args = null; 14728 } 14729 14730 // Successfully disabled the old package. Now proceed with re-installation 14731 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14732 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14733 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14734 14735 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14736 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14737 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14738 14739 PackageParser.Package newPackage = null; 14740 try { 14741 // Add the package to the internal data structures 14742 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14743 14744 // Set the update and install times 14745 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14746 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14747 System.currentTimeMillis()); 14748 14749 // Update the package dynamic state if succeeded 14750 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14751 // Now that the install succeeded make sure we remove data 14752 // directories for any child package the update removed. 14753 final int deletedChildCount = (deletedPackage.childPackages != null) 14754 ? deletedPackage.childPackages.size() : 0; 14755 final int newChildCount = (newPackage.childPackages != null) 14756 ? newPackage.childPackages.size() : 0; 14757 for (int i = 0; i < deletedChildCount; i++) { 14758 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14759 boolean childPackageDeleted = true; 14760 for (int j = 0; j < newChildCount; j++) { 14761 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14762 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14763 childPackageDeleted = false; 14764 break; 14765 } 14766 } 14767 if (childPackageDeleted) { 14768 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14769 deletedChildPkg.packageName); 14770 if (ps != null && res.removedInfo.removedChildPackages != null) { 14771 PackageRemovedInfo removedChildRes = res.removedInfo 14772 .removedChildPackages.get(deletedChildPkg.packageName); 14773 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14774 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14775 } 14776 } 14777 } 14778 14779 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14780 prepareAppDataAfterInstallLIF(newPackage); 14781 } 14782 } catch (PackageManagerException e) { 14783 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14784 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14785 } 14786 14787 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14788 // Re installation failed. Restore old information 14789 // Remove new pkg information 14790 if (newPackage != null) { 14791 removeInstalledPackageLI(newPackage, true); 14792 } 14793 // Add back the old system package 14794 try { 14795 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14796 } catch (PackageManagerException e) { 14797 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14798 } 14799 14800 synchronized (mPackages) { 14801 if (disabledSystem) { 14802 enableSystemPackageLPw(deletedPackage); 14803 } 14804 14805 // Ensure the installer package name up to date 14806 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14807 14808 // Update permissions for restored package 14809 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14810 14811 mSettings.writeLPr(); 14812 } 14813 14814 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14815 + " after failed upgrade"); 14816 } 14817 } 14818 14819 /** 14820 * Checks whether the parent or any of the child packages have a change shared 14821 * user. For a package to be a valid update the shred users of the parent and 14822 * the children should match. We may later support changing child shared users. 14823 * @param oldPkg The updated package. 14824 * @param newPkg The update package. 14825 * @return The shared user that change between the versions. 14826 */ 14827 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14828 PackageParser.Package newPkg) { 14829 // Check parent shared user 14830 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14831 return newPkg.packageName; 14832 } 14833 // Check child shared users 14834 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14835 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14836 for (int i = 0; i < newChildCount; i++) { 14837 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14838 // If this child was present, did it have the same shared user? 14839 for (int j = 0; j < oldChildCount; j++) { 14840 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14841 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14842 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14843 return newChildPkg.packageName; 14844 } 14845 } 14846 } 14847 return null; 14848 } 14849 14850 private void removeNativeBinariesLI(PackageSetting ps) { 14851 // Remove the lib path for the parent package 14852 if (ps != null) { 14853 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14854 // Remove the lib path for the child packages 14855 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14856 for (int i = 0; i < childCount; i++) { 14857 PackageSetting childPs = null; 14858 synchronized (mPackages) { 14859 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 14860 } 14861 if (childPs != null) { 14862 NativeLibraryHelper.removeNativeBinariesLI(childPs 14863 .legacyNativeLibraryPathString); 14864 } 14865 } 14866 } 14867 } 14868 14869 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14870 // Enable the parent package 14871 mSettings.enableSystemPackageLPw(pkg.packageName); 14872 // Enable the child packages 14873 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14874 for (int i = 0; i < childCount; i++) { 14875 PackageParser.Package childPkg = pkg.childPackages.get(i); 14876 mSettings.enableSystemPackageLPw(childPkg.packageName); 14877 } 14878 } 14879 14880 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14881 PackageParser.Package newPkg) { 14882 // Disable the parent package (parent always replaced) 14883 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14884 // Disable the child packages 14885 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14886 for (int i = 0; i < childCount; i++) { 14887 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14888 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14889 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14890 } 14891 return disabled; 14892 } 14893 14894 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14895 String installerPackageName) { 14896 // Enable the parent package 14897 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14898 // Enable the child packages 14899 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14900 for (int i = 0; i < childCount; i++) { 14901 PackageParser.Package childPkg = pkg.childPackages.get(i); 14902 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14903 } 14904 } 14905 14906 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14907 // Collect all used permissions in the UID 14908 ArraySet<String> usedPermissions = new ArraySet<>(); 14909 final int packageCount = su.packages.size(); 14910 for (int i = 0; i < packageCount; i++) { 14911 PackageSetting ps = su.packages.valueAt(i); 14912 if (ps.pkg == null) { 14913 continue; 14914 } 14915 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14916 for (int j = 0; j < requestedPermCount; j++) { 14917 String permission = ps.pkg.requestedPermissions.get(j); 14918 BasePermission bp = mSettings.mPermissions.get(permission); 14919 if (bp != null) { 14920 usedPermissions.add(permission); 14921 } 14922 } 14923 } 14924 14925 PermissionsState permissionsState = su.getPermissionsState(); 14926 // Prune install permissions 14927 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14928 final int installPermCount = installPermStates.size(); 14929 for (int i = installPermCount - 1; i >= 0; i--) { 14930 PermissionState permissionState = installPermStates.get(i); 14931 if (!usedPermissions.contains(permissionState.getName())) { 14932 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14933 if (bp != null) { 14934 permissionsState.revokeInstallPermission(bp); 14935 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14936 PackageManager.MASK_PERMISSION_FLAGS, 0); 14937 } 14938 } 14939 } 14940 14941 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14942 14943 // Prune runtime permissions 14944 for (int userId : allUserIds) { 14945 List<PermissionState> runtimePermStates = permissionsState 14946 .getRuntimePermissionStates(userId); 14947 final int runtimePermCount = runtimePermStates.size(); 14948 for (int i = runtimePermCount - 1; i >= 0; i--) { 14949 PermissionState permissionState = runtimePermStates.get(i); 14950 if (!usedPermissions.contains(permissionState.getName())) { 14951 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14952 if (bp != null) { 14953 permissionsState.revokeRuntimePermission(bp, userId); 14954 permissionsState.updatePermissionFlags(bp, userId, 14955 PackageManager.MASK_PERMISSION_FLAGS, 0); 14956 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14957 runtimePermissionChangedUserIds, userId); 14958 } 14959 } 14960 } 14961 } 14962 14963 return runtimePermissionChangedUserIds; 14964 } 14965 14966 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14967 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14968 // Update the parent package setting 14969 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14970 res, user); 14971 // Update the child packages setting 14972 final int childCount = (newPackage.childPackages != null) 14973 ? newPackage.childPackages.size() : 0; 14974 for (int i = 0; i < childCount; i++) { 14975 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14976 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14977 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14978 childRes.origUsers, childRes, user); 14979 } 14980 } 14981 14982 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14983 String installerPackageName, int[] allUsers, int[] installedForUsers, 14984 PackageInstalledInfo res, UserHandle user) { 14985 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14986 14987 String pkgName = newPackage.packageName; 14988 synchronized (mPackages) { 14989 //write settings. the installStatus will be incomplete at this stage. 14990 //note that the new package setting would have already been 14991 //added to mPackages. It hasn't been persisted yet. 14992 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14993 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14994 mSettings.writeLPr(); 14995 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14996 } 14997 14998 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14999 synchronized (mPackages) { 15000 updatePermissionsLPw(newPackage.packageName, newPackage, 15001 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 15002 ? UPDATE_PERMISSIONS_ALL : 0)); 15003 // For system-bundled packages, we assume that installing an upgraded version 15004 // of the package implies that the user actually wants to run that new code, 15005 // so we enable the package. 15006 PackageSetting ps = mSettings.mPackages.get(pkgName); 15007 final int userId = user.getIdentifier(); 15008 if (ps != null) { 15009 if (isSystemApp(newPackage)) { 15010 if (DEBUG_INSTALL) { 15011 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 15012 } 15013 // Enable system package for requested users 15014 if (res.origUsers != null) { 15015 for (int origUserId : res.origUsers) { 15016 if (userId == UserHandle.USER_ALL || userId == origUserId) { 15017 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 15018 origUserId, installerPackageName); 15019 } 15020 } 15021 } 15022 // Also convey the prior install/uninstall state 15023 if (allUsers != null && installedForUsers != null) { 15024 for (int currentUserId : allUsers) { 15025 final boolean installed = ArrayUtils.contains( 15026 installedForUsers, currentUserId); 15027 if (DEBUG_INSTALL) { 15028 Slog.d(TAG, " user " + currentUserId + " => " + installed); 15029 } 15030 ps.setInstalled(installed, currentUserId); 15031 } 15032 // these install state changes will be persisted in the 15033 // upcoming call to mSettings.writeLPr(). 15034 } 15035 } 15036 // It's implied that when a user requests installation, they want the app to be 15037 // installed and enabled. 15038 if (userId != UserHandle.USER_ALL) { 15039 ps.setInstalled(true, userId); 15040 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 15041 } 15042 } 15043 res.name = pkgName; 15044 res.uid = newPackage.applicationInfo.uid; 15045 res.pkg = newPackage; 15046 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 15047 mSettings.setInstallerPackageName(pkgName, installerPackageName); 15048 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15049 //to update install status 15050 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15051 mSettings.writeLPr(); 15052 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15053 } 15054 15055 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15056 } 15057 15058 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 15059 try { 15060 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 15061 installPackageLI(args, res); 15062 } finally { 15063 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15064 } 15065 } 15066 15067 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 15068 final int installFlags = args.installFlags; 15069 final String installerPackageName = args.installerPackageName; 15070 final String volumeUuid = args.volumeUuid; 15071 final File tmpPackageFile = new File(args.getCodePath()); 15072 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 15073 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 15074 || (args.volumeUuid != null)); 15075 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 15076 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 15077 boolean replace = false; 15078 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 15079 if (args.move != null) { 15080 // moving a complete application; perform an initial scan on the new install location 15081 scanFlags |= SCAN_INITIAL; 15082 } 15083 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 15084 scanFlags |= SCAN_DONT_KILL_APP; 15085 } 15086 15087 // Result object to be returned 15088 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15089 15090 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 15091 15092 // Sanity check 15093 if (ephemeral && (forwardLocked || onExternal)) { 15094 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 15095 + " external=" + onExternal); 15096 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15097 return; 15098 } 15099 15100 // Retrieve PackageSettings and parse package 15101 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 15102 | PackageParser.PARSE_ENFORCE_CODE 15103 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 15104 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 15105 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 15106 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 15107 PackageParser pp = new PackageParser(); 15108 pp.setSeparateProcesses(mSeparateProcesses); 15109 pp.setDisplayMetrics(mMetrics); 15110 15111 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 15112 final PackageParser.Package pkg; 15113 try { 15114 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 15115 } catch (PackageParserException e) { 15116 res.setError("Failed parse during installPackageLI", e); 15117 return; 15118 } finally { 15119 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15120 } 15121 15122 // If we are installing a clustered package add results for the children 15123 if (pkg.childPackages != null) { 15124 synchronized (mPackages) { 15125 final int childCount = pkg.childPackages.size(); 15126 for (int i = 0; i < childCount; i++) { 15127 PackageParser.Package childPkg = pkg.childPackages.get(i); 15128 PackageInstalledInfo childRes = new PackageInstalledInfo(); 15129 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15130 childRes.pkg = childPkg; 15131 childRes.name = childPkg.packageName; 15132 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15133 if (childPs != null) { 15134 childRes.origUsers = childPs.queryInstalledUsers( 15135 sUserManager.getUserIds(), true); 15136 } 15137 if ((mPackages.containsKey(childPkg.packageName))) { 15138 childRes.removedInfo = new PackageRemovedInfo(); 15139 childRes.removedInfo.removedPackage = childPkg.packageName; 15140 } 15141 if (res.addedChildPackages == null) { 15142 res.addedChildPackages = new ArrayMap<>(); 15143 } 15144 res.addedChildPackages.put(childPkg.packageName, childRes); 15145 } 15146 } 15147 } 15148 15149 // If package doesn't declare API override, mark that we have an install 15150 // time CPU ABI override. 15151 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15152 pkg.cpuAbiOverride = args.abiOverride; 15153 } 15154 15155 String pkgName = res.name = pkg.packageName; 15156 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15157 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15158 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15159 return; 15160 } 15161 } 15162 15163 try { 15164 // either use what we've been given or parse directly from the APK 15165 if (args.certificates != null) { 15166 try { 15167 PackageParser.populateCertificates(pkg, args.certificates); 15168 } catch (PackageParserException e) { 15169 // there was something wrong with the certificates we were given; 15170 // try to pull them from the APK 15171 PackageParser.collectCertificates(pkg, parseFlags); 15172 } 15173 } else { 15174 PackageParser.collectCertificates(pkg, parseFlags); 15175 } 15176 } catch (PackageParserException e) { 15177 res.setError("Failed collect during installPackageLI", e); 15178 return; 15179 } 15180 15181 // Get rid of all references to package scan path via parser. 15182 pp = null; 15183 String oldCodePath = null; 15184 boolean systemApp = false; 15185 synchronized (mPackages) { 15186 // Check if installing already existing package 15187 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15188 String oldName = mSettings.getRenamedPackageLPr(pkgName); 15189 if (pkg.mOriginalPackages != null 15190 && pkg.mOriginalPackages.contains(oldName) 15191 && mPackages.containsKey(oldName)) { 15192 // This package is derived from an original package, 15193 // and this device has been updating from that original 15194 // name. We must continue using the original name, so 15195 // rename the new package here. 15196 pkg.setPackageName(oldName); 15197 pkgName = pkg.packageName; 15198 replace = true; 15199 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15200 + oldName + " pkgName=" + pkgName); 15201 } else if (mPackages.containsKey(pkgName)) { 15202 // This package, under its official name, already exists 15203 // on the device; we should replace it. 15204 replace = true; 15205 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15206 } 15207 15208 // Child packages are installed through the parent package 15209 if (pkg.parentPackage != null) { 15210 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15211 "Package " + pkg.packageName + " is child of package " 15212 + pkg.parentPackage.parentPackage + ". Child packages " 15213 + "can be updated only through the parent package."); 15214 return; 15215 } 15216 15217 if (replace) { 15218 // Prevent apps opting out from runtime permissions 15219 PackageParser.Package oldPackage = mPackages.get(pkgName); 15220 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15221 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15222 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15223 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15224 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15225 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15226 + " doesn't support runtime permissions but the old" 15227 + " target SDK " + oldTargetSdk + " does."); 15228 return; 15229 } 15230 15231 // Prevent installing of child packages 15232 if (oldPackage.parentPackage != null) { 15233 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15234 "Package " + pkg.packageName + " is child of package " 15235 + oldPackage.parentPackage + ". Child packages " 15236 + "can be updated only through the parent package."); 15237 return; 15238 } 15239 } 15240 } 15241 15242 PackageSetting ps = mSettings.mPackages.get(pkgName); 15243 if (ps != null) { 15244 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15245 15246 // Quick sanity check that we're signed correctly if updating; 15247 // we'll check this again later when scanning, but we want to 15248 // bail early here before tripping over redefined permissions. 15249 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15250 if (!checkUpgradeKeySetLP(ps, pkg)) { 15251 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15252 + pkg.packageName + " upgrade keys do not match the " 15253 + "previously installed version"); 15254 return; 15255 } 15256 } else { 15257 try { 15258 verifySignaturesLP(ps, pkg); 15259 } catch (PackageManagerException e) { 15260 res.setError(e.error, e.getMessage()); 15261 return; 15262 } 15263 } 15264 15265 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15266 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15267 systemApp = (ps.pkg.applicationInfo.flags & 15268 ApplicationInfo.FLAG_SYSTEM) != 0; 15269 } 15270 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15271 } 15272 15273 // Check whether the newly-scanned package wants to define an already-defined perm 15274 int N = pkg.permissions.size(); 15275 for (int i = N-1; i >= 0; i--) { 15276 PackageParser.Permission perm = pkg.permissions.get(i); 15277 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15278 if (bp != null) { 15279 // If the defining package is signed with our cert, it's okay. This 15280 // also includes the "updating the same package" case, of course. 15281 // "updating same package" could also involve key-rotation. 15282 final boolean sigsOk; 15283 if (bp.sourcePackage.equals(pkg.packageName) 15284 && (bp.packageSetting instanceof PackageSetting) 15285 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15286 scanFlags))) { 15287 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15288 } else { 15289 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15290 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15291 } 15292 if (!sigsOk) { 15293 // If the owning package is the system itself, we log but allow 15294 // install to proceed; we fail the install on all other permission 15295 // redefinitions. 15296 if (!bp.sourcePackage.equals("android")) { 15297 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15298 + pkg.packageName + " attempting to redeclare permission " 15299 + perm.info.name + " already owned by " + bp.sourcePackage); 15300 res.origPermission = perm.info.name; 15301 res.origPackage = bp.sourcePackage; 15302 return; 15303 } else { 15304 Slog.w(TAG, "Package " + pkg.packageName 15305 + " attempting to redeclare system permission " 15306 + perm.info.name + "; ignoring new declaration"); 15307 pkg.permissions.remove(i); 15308 } 15309 } 15310 } 15311 } 15312 } 15313 15314 if (systemApp) { 15315 if (onExternal) { 15316 // Abort update; system app can't be replaced with app on sdcard 15317 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15318 "Cannot install updates to system apps on sdcard"); 15319 return; 15320 } else if (ephemeral) { 15321 // Abort update; system app can't be replaced with an ephemeral app 15322 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15323 "Cannot update a system app with an ephemeral app"); 15324 return; 15325 } 15326 } 15327 15328 if (args.move != null) { 15329 // We did an in-place move, so dex is ready to roll 15330 scanFlags |= SCAN_NO_DEX; 15331 scanFlags |= SCAN_MOVE; 15332 15333 synchronized (mPackages) { 15334 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15335 if (ps == null) { 15336 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15337 "Missing settings for moved package " + pkgName); 15338 } 15339 15340 // We moved the entire application as-is, so bring over the 15341 // previously derived ABI information. 15342 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15343 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15344 } 15345 15346 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15347 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15348 scanFlags |= SCAN_NO_DEX; 15349 15350 try { 15351 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15352 args.abiOverride : pkg.cpuAbiOverride); 15353 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15354 true /*extractLibs*/, mAppLib32InstallDir); 15355 } catch (PackageManagerException pme) { 15356 Slog.e(TAG, "Error deriving application ABI", pme); 15357 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15358 return; 15359 } 15360 15361 // Shared libraries for the package need to be updated. 15362 synchronized (mPackages) { 15363 try { 15364 updateSharedLibrariesLPr(pkg, null); 15365 } catch (PackageManagerException e) { 15366 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15367 } 15368 } 15369 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15370 // Do not run PackageDexOptimizer through the local performDexOpt 15371 // method because `pkg` may not be in `mPackages` yet. 15372 // 15373 // Also, don't fail application installs if the dexopt step fails. 15374 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15375 null /* instructionSets */, false /* checkProfiles */, 15376 getCompilerFilterForReason(REASON_INSTALL), 15377 getOrCreateCompilerPackageStats(pkg)); 15378 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15379 15380 // Notify BackgroundDexOptService that the package has been changed. 15381 // If this is an update of a package which used to fail to compile, 15382 // BDOS will remove it from its blacklist. 15383 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15384 } 15385 15386 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15387 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15388 return; 15389 } 15390 15391 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15392 15393 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15394 "installPackageLI")) { 15395 if (replace) { 15396 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15397 installerPackageName, res); 15398 } else { 15399 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15400 args.user, installerPackageName, volumeUuid, res); 15401 } 15402 } 15403 synchronized (mPackages) { 15404 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15405 if (ps != null) { 15406 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15407 } 15408 15409 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15410 for (int i = 0; i < childCount; i++) { 15411 PackageParser.Package childPkg = pkg.childPackages.get(i); 15412 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15413 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15414 if (childPs != null) { 15415 childRes.newUsers = childPs.queryInstalledUsers( 15416 sUserManager.getUserIds(), true); 15417 } 15418 } 15419 } 15420 } 15421 15422 private void startIntentFilterVerifications(int userId, boolean replacing, 15423 PackageParser.Package pkg) { 15424 if (mIntentFilterVerifierComponent == null) { 15425 Slog.w(TAG, "No IntentFilter verification will not be done as " 15426 + "there is no IntentFilterVerifier available!"); 15427 return; 15428 } 15429 15430 final int verifierUid = getPackageUid( 15431 mIntentFilterVerifierComponent.getPackageName(), 15432 MATCH_DEBUG_TRIAGED_MISSING, 15433 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15434 15435 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15436 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15437 mHandler.sendMessage(msg); 15438 15439 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15440 for (int i = 0; i < childCount; i++) { 15441 PackageParser.Package childPkg = pkg.childPackages.get(i); 15442 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15443 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15444 mHandler.sendMessage(msg); 15445 } 15446 } 15447 15448 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15449 PackageParser.Package pkg) { 15450 int size = pkg.activities.size(); 15451 if (size == 0) { 15452 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15453 "No activity, so no need to verify any IntentFilter!"); 15454 return; 15455 } 15456 15457 final boolean hasDomainURLs = hasDomainURLs(pkg); 15458 if (!hasDomainURLs) { 15459 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15460 "No domain URLs, so no need to verify any IntentFilter!"); 15461 return; 15462 } 15463 15464 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15465 + " if any IntentFilter from the " + size 15466 + " Activities needs verification ..."); 15467 15468 int count = 0; 15469 final String packageName = pkg.packageName; 15470 15471 synchronized (mPackages) { 15472 // If this is a new install and we see that we've already run verification for this 15473 // package, we have nothing to do: it means the state was restored from backup. 15474 if (!replacing) { 15475 IntentFilterVerificationInfo ivi = 15476 mSettings.getIntentFilterVerificationLPr(packageName); 15477 if (ivi != null) { 15478 if (DEBUG_DOMAIN_VERIFICATION) { 15479 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15480 + ivi.getStatusString()); 15481 } 15482 return; 15483 } 15484 } 15485 15486 // If any filters need to be verified, then all need to be. 15487 boolean needToVerify = false; 15488 for (PackageParser.Activity a : pkg.activities) { 15489 for (ActivityIntentInfo filter : a.intents) { 15490 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15491 if (DEBUG_DOMAIN_VERIFICATION) { 15492 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15493 } 15494 needToVerify = true; 15495 break; 15496 } 15497 } 15498 } 15499 15500 if (needToVerify) { 15501 final int verificationId = mIntentFilterVerificationToken++; 15502 for (PackageParser.Activity a : pkg.activities) { 15503 for (ActivityIntentInfo filter : a.intents) { 15504 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15505 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15506 "Verification needed for IntentFilter:" + filter.toString()); 15507 mIntentFilterVerifier.addOneIntentFilterVerification( 15508 verifierUid, userId, verificationId, filter, packageName); 15509 count++; 15510 } 15511 } 15512 } 15513 } 15514 } 15515 15516 if (count > 0) { 15517 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15518 + " IntentFilter verification" + (count > 1 ? "s" : "") 15519 + " for userId:" + userId); 15520 mIntentFilterVerifier.startVerifications(userId); 15521 } else { 15522 if (DEBUG_DOMAIN_VERIFICATION) { 15523 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15524 } 15525 } 15526 } 15527 15528 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15529 final ComponentName cn = filter.activity.getComponentName(); 15530 final String packageName = cn.getPackageName(); 15531 15532 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15533 packageName); 15534 if (ivi == null) { 15535 return true; 15536 } 15537 int status = ivi.getStatus(); 15538 switch (status) { 15539 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15540 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15541 return true; 15542 15543 default: 15544 // Nothing to do 15545 return false; 15546 } 15547 } 15548 15549 private static boolean isMultiArch(ApplicationInfo info) { 15550 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15551 } 15552 15553 private static boolean isExternal(PackageParser.Package pkg) { 15554 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15555 } 15556 15557 private static boolean isExternal(PackageSetting ps) { 15558 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15559 } 15560 15561 private static boolean isEphemeral(PackageParser.Package pkg) { 15562 return pkg.applicationInfo.isEphemeralApp(); 15563 } 15564 15565 private static boolean isEphemeral(PackageSetting ps) { 15566 return ps.pkg != null && isEphemeral(ps.pkg); 15567 } 15568 15569 private static boolean isSystemApp(PackageParser.Package pkg) { 15570 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15571 } 15572 15573 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15574 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15575 } 15576 15577 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15578 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15579 } 15580 15581 private static boolean isSystemApp(PackageSetting ps) { 15582 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15583 } 15584 15585 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15586 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15587 } 15588 15589 private int packageFlagsToInstallFlags(PackageSetting ps) { 15590 int installFlags = 0; 15591 if (isEphemeral(ps)) { 15592 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15593 } 15594 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15595 // This existing package was an external ASEC install when we have 15596 // the external flag without a UUID 15597 installFlags |= PackageManager.INSTALL_EXTERNAL; 15598 } 15599 if (ps.isForwardLocked()) { 15600 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15601 } 15602 return installFlags; 15603 } 15604 15605 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15606 if (isExternal(pkg)) { 15607 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15608 return StorageManager.UUID_PRIMARY_PHYSICAL; 15609 } else { 15610 return pkg.volumeUuid; 15611 } 15612 } else { 15613 return StorageManager.UUID_PRIVATE_INTERNAL; 15614 } 15615 } 15616 15617 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15618 if (isExternal(pkg)) { 15619 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15620 return mSettings.getExternalVersion(); 15621 } else { 15622 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15623 } 15624 } else { 15625 return mSettings.getInternalVersion(); 15626 } 15627 } 15628 15629 private void deleteTempPackageFiles() { 15630 final FilenameFilter filter = new FilenameFilter() { 15631 public boolean accept(File dir, String name) { 15632 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15633 } 15634 }; 15635 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15636 file.delete(); 15637 } 15638 } 15639 15640 @Override 15641 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15642 int flags) { 15643 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15644 flags); 15645 } 15646 15647 @Override 15648 public void deletePackage(final String packageName, 15649 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15650 mContext.enforceCallingOrSelfPermission( 15651 android.Manifest.permission.DELETE_PACKAGES, null); 15652 Preconditions.checkNotNull(packageName); 15653 Preconditions.checkNotNull(observer); 15654 final int uid = Binder.getCallingUid(); 15655 if (!isOrphaned(packageName) 15656 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 15657 try { 15658 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 15659 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 15660 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 15661 observer.onUserActionRequired(intent); 15662 } catch (RemoteException re) { 15663 } 15664 return; 15665 } 15666 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15667 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15668 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15669 mContext.enforceCallingOrSelfPermission( 15670 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15671 "deletePackage for user " + userId); 15672 } 15673 15674 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15675 try { 15676 observer.onPackageDeleted(packageName, 15677 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15678 } catch (RemoteException re) { 15679 } 15680 return; 15681 } 15682 15683 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15684 try { 15685 observer.onPackageDeleted(packageName, 15686 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15687 } catch (RemoteException re) { 15688 } 15689 return; 15690 } 15691 15692 if (DEBUG_REMOVE) { 15693 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15694 + " deleteAllUsers: " + deleteAllUsers ); 15695 } 15696 // Queue up an async operation since the package deletion may take a little while. 15697 mHandler.post(new Runnable() { 15698 public void run() { 15699 mHandler.removeCallbacks(this); 15700 int returnCode; 15701 if (!deleteAllUsers) { 15702 returnCode = deletePackageX(packageName, userId, deleteFlags); 15703 } else { 15704 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15705 // If nobody is blocking uninstall, proceed with delete for all users 15706 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15707 returnCode = deletePackageX(packageName, userId, deleteFlags); 15708 } else { 15709 // Otherwise uninstall individually for users with blockUninstalls=false 15710 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15711 for (int userId : users) { 15712 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15713 returnCode = deletePackageX(packageName, userId, userFlags); 15714 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15715 Slog.w(TAG, "Package delete failed for user " + userId 15716 + ", returnCode " + returnCode); 15717 } 15718 } 15719 } 15720 // The app has only been marked uninstalled for certain users. 15721 // We still need to report that delete was blocked 15722 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15723 } 15724 } 15725 try { 15726 observer.onPackageDeleted(packageName, returnCode, null); 15727 } catch (RemoteException e) { 15728 Log.i(TAG, "Observer no longer exists."); 15729 } //end catch 15730 } //end run 15731 }); 15732 } 15733 15734 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 15735 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 15736 || callingUid == Process.SYSTEM_UID) { 15737 return true; 15738 } 15739 final int callingUserId = UserHandle.getUserId(callingUid); 15740 // If the caller installed the pkgName, then allow it to silently uninstall. 15741 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 15742 return true; 15743 } 15744 15745 // Allow package verifier to silently uninstall. 15746 if (mRequiredVerifierPackage != null && 15747 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 15748 return true; 15749 } 15750 15751 // Allow package uninstaller to silently uninstall. 15752 if (mRequiredUninstallerPackage != null && 15753 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 15754 return true; 15755 } 15756 15757 // Allow storage manager to silently uninstall. 15758 if (mStorageManagerPackage != null && 15759 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 15760 return true; 15761 } 15762 return false; 15763 } 15764 15765 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15766 int[] result = EMPTY_INT_ARRAY; 15767 for (int userId : userIds) { 15768 if (getBlockUninstallForUser(packageName, userId)) { 15769 result = ArrayUtils.appendInt(result, userId); 15770 } 15771 } 15772 return result; 15773 } 15774 15775 @Override 15776 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15777 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15778 } 15779 15780 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15781 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15782 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15783 try { 15784 if (dpm != null) { 15785 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15786 /* callingUserOnly =*/ false); 15787 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15788 : deviceOwnerComponentName.getPackageName(); 15789 // Does the package contains the device owner? 15790 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15791 // this check is probably not needed, since DO should be registered as a device 15792 // admin on some user too. (Original bug for this: b/17657954) 15793 if (packageName.equals(deviceOwnerPackageName)) { 15794 return true; 15795 } 15796 // Does it contain a device admin for any user? 15797 int[] users; 15798 if (userId == UserHandle.USER_ALL) { 15799 users = sUserManager.getUserIds(); 15800 } else { 15801 users = new int[]{userId}; 15802 } 15803 for (int i = 0; i < users.length; ++i) { 15804 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15805 return true; 15806 } 15807 } 15808 } 15809 } catch (RemoteException e) { 15810 } 15811 return false; 15812 } 15813 15814 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15815 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15816 } 15817 15818 /** 15819 * This method is an internal method that could be get invoked either 15820 * to delete an installed package or to clean up a failed installation. 15821 * After deleting an installed package, a broadcast is sent to notify any 15822 * listeners that the package has been removed. For cleaning up a failed 15823 * installation, the broadcast is not necessary since the package's 15824 * installation wouldn't have sent the initial broadcast either 15825 * The key steps in deleting a package are 15826 * deleting the package information in internal structures like mPackages, 15827 * deleting the packages base directories through installd 15828 * updating mSettings to reflect current status 15829 * persisting settings for later use 15830 * sending a broadcast if necessary 15831 */ 15832 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15833 final PackageRemovedInfo info = new PackageRemovedInfo(); 15834 final boolean res; 15835 15836 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15837 ? UserHandle.USER_ALL : userId; 15838 15839 if (isPackageDeviceAdmin(packageName, removeUser)) { 15840 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15841 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15842 } 15843 15844 PackageSetting uninstalledPs = null; 15845 15846 // for the uninstall-updates case and restricted profiles, remember the per- 15847 // user handle installed state 15848 int[] allUsers; 15849 synchronized (mPackages) { 15850 uninstalledPs = mSettings.mPackages.get(packageName); 15851 if (uninstalledPs == null) { 15852 Slog.w(TAG, "Not removing non-existent package " + packageName); 15853 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15854 } 15855 allUsers = sUserManager.getUserIds(); 15856 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15857 } 15858 15859 final int freezeUser; 15860 if (isUpdatedSystemApp(uninstalledPs) 15861 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15862 // We're downgrading a system app, which will apply to all users, so 15863 // freeze them all during the downgrade 15864 freezeUser = UserHandle.USER_ALL; 15865 } else { 15866 freezeUser = removeUser; 15867 } 15868 15869 synchronized (mInstallLock) { 15870 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15871 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15872 deleteFlags, "deletePackageX")) { 15873 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15874 deleteFlags | REMOVE_CHATTY, info, true, null); 15875 } 15876 synchronized (mPackages) { 15877 if (res) { 15878 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15879 } 15880 } 15881 } 15882 15883 if (res) { 15884 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15885 info.sendPackageRemovedBroadcasts(killApp); 15886 info.sendSystemPackageUpdatedBroadcasts(); 15887 info.sendSystemPackageAppearedBroadcasts(); 15888 } 15889 // Force a gc here. 15890 Runtime.getRuntime().gc(); 15891 // Delete the resources here after sending the broadcast to let 15892 // other processes clean up before deleting resources. 15893 if (info.args != null) { 15894 synchronized (mInstallLock) { 15895 info.args.doPostDeleteLI(true); 15896 } 15897 } 15898 15899 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15900 } 15901 15902 class PackageRemovedInfo { 15903 String removedPackage; 15904 int uid = -1; 15905 int removedAppId = -1; 15906 int[] origUsers; 15907 int[] removedUsers = null; 15908 boolean isRemovedPackageSystemUpdate = false; 15909 boolean isUpdate; 15910 boolean dataRemoved; 15911 boolean removedForAllUsers; 15912 // Clean up resources deleted packages. 15913 InstallArgs args = null; 15914 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15915 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15916 15917 void sendPackageRemovedBroadcasts(boolean killApp) { 15918 sendPackageRemovedBroadcastInternal(killApp); 15919 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15920 for (int i = 0; i < childCount; i++) { 15921 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15922 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15923 } 15924 } 15925 15926 void sendSystemPackageUpdatedBroadcasts() { 15927 if (isRemovedPackageSystemUpdate) { 15928 sendSystemPackageUpdatedBroadcastsInternal(); 15929 final int childCount = (removedChildPackages != null) 15930 ? removedChildPackages.size() : 0; 15931 for (int i = 0; i < childCount; i++) { 15932 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15933 if (childInfo.isRemovedPackageSystemUpdate) { 15934 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15935 } 15936 } 15937 } 15938 } 15939 15940 void sendSystemPackageAppearedBroadcasts() { 15941 final int packageCount = (appearedChildPackages != null) 15942 ? appearedChildPackages.size() : 0; 15943 for (int i = 0; i < packageCount; i++) { 15944 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15945 sendPackageAddedForNewUsers(installedInfo.name, true, 15946 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 15947 } 15948 } 15949 15950 private void sendSystemPackageUpdatedBroadcastsInternal() { 15951 Bundle extras = new Bundle(2); 15952 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15953 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15954 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15955 extras, 0, null, null, null); 15956 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15957 extras, 0, null, null, null); 15958 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15959 null, 0, removedPackage, null, null); 15960 } 15961 15962 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15963 Bundle extras = new Bundle(2); 15964 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15965 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15966 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15967 if (isUpdate || isRemovedPackageSystemUpdate) { 15968 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15969 } 15970 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15971 if (removedPackage != null) { 15972 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15973 extras, 0, null, null, removedUsers); 15974 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15975 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15976 removedPackage, extras, 0, null, null, removedUsers); 15977 } 15978 } 15979 if (removedAppId >= 0) { 15980 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15981 removedUsers); 15982 } 15983 } 15984 } 15985 15986 /* 15987 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15988 * flag is not set, the data directory is removed as well. 15989 * make sure this flag is set for partially installed apps. If not its meaningless to 15990 * delete a partially installed application. 15991 */ 15992 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15993 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15994 String packageName = ps.name; 15995 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15996 // Retrieve object to delete permissions for shared user later on 15997 final PackageParser.Package deletedPkg; 15998 final PackageSetting deletedPs; 15999 // reader 16000 synchronized (mPackages) { 16001 deletedPkg = mPackages.get(packageName); 16002 deletedPs = mSettings.mPackages.get(packageName); 16003 if (outInfo != null) { 16004 outInfo.removedPackage = packageName; 16005 outInfo.removedUsers = deletedPs != null 16006 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 16007 : null; 16008 } 16009 } 16010 16011 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 16012 16013 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 16014 final PackageParser.Package resolvedPkg; 16015 if (deletedPkg != null) { 16016 resolvedPkg = deletedPkg; 16017 } else { 16018 // We don't have a parsed package when it lives on an ejected 16019 // adopted storage device, so fake something together 16020 resolvedPkg = new PackageParser.Package(ps.name); 16021 resolvedPkg.setVolumeUuid(ps.volumeUuid); 16022 } 16023 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 16024 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16025 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 16026 if (outInfo != null) { 16027 outInfo.dataRemoved = true; 16028 } 16029 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 16030 } 16031 16032 // writer 16033 synchronized (mPackages) { 16034 if (deletedPs != null) { 16035 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 16036 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 16037 clearDefaultBrowserIfNeeded(packageName); 16038 if (outInfo != null) { 16039 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 16040 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 16041 } 16042 updatePermissionsLPw(deletedPs.name, null, 0); 16043 if (deletedPs.sharedUser != null) { 16044 // Remove permissions associated with package. Since runtime 16045 // permissions are per user we have to kill the removed package 16046 // or packages running under the shared user of the removed 16047 // package if revoking the permissions requested only by the removed 16048 // package is successful and this causes a change in gids. 16049 for (int userId : UserManagerService.getInstance().getUserIds()) { 16050 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 16051 userId); 16052 if (userIdToKill == UserHandle.USER_ALL 16053 || userIdToKill >= UserHandle.USER_SYSTEM) { 16054 // If gids changed for this user, kill all affected packages. 16055 mHandler.post(new Runnable() { 16056 @Override 16057 public void run() { 16058 // This has to happen with no lock held. 16059 killApplication(deletedPs.name, deletedPs.appId, 16060 KILL_APP_REASON_GIDS_CHANGED); 16061 } 16062 }); 16063 break; 16064 } 16065 } 16066 } 16067 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 16068 } 16069 // make sure to preserve per-user disabled state if this removal was just 16070 // a downgrade of a system app to the factory package 16071 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 16072 if (DEBUG_REMOVE) { 16073 Slog.d(TAG, "Propagating install state across downgrade"); 16074 } 16075 for (int userId : allUserHandles) { 16076 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16077 if (DEBUG_REMOVE) { 16078 Slog.d(TAG, " user " + userId + " => " + installed); 16079 } 16080 ps.setInstalled(installed, userId); 16081 } 16082 } 16083 } 16084 // can downgrade to reader 16085 if (writeSettings) { 16086 // Save settings now 16087 mSettings.writeLPr(); 16088 } 16089 } 16090 if (outInfo != null) { 16091 // A user ID was deleted here. Go through all users and remove it 16092 // from KeyStore. 16093 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 16094 } 16095 } 16096 16097 static boolean locationIsPrivileged(File path) { 16098 try { 16099 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 16100 .getCanonicalPath(); 16101 return path.getCanonicalPath().startsWith(privilegedAppDir); 16102 } catch (IOException e) { 16103 Slog.e(TAG, "Unable to access code path " + path); 16104 } 16105 return false; 16106 } 16107 16108 /* 16109 * Tries to delete system package. 16110 */ 16111 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 16112 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 16113 boolean writeSettings) { 16114 if (deletedPs.parentPackageName != null) { 16115 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 16116 return false; 16117 } 16118 16119 final boolean applyUserRestrictions 16120 = (allUserHandles != null) && (outInfo.origUsers != null); 16121 final PackageSetting disabledPs; 16122 // Confirm if the system package has been updated 16123 // An updated system app can be deleted. This will also have to restore 16124 // the system pkg from system partition 16125 // reader 16126 synchronized (mPackages) { 16127 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 16128 } 16129 16130 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 16131 + " disabledPs=" + disabledPs); 16132 16133 if (disabledPs == null) { 16134 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 16135 return false; 16136 } else if (DEBUG_REMOVE) { 16137 Slog.d(TAG, "Deleting system pkg from data partition"); 16138 } 16139 16140 if (DEBUG_REMOVE) { 16141 if (applyUserRestrictions) { 16142 Slog.d(TAG, "Remembering install states:"); 16143 for (int userId : allUserHandles) { 16144 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 16145 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 16146 } 16147 } 16148 } 16149 16150 // Delete the updated package 16151 outInfo.isRemovedPackageSystemUpdate = true; 16152 if (outInfo.removedChildPackages != null) { 16153 final int childCount = (deletedPs.childPackageNames != null) 16154 ? deletedPs.childPackageNames.size() : 0; 16155 for (int i = 0; i < childCount; i++) { 16156 String childPackageName = deletedPs.childPackageNames.get(i); 16157 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16158 .contains(childPackageName)) { 16159 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16160 childPackageName); 16161 if (childInfo != null) { 16162 childInfo.isRemovedPackageSystemUpdate = true; 16163 } 16164 } 16165 } 16166 } 16167 16168 if (disabledPs.versionCode < deletedPs.versionCode) { 16169 // Delete data for downgrades 16170 flags &= ~PackageManager.DELETE_KEEP_DATA; 16171 } else { 16172 // Preserve data by setting flag 16173 flags |= PackageManager.DELETE_KEEP_DATA; 16174 } 16175 16176 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16177 outInfo, writeSettings, disabledPs.pkg); 16178 if (!ret) { 16179 return false; 16180 } 16181 16182 // writer 16183 synchronized (mPackages) { 16184 // Reinstate the old system package 16185 enableSystemPackageLPw(disabledPs.pkg); 16186 // Remove any native libraries from the upgraded package. 16187 removeNativeBinariesLI(deletedPs); 16188 } 16189 16190 // Install the system package 16191 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16192 int parseFlags = mDefParseFlags 16193 | PackageParser.PARSE_MUST_BE_APK 16194 | PackageParser.PARSE_IS_SYSTEM 16195 | PackageParser.PARSE_IS_SYSTEM_DIR; 16196 if (locationIsPrivileged(disabledPs.codePath)) { 16197 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16198 } 16199 16200 final PackageParser.Package newPkg; 16201 try { 16202 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 16203 } catch (PackageManagerException e) { 16204 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16205 + e.getMessage()); 16206 return false; 16207 } 16208 try { 16209 // update shared libraries for the newly re-installed system package 16210 updateSharedLibrariesLPr(newPkg, null); 16211 } catch (PackageManagerException e) { 16212 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16213 } 16214 16215 prepareAppDataAfterInstallLIF(newPkg); 16216 16217 // writer 16218 synchronized (mPackages) { 16219 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16220 16221 // Propagate the permissions state as we do not want to drop on the floor 16222 // runtime permissions. The update permissions method below will take 16223 // care of removing obsolete permissions and grant install permissions. 16224 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16225 updatePermissionsLPw(newPkg.packageName, newPkg, 16226 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16227 16228 if (applyUserRestrictions) { 16229 if (DEBUG_REMOVE) { 16230 Slog.d(TAG, "Propagating install state across reinstall"); 16231 } 16232 for (int userId : allUserHandles) { 16233 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16234 if (DEBUG_REMOVE) { 16235 Slog.d(TAG, " user " + userId + " => " + installed); 16236 } 16237 ps.setInstalled(installed, userId); 16238 16239 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16240 } 16241 // Regardless of writeSettings we need to ensure that this restriction 16242 // state propagation is persisted 16243 mSettings.writeAllUsersPackageRestrictionsLPr(); 16244 } 16245 // can downgrade to reader here 16246 if (writeSettings) { 16247 mSettings.writeLPr(); 16248 } 16249 } 16250 return true; 16251 } 16252 16253 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16254 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16255 PackageRemovedInfo outInfo, boolean writeSettings, 16256 PackageParser.Package replacingPackage) { 16257 synchronized (mPackages) { 16258 if (outInfo != null) { 16259 outInfo.uid = ps.appId; 16260 } 16261 16262 if (outInfo != null && outInfo.removedChildPackages != null) { 16263 final int childCount = (ps.childPackageNames != null) 16264 ? ps.childPackageNames.size() : 0; 16265 for (int i = 0; i < childCount; i++) { 16266 String childPackageName = ps.childPackageNames.get(i); 16267 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16268 if (childPs == null) { 16269 return false; 16270 } 16271 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16272 childPackageName); 16273 if (childInfo != null) { 16274 childInfo.uid = childPs.appId; 16275 } 16276 } 16277 } 16278 } 16279 16280 // Delete package data from internal structures and also remove data if flag is set 16281 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16282 16283 // Delete the child packages data 16284 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16285 for (int i = 0; i < childCount; i++) { 16286 PackageSetting childPs; 16287 synchronized (mPackages) { 16288 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16289 } 16290 if (childPs != null) { 16291 PackageRemovedInfo childOutInfo = (outInfo != null 16292 && outInfo.removedChildPackages != null) 16293 ? outInfo.removedChildPackages.get(childPs.name) : null; 16294 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16295 && (replacingPackage != null 16296 && !replacingPackage.hasChildPackage(childPs.name)) 16297 ? flags & ~DELETE_KEEP_DATA : flags; 16298 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16299 deleteFlags, writeSettings); 16300 } 16301 } 16302 16303 // Delete application code and resources only for parent packages 16304 if (ps.parentPackageName == null) { 16305 if (deleteCodeAndResources && (outInfo != null)) { 16306 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16307 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16308 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16309 } 16310 } 16311 16312 return true; 16313 } 16314 16315 @Override 16316 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16317 int userId) { 16318 mContext.enforceCallingOrSelfPermission( 16319 android.Manifest.permission.DELETE_PACKAGES, null); 16320 synchronized (mPackages) { 16321 PackageSetting ps = mSettings.mPackages.get(packageName); 16322 if (ps == null) { 16323 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16324 return false; 16325 } 16326 if (!ps.getInstalled(userId)) { 16327 // Can't block uninstall for an app that is not installed or enabled. 16328 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16329 return false; 16330 } 16331 ps.setBlockUninstall(blockUninstall, userId); 16332 mSettings.writePackageRestrictionsLPr(userId); 16333 } 16334 return true; 16335 } 16336 16337 @Override 16338 public boolean getBlockUninstallForUser(String packageName, int userId) { 16339 synchronized (mPackages) { 16340 PackageSetting ps = mSettings.mPackages.get(packageName); 16341 if (ps == null) { 16342 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16343 return false; 16344 } 16345 return ps.getBlockUninstall(userId); 16346 } 16347 } 16348 16349 @Override 16350 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16351 int callingUid = Binder.getCallingUid(); 16352 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16353 throw new SecurityException( 16354 "setRequiredForSystemUser can only be run by the system or root"); 16355 } 16356 synchronized (mPackages) { 16357 PackageSetting ps = mSettings.mPackages.get(packageName); 16358 if (ps == null) { 16359 Log.w(TAG, "Package doesn't exist: " + packageName); 16360 return false; 16361 } 16362 if (systemUserApp) { 16363 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16364 } else { 16365 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16366 } 16367 mSettings.writeLPr(); 16368 } 16369 return true; 16370 } 16371 16372 /* 16373 * This method handles package deletion in general 16374 */ 16375 private boolean deletePackageLIF(String packageName, UserHandle user, 16376 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16377 PackageRemovedInfo outInfo, boolean writeSettings, 16378 PackageParser.Package replacingPackage) { 16379 if (packageName == null) { 16380 Slog.w(TAG, "Attempt to delete null packageName."); 16381 return false; 16382 } 16383 16384 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16385 16386 PackageSetting ps; 16387 16388 synchronized (mPackages) { 16389 ps = mSettings.mPackages.get(packageName); 16390 if (ps == null) { 16391 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16392 return false; 16393 } 16394 16395 if (ps.parentPackageName != null && (!isSystemApp(ps) 16396 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16397 if (DEBUG_REMOVE) { 16398 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16399 + ((user == null) ? UserHandle.USER_ALL : user)); 16400 } 16401 final int removedUserId = (user != null) ? user.getIdentifier() 16402 : UserHandle.USER_ALL; 16403 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16404 return false; 16405 } 16406 markPackageUninstalledForUserLPw(ps, user); 16407 scheduleWritePackageRestrictionsLocked(user); 16408 return true; 16409 } 16410 } 16411 16412 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16413 && user.getIdentifier() != UserHandle.USER_ALL)) { 16414 // The caller is asking that the package only be deleted for a single 16415 // user. To do this, we just mark its uninstalled state and delete 16416 // its data. If this is a system app, we only allow this to happen if 16417 // they have set the special DELETE_SYSTEM_APP which requests different 16418 // semantics than normal for uninstalling system apps. 16419 markPackageUninstalledForUserLPw(ps, user); 16420 16421 if (!isSystemApp(ps)) { 16422 // Do not uninstall the APK if an app should be cached 16423 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16424 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16425 // Other user still have this package installed, so all 16426 // we need to do is clear this user's data and save that 16427 // it is uninstalled. 16428 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16429 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16430 return false; 16431 } 16432 scheduleWritePackageRestrictionsLocked(user); 16433 return true; 16434 } else { 16435 // We need to set it back to 'installed' so the uninstall 16436 // broadcasts will be sent correctly. 16437 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16438 ps.setInstalled(true, user.getIdentifier()); 16439 } 16440 } else { 16441 // This is a system app, so we assume that the 16442 // other users still have this package installed, so all 16443 // we need to do is clear this user's data and save that 16444 // it is uninstalled. 16445 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16446 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16447 return false; 16448 } 16449 scheduleWritePackageRestrictionsLocked(user); 16450 return true; 16451 } 16452 } 16453 16454 // If we are deleting a composite package for all users, keep track 16455 // of result for each child. 16456 if (ps.childPackageNames != null && outInfo != null) { 16457 synchronized (mPackages) { 16458 final int childCount = ps.childPackageNames.size(); 16459 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16460 for (int i = 0; i < childCount; i++) { 16461 String childPackageName = ps.childPackageNames.get(i); 16462 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16463 childInfo.removedPackage = childPackageName; 16464 outInfo.removedChildPackages.put(childPackageName, childInfo); 16465 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16466 if (childPs != null) { 16467 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16468 } 16469 } 16470 } 16471 } 16472 16473 boolean ret = false; 16474 if (isSystemApp(ps)) { 16475 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16476 // When an updated system application is deleted we delete the existing resources 16477 // as well and fall back to existing code in system partition 16478 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16479 } else { 16480 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16481 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16482 outInfo, writeSettings, replacingPackage); 16483 } 16484 16485 // Take a note whether we deleted the package for all users 16486 if (outInfo != null) { 16487 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16488 if (outInfo.removedChildPackages != null) { 16489 synchronized (mPackages) { 16490 final int childCount = outInfo.removedChildPackages.size(); 16491 for (int i = 0; i < childCount; i++) { 16492 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16493 if (childInfo != null) { 16494 childInfo.removedForAllUsers = mPackages.get( 16495 childInfo.removedPackage) == null; 16496 } 16497 } 16498 } 16499 } 16500 // If we uninstalled an update to a system app there may be some 16501 // child packages that appeared as they are declared in the system 16502 // app but were not declared in the update. 16503 if (isSystemApp(ps)) { 16504 synchronized (mPackages) { 16505 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 16506 final int childCount = (updatedPs.childPackageNames != null) 16507 ? updatedPs.childPackageNames.size() : 0; 16508 for (int i = 0; i < childCount; i++) { 16509 String childPackageName = updatedPs.childPackageNames.get(i); 16510 if (outInfo.removedChildPackages == null 16511 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16512 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16513 if (childPs == null) { 16514 continue; 16515 } 16516 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16517 installRes.name = childPackageName; 16518 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16519 installRes.pkg = mPackages.get(childPackageName); 16520 installRes.uid = childPs.pkg.applicationInfo.uid; 16521 if (outInfo.appearedChildPackages == null) { 16522 outInfo.appearedChildPackages = new ArrayMap<>(); 16523 } 16524 outInfo.appearedChildPackages.put(childPackageName, installRes); 16525 } 16526 } 16527 } 16528 } 16529 } 16530 16531 return ret; 16532 } 16533 16534 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16535 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16536 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16537 for (int nextUserId : userIds) { 16538 if (DEBUG_REMOVE) { 16539 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16540 } 16541 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16542 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16543 false /*hidden*/, false /*suspended*/, null, null, null, 16544 false /*blockUninstall*/, 16545 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16546 } 16547 } 16548 16549 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16550 PackageRemovedInfo outInfo) { 16551 final PackageParser.Package pkg; 16552 synchronized (mPackages) { 16553 pkg = mPackages.get(ps.name); 16554 } 16555 16556 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16557 : new int[] {userId}; 16558 for (int nextUserId : userIds) { 16559 if (DEBUG_REMOVE) { 16560 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16561 + nextUserId); 16562 } 16563 16564 destroyAppDataLIF(pkg, userId, 16565 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16566 destroyAppProfilesLIF(pkg, userId); 16567 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16568 schedulePackageCleaning(ps.name, nextUserId, false); 16569 synchronized (mPackages) { 16570 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16571 scheduleWritePackageRestrictionsLocked(nextUserId); 16572 } 16573 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16574 } 16575 } 16576 16577 if (outInfo != null) { 16578 outInfo.removedPackage = ps.name; 16579 outInfo.removedAppId = ps.appId; 16580 outInfo.removedUsers = userIds; 16581 } 16582 16583 return true; 16584 } 16585 16586 private final class ClearStorageConnection implements ServiceConnection { 16587 IMediaContainerService mContainerService; 16588 16589 @Override 16590 public void onServiceConnected(ComponentName name, IBinder service) { 16591 synchronized (this) { 16592 mContainerService = IMediaContainerService.Stub.asInterface(service); 16593 notifyAll(); 16594 } 16595 } 16596 16597 @Override 16598 public void onServiceDisconnected(ComponentName name) { 16599 } 16600 } 16601 16602 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16603 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16604 16605 final boolean mounted; 16606 if (Environment.isExternalStorageEmulated()) { 16607 mounted = true; 16608 } else { 16609 final String status = Environment.getExternalStorageState(); 16610 16611 mounted = status.equals(Environment.MEDIA_MOUNTED) 16612 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16613 } 16614 16615 if (!mounted) { 16616 return; 16617 } 16618 16619 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16620 int[] users; 16621 if (userId == UserHandle.USER_ALL) { 16622 users = sUserManager.getUserIds(); 16623 } else { 16624 users = new int[] { userId }; 16625 } 16626 final ClearStorageConnection conn = new ClearStorageConnection(); 16627 if (mContext.bindServiceAsUser( 16628 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16629 try { 16630 for (int curUser : users) { 16631 long timeout = SystemClock.uptimeMillis() + 5000; 16632 synchronized (conn) { 16633 long now; 16634 while (conn.mContainerService == null && 16635 (now = SystemClock.uptimeMillis()) < timeout) { 16636 try { 16637 conn.wait(timeout - now); 16638 } catch (InterruptedException e) { 16639 } 16640 } 16641 } 16642 if (conn.mContainerService == null) { 16643 return; 16644 } 16645 16646 final UserEnvironment userEnv = new UserEnvironment(curUser); 16647 clearDirectory(conn.mContainerService, 16648 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16649 if (allData) { 16650 clearDirectory(conn.mContainerService, 16651 userEnv.buildExternalStorageAppDataDirs(packageName)); 16652 clearDirectory(conn.mContainerService, 16653 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16654 } 16655 } 16656 } finally { 16657 mContext.unbindService(conn); 16658 } 16659 } 16660 } 16661 16662 @Override 16663 public void clearApplicationProfileData(String packageName) { 16664 enforceSystemOrRoot("Only the system can clear all profile data"); 16665 16666 final PackageParser.Package pkg; 16667 synchronized (mPackages) { 16668 pkg = mPackages.get(packageName); 16669 } 16670 16671 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16672 synchronized (mInstallLock) { 16673 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16674 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16675 true /* removeBaseMarker */); 16676 } 16677 } 16678 } 16679 16680 @Override 16681 public void clearApplicationUserData(final String packageName, 16682 final IPackageDataObserver observer, final int userId) { 16683 mContext.enforceCallingOrSelfPermission( 16684 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16685 16686 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16687 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16688 16689 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16690 throw new SecurityException("Cannot clear data for a protected package: " 16691 + packageName); 16692 } 16693 // Queue up an async operation since the package deletion may take a little while. 16694 mHandler.post(new Runnable() { 16695 public void run() { 16696 mHandler.removeCallbacks(this); 16697 final boolean succeeded; 16698 try (PackageFreezer freezer = freezePackage(packageName, 16699 "clearApplicationUserData")) { 16700 synchronized (mInstallLock) { 16701 succeeded = clearApplicationUserDataLIF(packageName, userId); 16702 } 16703 clearExternalStorageDataSync(packageName, userId, true); 16704 } 16705 if (succeeded) { 16706 // invoke DeviceStorageMonitor's update method to clear any notifications 16707 DeviceStorageMonitorInternal dsm = LocalServices 16708 .getService(DeviceStorageMonitorInternal.class); 16709 if (dsm != null) { 16710 dsm.checkMemory(); 16711 } 16712 } 16713 if(observer != null) { 16714 try { 16715 observer.onRemoveCompleted(packageName, succeeded); 16716 } catch (RemoteException e) { 16717 Log.i(TAG, "Observer no longer exists."); 16718 } 16719 } //end if observer 16720 } //end run 16721 }); 16722 } 16723 16724 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16725 if (packageName == null) { 16726 Slog.w(TAG, "Attempt to delete null packageName."); 16727 return false; 16728 } 16729 16730 // Try finding details about the requested package 16731 PackageParser.Package pkg; 16732 synchronized (mPackages) { 16733 pkg = mPackages.get(packageName); 16734 if (pkg == null) { 16735 final PackageSetting ps = mSettings.mPackages.get(packageName); 16736 if (ps != null) { 16737 pkg = ps.pkg; 16738 } 16739 } 16740 16741 if (pkg == null) { 16742 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16743 return false; 16744 } 16745 16746 PackageSetting ps = (PackageSetting) pkg.mExtras; 16747 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16748 } 16749 16750 clearAppDataLIF(pkg, userId, 16751 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16752 16753 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16754 removeKeystoreDataIfNeeded(userId, appId); 16755 16756 UserManagerInternal umInternal = getUserManagerInternal(); 16757 final int flags; 16758 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16759 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16760 } else if (umInternal.isUserRunning(userId)) { 16761 flags = StorageManager.FLAG_STORAGE_DE; 16762 } else { 16763 flags = 0; 16764 } 16765 prepareAppDataContentsLIF(pkg, userId, flags); 16766 16767 return true; 16768 } 16769 16770 /** 16771 * Reverts user permission state changes (permissions and flags) in 16772 * all packages for a given user. 16773 * 16774 * @param userId The device user for which to do a reset. 16775 */ 16776 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16777 final int packageCount = mPackages.size(); 16778 for (int i = 0; i < packageCount; i++) { 16779 PackageParser.Package pkg = mPackages.valueAt(i); 16780 PackageSetting ps = (PackageSetting) pkg.mExtras; 16781 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16782 } 16783 } 16784 16785 private void resetNetworkPolicies(int userId) { 16786 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16787 } 16788 16789 /** 16790 * Reverts user permission state changes (permissions and flags). 16791 * 16792 * @param ps The package for which to reset. 16793 * @param userId The device user for which to do a reset. 16794 */ 16795 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16796 final PackageSetting ps, final int userId) { 16797 if (ps.pkg == null) { 16798 return; 16799 } 16800 16801 // These are flags that can change base on user actions. 16802 final int userSettableMask = FLAG_PERMISSION_USER_SET 16803 | FLAG_PERMISSION_USER_FIXED 16804 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16805 | FLAG_PERMISSION_REVIEW_REQUIRED; 16806 16807 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16808 | FLAG_PERMISSION_POLICY_FIXED; 16809 16810 boolean writeInstallPermissions = false; 16811 boolean writeRuntimePermissions = false; 16812 16813 final int permissionCount = ps.pkg.requestedPermissions.size(); 16814 for (int i = 0; i < permissionCount; i++) { 16815 String permission = ps.pkg.requestedPermissions.get(i); 16816 16817 BasePermission bp = mSettings.mPermissions.get(permission); 16818 if (bp == null) { 16819 continue; 16820 } 16821 16822 // If shared user we just reset the state to which only this app contributed. 16823 if (ps.sharedUser != null) { 16824 boolean used = false; 16825 final int packageCount = ps.sharedUser.packages.size(); 16826 for (int j = 0; j < packageCount; j++) { 16827 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16828 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16829 && pkg.pkg.requestedPermissions.contains(permission)) { 16830 used = true; 16831 break; 16832 } 16833 } 16834 if (used) { 16835 continue; 16836 } 16837 } 16838 16839 PermissionsState permissionsState = ps.getPermissionsState(); 16840 16841 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16842 16843 // Always clear the user settable flags. 16844 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16845 bp.name) != null; 16846 // If permission review is enabled and this is a legacy app, mark the 16847 // permission as requiring a review as this is the initial state. 16848 int flags = 0; 16849 if (mPermissionReviewRequired 16850 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16851 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16852 } 16853 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16854 if (hasInstallState) { 16855 writeInstallPermissions = true; 16856 } else { 16857 writeRuntimePermissions = true; 16858 } 16859 } 16860 16861 // Below is only runtime permission handling. 16862 if (!bp.isRuntime()) { 16863 continue; 16864 } 16865 16866 // Never clobber system or policy. 16867 if ((oldFlags & policyOrSystemFlags) != 0) { 16868 continue; 16869 } 16870 16871 // If this permission was granted by default, make sure it is. 16872 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16873 if (permissionsState.grantRuntimePermission(bp, userId) 16874 != PERMISSION_OPERATION_FAILURE) { 16875 writeRuntimePermissions = true; 16876 } 16877 // If permission review is enabled the permissions for a legacy apps 16878 // are represented as constantly granted runtime ones, so don't revoke. 16879 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16880 // Otherwise, reset the permission. 16881 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16882 switch (revokeResult) { 16883 case PERMISSION_OPERATION_SUCCESS: 16884 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16885 writeRuntimePermissions = true; 16886 final int appId = ps.appId; 16887 mHandler.post(new Runnable() { 16888 @Override 16889 public void run() { 16890 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16891 } 16892 }); 16893 } break; 16894 } 16895 } 16896 } 16897 16898 // Synchronously write as we are taking permissions away. 16899 if (writeRuntimePermissions) { 16900 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16901 } 16902 16903 // Synchronously write as we are taking permissions away. 16904 if (writeInstallPermissions) { 16905 mSettings.writeLPr(); 16906 } 16907 } 16908 16909 /** 16910 * Remove entries from the keystore daemon. Will only remove it if the 16911 * {@code appId} is valid. 16912 */ 16913 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16914 if (appId < 0) { 16915 return; 16916 } 16917 16918 final KeyStore keyStore = KeyStore.getInstance(); 16919 if (keyStore != null) { 16920 if (userId == UserHandle.USER_ALL) { 16921 for (final int individual : sUserManager.getUserIds()) { 16922 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16923 } 16924 } else { 16925 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16926 } 16927 } else { 16928 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16929 } 16930 } 16931 16932 @Override 16933 public void deleteApplicationCacheFiles(final String packageName, 16934 final IPackageDataObserver observer) { 16935 final int userId = UserHandle.getCallingUserId(); 16936 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16937 } 16938 16939 @Override 16940 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16941 final IPackageDataObserver observer) { 16942 mContext.enforceCallingOrSelfPermission( 16943 android.Manifest.permission.DELETE_CACHE_FILES, null); 16944 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16945 /* requireFullPermission= */ true, /* checkShell= */ false, 16946 "delete application cache files"); 16947 16948 final PackageParser.Package pkg; 16949 synchronized (mPackages) { 16950 pkg = mPackages.get(packageName); 16951 } 16952 16953 // Queue up an async operation since the package deletion may take a little while. 16954 mHandler.post(new Runnable() { 16955 public void run() { 16956 synchronized (mInstallLock) { 16957 final int flags = StorageManager.FLAG_STORAGE_DE 16958 | StorageManager.FLAG_STORAGE_CE; 16959 // We're only clearing cache files, so we don't care if the 16960 // app is unfrozen and still able to run 16961 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16962 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16963 } 16964 clearExternalStorageDataSync(packageName, userId, false); 16965 if (observer != null) { 16966 try { 16967 observer.onRemoveCompleted(packageName, true); 16968 } catch (RemoteException e) { 16969 Log.i(TAG, "Observer no longer exists."); 16970 } 16971 } 16972 } 16973 }); 16974 } 16975 16976 @Override 16977 public void getPackageSizeInfo(final String packageName, int userHandle, 16978 final IPackageStatsObserver observer) { 16979 mContext.enforceCallingOrSelfPermission( 16980 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16981 if (packageName == null) { 16982 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16983 } 16984 16985 PackageStats stats = new PackageStats(packageName, userHandle); 16986 16987 /* 16988 * Queue up an async operation since the package measurement may take a 16989 * little while. 16990 */ 16991 Message msg = mHandler.obtainMessage(INIT_COPY); 16992 msg.obj = new MeasureParams(stats, observer); 16993 mHandler.sendMessage(msg); 16994 } 16995 16996 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16997 final PackageSetting ps; 16998 synchronized (mPackages) { 16999 ps = mSettings.mPackages.get(packageName); 17000 if (ps == null) { 17001 Slog.w(TAG, "Failed to find settings for " + packageName); 17002 return false; 17003 } 17004 } 17005 try { 17006 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 17007 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 17008 ps.getCeDataInode(userId), ps.codePathString, stats); 17009 } catch (InstallerException e) { 17010 Slog.w(TAG, String.valueOf(e)); 17011 return false; 17012 } 17013 17014 // For now, ignore code size of packages on system partition 17015 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 17016 stats.codeSize = 0; 17017 } 17018 17019 return true; 17020 } 17021 17022 private int getUidTargetSdkVersionLockedLPr(int uid) { 17023 Object obj = mSettings.getUserIdLPr(uid); 17024 if (obj instanceof SharedUserSetting) { 17025 final SharedUserSetting sus = (SharedUserSetting) obj; 17026 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 17027 final Iterator<PackageSetting> it = sus.packages.iterator(); 17028 while (it.hasNext()) { 17029 final PackageSetting ps = it.next(); 17030 if (ps.pkg != null) { 17031 int v = ps.pkg.applicationInfo.targetSdkVersion; 17032 if (v < vers) vers = v; 17033 } 17034 } 17035 return vers; 17036 } else if (obj instanceof PackageSetting) { 17037 final PackageSetting ps = (PackageSetting) obj; 17038 if (ps.pkg != null) { 17039 return ps.pkg.applicationInfo.targetSdkVersion; 17040 } 17041 } 17042 return Build.VERSION_CODES.CUR_DEVELOPMENT; 17043 } 17044 17045 @Override 17046 public void addPreferredActivity(IntentFilter filter, int match, 17047 ComponentName[] set, ComponentName activity, int userId) { 17048 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17049 "Adding preferred"); 17050 } 17051 17052 private void addPreferredActivityInternal(IntentFilter filter, int match, 17053 ComponentName[] set, ComponentName activity, boolean always, int userId, 17054 String opname) { 17055 // writer 17056 int callingUid = Binder.getCallingUid(); 17057 enforceCrossUserPermission(callingUid, userId, 17058 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 17059 if (filter.countActions() == 0) { 17060 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17061 return; 17062 } 17063 synchronized (mPackages) { 17064 if (mContext.checkCallingOrSelfPermission( 17065 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17066 != PackageManager.PERMISSION_GRANTED) { 17067 if (getUidTargetSdkVersionLockedLPr(callingUid) 17068 < Build.VERSION_CODES.FROYO) { 17069 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 17070 + callingUid); 17071 return; 17072 } 17073 mContext.enforceCallingOrSelfPermission( 17074 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17075 } 17076 17077 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 17078 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 17079 + userId + ":"); 17080 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17081 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 17082 scheduleWritePackageRestrictionsLocked(userId); 17083 postPreferredActivityChangedBroadcast(userId); 17084 } 17085 } 17086 17087 private void postPreferredActivityChangedBroadcast(int userId) { 17088 mHandler.post(() -> { 17089 final IActivityManager am = ActivityManagerNative.getDefault(); 17090 if (am == null) { 17091 return; 17092 } 17093 17094 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 17095 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17096 try { 17097 am.broadcastIntent(null, intent, null, null, 17098 0, null, null, null, android.app.AppOpsManager.OP_NONE, 17099 null, false, false, userId); 17100 } catch (RemoteException e) { 17101 } 17102 }); 17103 } 17104 17105 @Override 17106 public void replacePreferredActivity(IntentFilter filter, int match, 17107 ComponentName[] set, ComponentName activity, int userId) { 17108 if (filter.countActions() != 1) { 17109 throw new IllegalArgumentException( 17110 "replacePreferredActivity expects filter to have only 1 action."); 17111 } 17112 if (filter.countDataAuthorities() != 0 17113 || filter.countDataPaths() != 0 17114 || filter.countDataSchemes() > 1 17115 || filter.countDataTypes() != 0) { 17116 throw new IllegalArgumentException( 17117 "replacePreferredActivity expects filter to have no data authorities, " + 17118 "paths, or types; and at most one scheme."); 17119 } 17120 17121 final int callingUid = Binder.getCallingUid(); 17122 enforceCrossUserPermission(callingUid, userId, 17123 true /* requireFullPermission */, false /* checkShell */, 17124 "replace preferred activity"); 17125 synchronized (mPackages) { 17126 if (mContext.checkCallingOrSelfPermission( 17127 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17128 != PackageManager.PERMISSION_GRANTED) { 17129 if (getUidTargetSdkVersionLockedLPr(callingUid) 17130 < Build.VERSION_CODES.FROYO) { 17131 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 17132 + Binder.getCallingUid()); 17133 return; 17134 } 17135 mContext.enforceCallingOrSelfPermission( 17136 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17137 } 17138 17139 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17140 if (pir != null) { 17141 // Get all of the existing entries that exactly match this filter. 17142 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 17143 if (existing != null && existing.size() == 1) { 17144 PreferredActivity cur = existing.get(0); 17145 if (DEBUG_PREFERRED) { 17146 Slog.i(TAG, "Checking replace of preferred:"); 17147 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17148 if (!cur.mPref.mAlways) { 17149 Slog.i(TAG, " -- CUR; not mAlways!"); 17150 } else { 17151 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 17152 Slog.i(TAG, " -- CUR: mSet=" 17153 + Arrays.toString(cur.mPref.mSetComponents)); 17154 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 17155 Slog.i(TAG, " -- NEW: mMatch=" 17156 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 17157 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17158 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17159 } 17160 } 17161 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17162 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17163 && cur.mPref.sameSet(set)) { 17164 // Setting the preferred activity to what it happens to be already 17165 if (DEBUG_PREFERRED) { 17166 Slog.i(TAG, "Replacing with same preferred activity " 17167 + cur.mPref.mShortComponent + " for user " 17168 + userId + ":"); 17169 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17170 } 17171 return; 17172 } 17173 } 17174 17175 if (existing != null) { 17176 if (DEBUG_PREFERRED) { 17177 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17178 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17179 } 17180 for (int i = 0; i < existing.size(); i++) { 17181 PreferredActivity pa = existing.get(i); 17182 if (DEBUG_PREFERRED) { 17183 Slog.i(TAG, "Removing existing preferred activity " 17184 + pa.mPref.mComponent + ":"); 17185 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17186 } 17187 pir.removeFilter(pa); 17188 } 17189 } 17190 } 17191 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17192 "Replacing preferred"); 17193 } 17194 } 17195 17196 @Override 17197 public void clearPackagePreferredActivities(String packageName) { 17198 final int uid = Binder.getCallingUid(); 17199 // writer 17200 synchronized (mPackages) { 17201 PackageParser.Package pkg = mPackages.get(packageName); 17202 if (pkg == null || pkg.applicationInfo.uid != uid) { 17203 if (mContext.checkCallingOrSelfPermission( 17204 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17205 != PackageManager.PERMISSION_GRANTED) { 17206 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17207 < Build.VERSION_CODES.FROYO) { 17208 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17209 + Binder.getCallingUid()); 17210 return; 17211 } 17212 mContext.enforceCallingOrSelfPermission( 17213 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17214 } 17215 } 17216 17217 int user = UserHandle.getCallingUserId(); 17218 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17219 scheduleWritePackageRestrictionsLocked(user); 17220 } 17221 } 17222 } 17223 17224 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17225 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17226 ArrayList<PreferredActivity> removed = null; 17227 boolean changed = false; 17228 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17229 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17230 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17231 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17232 continue; 17233 } 17234 Iterator<PreferredActivity> it = pir.filterIterator(); 17235 while (it.hasNext()) { 17236 PreferredActivity pa = it.next(); 17237 // Mark entry for removal only if it matches the package name 17238 // and the entry is of type "always". 17239 if (packageName == null || 17240 (pa.mPref.mComponent.getPackageName().equals(packageName) 17241 && pa.mPref.mAlways)) { 17242 if (removed == null) { 17243 removed = new ArrayList<PreferredActivity>(); 17244 } 17245 removed.add(pa); 17246 } 17247 } 17248 if (removed != null) { 17249 for (int j=0; j<removed.size(); j++) { 17250 PreferredActivity pa = removed.get(j); 17251 pir.removeFilter(pa); 17252 } 17253 changed = true; 17254 } 17255 } 17256 if (changed) { 17257 postPreferredActivityChangedBroadcast(userId); 17258 } 17259 return changed; 17260 } 17261 17262 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17263 private void clearIntentFilterVerificationsLPw(int userId) { 17264 final int packageCount = mPackages.size(); 17265 for (int i = 0; i < packageCount; i++) { 17266 PackageParser.Package pkg = mPackages.valueAt(i); 17267 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17268 } 17269 } 17270 17271 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17272 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17273 if (userId == UserHandle.USER_ALL) { 17274 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17275 sUserManager.getUserIds())) { 17276 for (int oneUserId : sUserManager.getUserIds()) { 17277 scheduleWritePackageRestrictionsLocked(oneUserId); 17278 } 17279 } 17280 } else { 17281 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17282 scheduleWritePackageRestrictionsLocked(userId); 17283 } 17284 } 17285 } 17286 17287 void clearDefaultBrowserIfNeeded(String packageName) { 17288 for (int oneUserId : sUserManager.getUserIds()) { 17289 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17290 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17291 if (packageName.equals(defaultBrowserPackageName)) { 17292 setDefaultBrowserPackageName(null, oneUserId); 17293 } 17294 } 17295 } 17296 17297 @Override 17298 public void resetApplicationPreferences(int userId) { 17299 mContext.enforceCallingOrSelfPermission( 17300 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17301 final long identity = Binder.clearCallingIdentity(); 17302 // writer 17303 try { 17304 synchronized (mPackages) { 17305 clearPackagePreferredActivitiesLPw(null, userId); 17306 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17307 // TODO: We have to reset the default SMS and Phone. This requires 17308 // significant refactoring to keep all default apps in the package 17309 // manager (cleaner but more work) or have the services provide 17310 // callbacks to the package manager to request a default app reset. 17311 applyFactoryDefaultBrowserLPw(userId); 17312 clearIntentFilterVerificationsLPw(userId); 17313 primeDomainVerificationsLPw(userId); 17314 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17315 scheduleWritePackageRestrictionsLocked(userId); 17316 } 17317 resetNetworkPolicies(userId); 17318 } finally { 17319 Binder.restoreCallingIdentity(identity); 17320 } 17321 } 17322 17323 @Override 17324 public int getPreferredActivities(List<IntentFilter> outFilters, 17325 List<ComponentName> outActivities, String packageName) { 17326 17327 int num = 0; 17328 final int userId = UserHandle.getCallingUserId(); 17329 // reader 17330 synchronized (mPackages) { 17331 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17332 if (pir != null) { 17333 final Iterator<PreferredActivity> it = pir.filterIterator(); 17334 while (it.hasNext()) { 17335 final PreferredActivity pa = it.next(); 17336 if (packageName == null 17337 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17338 && pa.mPref.mAlways)) { 17339 if (outFilters != null) { 17340 outFilters.add(new IntentFilter(pa)); 17341 } 17342 if (outActivities != null) { 17343 outActivities.add(pa.mPref.mComponent); 17344 } 17345 } 17346 } 17347 } 17348 } 17349 17350 return num; 17351 } 17352 17353 @Override 17354 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17355 int userId) { 17356 int callingUid = Binder.getCallingUid(); 17357 if (callingUid != Process.SYSTEM_UID) { 17358 throw new SecurityException( 17359 "addPersistentPreferredActivity can only be run by the system"); 17360 } 17361 if (filter.countActions() == 0) { 17362 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17363 return; 17364 } 17365 synchronized (mPackages) { 17366 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17367 ":"); 17368 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17369 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17370 new PersistentPreferredActivity(filter, activity)); 17371 scheduleWritePackageRestrictionsLocked(userId); 17372 postPreferredActivityChangedBroadcast(userId); 17373 } 17374 } 17375 17376 @Override 17377 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17378 int callingUid = Binder.getCallingUid(); 17379 if (callingUid != Process.SYSTEM_UID) { 17380 throw new SecurityException( 17381 "clearPackagePersistentPreferredActivities can only be run by the system"); 17382 } 17383 ArrayList<PersistentPreferredActivity> removed = null; 17384 boolean changed = false; 17385 synchronized (mPackages) { 17386 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17387 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17388 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17389 .valueAt(i); 17390 if (userId != thisUserId) { 17391 continue; 17392 } 17393 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17394 while (it.hasNext()) { 17395 PersistentPreferredActivity ppa = it.next(); 17396 // Mark entry for removal only if it matches the package name. 17397 if (ppa.mComponent.getPackageName().equals(packageName)) { 17398 if (removed == null) { 17399 removed = new ArrayList<PersistentPreferredActivity>(); 17400 } 17401 removed.add(ppa); 17402 } 17403 } 17404 if (removed != null) { 17405 for (int j=0; j<removed.size(); j++) { 17406 PersistentPreferredActivity ppa = removed.get(j); 17407 ppir.removeFilter(ppa); 17408 } 17409 changed = true; 17410 } 17411 } 17412 17413 if (changed) { 17414 scheduleWritePackageRestrictionsLocked(userId); 17415 postPreferredActivityChangedBroadcast(userId); 17416 } 17417 } 17418 } 17419 17420 /** 17421 * Common machinery for picking apart a restored XML blob and passing 17422 * it to a caller-supplied functor to be applied to the running system. 17423 */ 17424 private void restoreFromXml(XmlPullParser parser, int userId, 17425 String expectedStartTag, BlobXmlRestorer functor) 17426 throws IOException, XmlPullParserException { 17427 int type; 17428 while ((type = parser.next()) != XmlPullParser.START_TAG 17429 && type != XmlPullParser.END_DOCUMENT) { 17430 } 17431 if (type != XmlPullParser.START_TAG) { 17432 // oops didn't find a start tag?! 17433 if (DEBUG_BACKUP) { 17434 Slog.e(TAG, "Didn't find start tag during restore"); 17435 } 17436 return; 17437 } 17438Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17439 // this is supposed to be TAG_PREFERRED_BACKUP 17440 if (!expectedStartTag.equals(parser.getName())) { 17441 if (DEBUG_BACKUP) { 17442 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17443 } 17444 return; 17445 } 17446 17447 // skip interfering stuff, then we're aligned with the backing implementation 17448 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17449Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17450 functor.apply(parser, userId); 17451 } 17452 17453 private interface BlobXmlRestorer { 17454 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17455 } 17456 17457 /** 17458 * Non-Binder method, support for the backup/restore mechanism: write the 17459 * full set of preferred activities in its canonical XML format. Returns the 17460 * XML output as a byte array, or null if there is none. 17461 */ 17462 @Override 17463 public byte[] getPreferredActivityBackup(int userId) { 17464 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17465 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17466 } 17467 17468 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17469 try { 17470 final XmlSerializer serializer = new FastXmlSerializer(); 17471 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17472 serializer.startDocument(null, true); 17473 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17474 17475 synchronized (mPackages) { 17476 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17477 } 17478 17479 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17480 serializer.endDocument(); 17481 serializer.flush(); 17482 } catch (Exception e) { 17483 if (DEBUG_BACKUP) { 17484 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17485 } 17486 return null; 17487 } 17488 17489 return dataStream.toByteArray(); 17490 } 17491 17492 @Override 17493 public void restorePreferredActivities(byte[] backup, int userId) { 17494 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17495 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17496 } 17497 17498 try { 17499 final XmlPullParser parser = Xml.newPullParser(); 17500 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17501 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17502 new BlobXmlRestorer() { 17503 @Override 17504 public void apply(XmlPullParser parser, int userId) 17505 throws XmlPullParserException, IOException { 17506 synchronized (mPackages) { 17507 mSettings.readPreferredActivitiesLPw(parser, userId); 17508 } 17509 } 17510 } ); 17511 } catch (Exception e) { 17512 if (DEBUG_BACKUP) { 17513 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17514 } 17515 } 17516 } 17517 17518 /** 17519 * Non-Binder method, support for the backup/restore mechanism: write the 17520 * default browser (etc) settings in its canonical XML format. Returns the default 17521 * browser XML representation as a byte array, or null if there is none. 17522 */ 17523 @Override 17524 public byte[] getDefaultAppsBackup(int userId) { 17525 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17526 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17527 } 17528 17529 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17530 try { 17531 final XmlSerializer serializer = new FastXmlSerializer(); 17532 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17533 serializer.startDocument(null, true); 17534 serializer.startTag(null, TAG_DEFAULT_APPS); 17535 17536 synchronized (mPackages) { 17537 mSettings.writeDefaultAppsLPr(serializer, userId); 17538 } 17539 17540 serializer.endTag(null, TAG_DEFAULT_APPS); 17541 serializer.endDocument(); 17542 serializer.flush(); 17543 } catch (Exception e) { 17544 if (DEBUG_BACKUP) { 17545 Slog.e(TAG, "Unable to write default apps for backup", e); 17546 } 17547 return null; 17548 } 17549 17550 return dataStream.toByteArray(); 17551 } 17552 17553 @Override 17554 public void restoreDefaultApps(byte[] backup, int userId) { 17555 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17556 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17557 } 17558 17559 try { 17560 final XmlPullParser parser = Xml.newPullParser(); 17561 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17562 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17563 new BlobXmlRestorer() { 17564 @Override 17565 public void apply(XmlPullParser parser, int userId) 17566 throws XmlPullParserException, IOException { 17567 synchronized (mPackages) { 17568 mSettings.readDefaultAppsLPw(parser, userId); 17569 } 17570 } 17571 } ); 17572 } catch (Exception e) { 17573 if (DEBUG_BACKUP) { 17574 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17575 } 17576 } 17577 } 17578 17579 @Override 17580 public byte[] getIntentFilterVerificationBackup(int userId) { 17581 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17582 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17583 } 17584 17585 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17586 try { 17587 final XmlSerializer serializer = new FastXmlSerializer(); 17588 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17589 serializer.startDocument(null, true); 17590 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17591 17592 synchronized (mPackages) { 17593 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17594 } 17595 17596 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17597 serializer.endDocument(); 17598 serializer.flush(); 17599 } catch (Exception e) { 17600 if (DEBUG_BACKUP) { 17601 Slog.e(TAG, "Unable to write default apps for backup", e); 17602 } 17603 return null; 17604 } 17605 17606 return dataStream.toByteArray(); 17607 } 17608 17609 @Override 17610 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17611 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17612 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17613 } 17614 17615 try { 17616 final XmlPullParser parser = Xml.newPullParser(); 17617 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17618 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17619 new BlobXmlRestorer() { 17620 @Override 17621 public void apply(XmlPullParser parser, int userId) 17622 throws XmlPullParserException, IOException { 17623 synchronized (mPackages) { 17624 mSettings.readAllDomainVerificationsLPr(parser, userId); 17625 mSettings.writeLPr(); 17626 } 17627 } 17628 } ); 17629 } catch (Exception e) { 17630 if (DEBUG_BACKUP) { 17631 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17632 } 17633 } 17634 } 17635 17636 @Override 17637 public byte[] getPermissionGrantBackup(int userId) { 17638 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17639 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17640 } 17641 17642 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17643 try { 17644 final XmlSerializer serializer = new FastXmlSerializer(); 17645 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17646 serializer.startDocument(null, true); 17647 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17648 17649 synchronized (mPackages) { 17650 serializeRuntimePermissionGrantsLPr(serializer, userId); 17651 } 17652 17653 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17654 serializer.endDocument(); 17655 serializer.flush(); 17656 } catch (Exception e) { 17657 if (DEBUG_BACKUP) { 17658 Slog.e(TAG, "Unable to write default apps for backup", e); 17659 } 17660 return null; 17661 } 17662 17663 return dataStream.toByteArray(); 17664 } 17665 17666 @Override 17667 public void restorePermissionGrants(byte[] backup, int userId) { 17668 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17669 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17670 } 17671 17672 try { 17673 final XmlPullParser parser = Xml.newPullParser(); 17674 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17675 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17676 new BlobXmlRestorer() { 17677 @Override 17678 public void apply(XmlPullParser parser, int userId) 17679 throws XmlPullParserException, IOException { 17680 synchronized (mPackages) { 17681 processRestoredPermissionGrantsLPr(parser, userId); 17682 } 17683 } 17684 } ); 17685 } catch (Exception e) { 17686 if (DEBUG_BACKUP) { 17687 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17688 } 17689 } 17690 } 17691 17692 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17693 throws IOException { 17694 serializer.startTag(null, TAG_ALL_GRANTS); 17695 17696 final int N = mSettings.mPackages.size(); 17697 for (int i = 0; i < N; i++) { 17698 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17699 boolean pkgGrantsKnown = false; 17700 17701 PermissionsState packagePerms = ps.getPermissionsState(); 17702 17703 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17704 final int grantFlags = state.getFlags(); 17705 // only look at grants that are not system/policy fixed 17706 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17707 final boolean isGranted = state.isGranted(); 17708 // And only back up the user-twiddled state bits 17709 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17710 final String packageName = mSettings.mPackages.keyAt(i); 17711 if (!pkgGrantsKnown) { 17712 serializer.startTag(null, TAG_GRANT); 17713 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17714 pkgGrantsKnown = true; 17715 } 17716 17717 final boolean userSet = 17718 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17719 final boolean userFixed = 17720 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17721 final boolean revoke = 17722 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17723 17724 serializer.startTag(null, TAG_PERMISSION); 17725 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17726 if (isGranted) { 17727 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17728 } 17729 if (userSet) { 17730 serializer.attribute(null, ATTR_USER_SET, "true"); 17731 } 17732 if (userFixed) { 17733 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17734 } 17735 if (revoke) { 17736 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17737 } 17738 serializer.endTag(null, TAG_PERMISSION); 17739 } 17740 } 17741 } 17742 17743 if (pkgGrantsKnown) { 17744 serializer.endTag(null, TAG_GRANT); 17745 } 17746 } 17747 17748 serializer.endTag(null, TAG_ALL_GRANTS); 17749 } 17750 17751 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17752 throws XmlPullParserException, IOException { 17753 String pkgName = null; 17754 int outerDepth = parser.getDepth(); 17755 int type; 17756 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17757 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17758 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17759 continue; 17760 } 17761 17762 final String tagName = parser.getName(); 17763 if (tagName.equals(TAG_GRANT)) { 17764 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17765 if (DEBUG_BACKUP) { 17766 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17767 } 17768 } else if (tagName.equals(TAG_PERMISSION)) { 17769 17770 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17771 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17772 17773 int newFlagSet = 0; 17774 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17775 newFlagSet |= FLAG_PERMISSION_USER_SET; 17776 } 17777 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17778 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17779 } 17780 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17781 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17782 } 17783 if (DEBUG_BACKUP) { 17784 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17785 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17786 } 17787 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17788 if (ps != null) { 17789 // Already installed so we apply the grant immediately 17790 if (DEBUG_BACKUP) { 17791 Slog.v(TAG, " + already installed; applying"); 17792 } 17793 PermissionsState perms = ps.getPermissionsState(); 17794 BasePermission bp = mSettings.mPermissions.get(permName); 17795 if (bp != null) { 17796 if (isGranted) { 17797 perms.grantRuntimePermission(bp, userId); 17798 } 17799 if (newFlagSet != 0) { 17800 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17801 } 17802 } 17803 } else { 17804 // Need to wait for post-restore install to apply the grant 17805 if (DEBUG_BACKUP) { 17806 Slog.v(TAG, " - not yet installed; saving for later"); 17807 } 17808 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17809 isGranted, newFlagSet, userId); 17810 } 17811 } else { 17812 PackageManagerService.reportSettingsProblem(Log.WARN, 17813 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17814 XmlUtils.skipCurrentTag(parser); 17815 } 17816 } 17817 17818 scheduleWriteSettingsLocked(); 17819 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17820 } 17821 17822 @Override 17823 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17824 int sourceUserId, int targetUserId, int flags) { 17825 mContext.enforceCallingOrSelfPermission( 17826 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17827 int callingUid = Binder.getCallingUid(); 17828 enforceOwnerRights(ownerPackage, callingUid); 17829 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17830 if (intentFilter.countActions() == 0) { 17831 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17832 return; 17833 } 17834 synchronized (mPackages) { 17835 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17836 ownerPackage, targetUserId, flags); 17837 CrossProfileIntentResolver resolver = 17838 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17839 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17840 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17841 if (existing != null) { 17842 int size = existing.size(); 17843 for (int i = 0; i < size; i++) { 17844 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17845 return; 17846 } 17847 } 17848 } 17849 resolver.addFilter(newFilter); 17850 scheduleWritePackageRestrictionsLocked(sourceUserId); 17851 } 17852 } 17853 17854 @Override 17855 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17856 mContext.enforceCallingOrSelfPermission( 17857 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17858 int callingUid = Binder.getCallingUid(); 17859 enforceOwnerRights(ownerPackage, callingUid); 17860 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17861 synchronized (mPackages) { 17862 CrossProfileIntentResolver resolver = 17863 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17864 ArraySet<CrossProfileIntentFilter> set = 17865 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17866 for (CrossProfileIntentFilter filter : set) { 17867 if (filter.getOwnerPackage().equals(ownerPackage)) { 17868 resolver.removeFilter(filter); 17869 } 17870 } 17871 scheduleWritePackageRestrictionsLocked(sourceUserId); 17872 } 17873 } 17874 17875 // Enforcing that callingUid is owning pkg on userId 17876 private void enforceOwnerRights(String pkg, int callingUid) { 17877 // The system owns everything. 17878 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17879 return; 17880 } 17881 int callingUserId = UserHandle.getUserId(callingUid); 17882 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17883 if (pi == null) { 17884 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17885 + callingUserId); 17886 } 17887 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17888 throw new SecurityException("Calling uid " + callingUid 17889 + " does not own package " + pkg); 17890 } 17891 } 17892 17893 @Override 17894 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17895 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17896 } 17897 17898 private Intent getHomeIntent() { 17899 Intent intent = new Intent(Intent.ACTION_MAIN); 17900 intent.addCategory(Intent.CATEGORY_HOME); 17901 intent.addCategory(Intent.CATEGORY_DEFAULT); 17902 return intent; 17903 } 17904 17905 private IntentFilter getHomeFilter() { 17906 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17907 filter.addCategory(Intent.CATEGORY_HOME); 17908 filter.addCategory(Intent.CATEGORY_DEFAULT); 17909 return filter; 17910 } 17911 17912 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17913 int userId) { 17914 Intent intent = getHomeIntent(); 17915 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17916 PackageManager.GET_META_DATA, userId); 17917 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17918 true, false, false, userId); 17919 17920 allHomeCandidates.clear(); 17921 if (list != null) { 17922 for (ResolveInfo ri : list) { 17923 allHomeCandidates.add(ri); 17924 } 17925 } 17926 return (preferred == null || preferred.activityInfo == null) 17927 ? null 17928 : new ComponentName(preferred.activityInfo.packageName, 17929 preferred.activityInfo.name); 17930 } 17931 17932 @Override 17933 public void setHomeActivity(ComponentName comp, int userId) { 17934 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17935 getHomeActivitiesAsUser(homeActivities, userId); 17936 17937 boolean found = false; 17938 17939 final int size = homeActivities.size(); 17940 final ComponentName[] set = new ComponentName[size]; 17941 for (int i = 0; i < size; i++) { 17942 final ResolveInfo candidate = homeActivities.get(i); 17943 final ActivityInfo info = candidate.activityInfo; 17944 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17945 set[i] = activityName; 17946 if (!found && activityName.equals(comp)) { 17947 found = true; 17948 } 17949 } 17950 if (!found) { 17951 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17952 + userId); 17953 } 17954 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17955 set, comp, userId); 17956 } 17957 17958 private @Nullable String getSetupWizardPackageName() { 17959 final Intent intent = new Intent(Intent.ACTION_MAIN); 17960 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17961 17962 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17963 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17964 | MATCH_DISABLED_COMPONENTS, 17965 UserHandle.myUserId()); 17966 if (matches.size() == 1) { 17967 return matches.get(0).getComponentInfo().packageName; 17968 } else { 17969 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17970 + ": matches=" + matches); 17971 return null; 17972 } 17973 } 17974 17975 private @Nullable String getStorageManagerPackageName() { 17976 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 17977 17978 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17979 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17980 | MATCH_DISABLED_COMPONENTS, 17981 UserHandle.myUserId()); 17982 if (matches.size() == 1) { 17983 return matches.get(0).getComponentInfo().packageName; 17984 } else { 17985 Slog.e(TAG, "There should probably be exactly one storage manager; found " 17986 + matches.size() + ": matches=" + matches); 17987 return null; 17988 } 17989 } 17990 17991 @Override 17992 public void setApplicationEnabledSetting(String appPackageName, 17993 int newState, int flags, int userId, String callingPackage) { 17994 if (!sUserManager.exists(userId)) return; 17995 if (callingPackage == null) { 17996 callingPackage = Integer.toString(Binder.getCallingUid()); 17997 } 17998 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17999 } 18000 18001 @Override 18002 public void setComponentEnabledSetting(ComponentName componentName, 18003 int newState, int flags, int userId) { 18004 if (!sUserManager.exists(userId)) return; 18005 setEnabledSetting(componentName.getPackageName(), 18006 componentName.getClassName(), newState, flags, userId, null); 18007 } 18008 18009 private void setEnabledSetting(final String packageName, String className, int newState, 18010 final int flags, int userId, String callingPackage) { 18011 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 18012 || newState == COMPONENT_ENABLED_STATE_ENABLED 18013 || newState == COMPONENT_ENABLED_STATE_DISABLED 18014 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18015 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 18016 throw new IllegalArgumentException("Invalid new component state: " 18017 + newState); 18018 } 18019 PackageSetting pkgSetting; 18020 final int uid = Binder.getCallingUid(); 18021 final int permission; 18022 if (uid == Process.SYSTEM_UID) { 18023 permission = PackageManager.PERMISSION_GRANTED; 18024 } else { 18025 permission = mContext.checkCallingOrSelfPermission( 18026 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18027 } 18028 enforceCrossUserPermission(uid, userId, 18029 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 18030 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18031 boolean sendNow = false; 18032 boolean isApp = (className == null); 18033 String componentName = isApp ? packageName : className; 18034 int packageUid = -1; 18035 ArrayList<String> components; 18036 18037 // writer 18038 synchronized (mPackages) { 18039 pkgSetting = mSettings.mPackages.get(packageName); 18040 if (pkgSetting == null) { 18041 if (className == null) { 18042 throw new IllegalArgumentException("Unknown package: " + packageName); 18043 } 18044 throw new IllegalArgumentException( 18045 "Unknown component: " + packageName + "/" + className); 18046 } 18047 } 18048 18049 // Limit who can change which apps 18050 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 18051 // Don't allow apps that don't have permission to modify other apps 18052 if (!allowedByPermission) { 18053 throw new SecurityException( 18054 "Permission Denial: attempt to change component state from pid=" 18055 + Binder.getCallingPid() 18056 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 18057 } 18058 // Don't allow changing protected packages. 18059 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 18060 throw new SecurityException("Cannot disable a protected package: " + packageName); 18061 } 18062 } 18063 18064 synchronized (mPackages) { 18065 if (uid == Process.SHELL_UID) { 18066 // Shell can only change whole packages between ENABLED and DISABLED_USER states 18067 int oldState = pkgSetting.getEnabled(userId); 18068 if (className == null 18069 && 18070 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 18071 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 18072 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 18073 && 18074 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18075 || newState == COMPONENT_ENABLED_STATE_DEFAULT 18076 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 18077 // ok 18078 } else { 18079 throw new SecurityException( 18080 "Shell cannot change component state for " + packageName + "/" 18081 + className + " to " + newState); 18082 } 18083 } 18084 if (className == null) { 18085 // We're dealing with an application/package level state change 18086 if (pkgSetting.getEnabled(userId) == newState) { 18087 // Nothing to do 18088 return; 18089 } 18090 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 18091 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 18092 // Don't care about who enables an app. 18093 callingPackage = null; 18094 } 18095 pkgSetting.setEnabled(newState, userId, callingPackage); 18096 // pkgSetting.pkg.mSetEnabled = newState; 18097 } else { 18098 // We're dealing with a component level state change 18099 // First, verify that this is a valid class name. 18100 PackageParser.Package pkg = pkgSetting.pkg; 18101 if (pkg == null || !pkg.hasComponentClassName(className)) { 18102 if (pkg != null && 18103 pkg.applicationInfo.targetSdkVersion >= 18104 Build.VERSION_CODES.JELLY_BEAN) { 18105 throw new IllegalArgumentException("Component class " + className 18106 + " does not exist in " + packageName); 18107 } else { 18108 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 18109 + className + " does not exist in " + packageName); 18110 } 18111 } 18112 switch (newState) { 18113 case COMPONENT_ENABLED_STATE_ENABLED: 18114 if (!pkgSetting.enableComponentLPw(className, userId)) { 18115 return; 18116 } 18117 break; 18118 case COMPONENT_ENABLED_STATE_DISABLED: 18119 if (!pkgSetting.disableComponentLPw(className, userId)) { 18120 return; 18121 } 18122 break; 18123 case COMPONENT_ENABLED_STATE_DEFAULT: 18124 if (!pkgSetting.restoreComponentLPw(className, userId)) { 18125 return; 18126 } 18127 break; 18128 default: 18129 Slog.e(TAG, "Invalid new component state: " + newState); 18130 return; 18131 } 18132 } 18133 scheduleWritePackageRestrictionsLocked(userId); 18134 components = mPendingBroadcasts.get(userId, packageName); 18135 final boolean newPackage = components == null; 18136 if (newPackage) { 18137 components = new ArrayList<String>(); 18138 } 18139 if (!components.contains(componentName)) { 18140 components.add(componentName); 18141 } 18142 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 18143 sendNow = true; 18144 // Purge entry from pending broadcast list if another one exists already 18145 // since we are sending one right away. 18146 mPendingBroadcasts.remove(userId, packageName); 18147 } else { 18148 if (newPackage) { 18149 mPendingBroadcasts.put(userId, packageName, components); 18150 } 18151 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 18152 // Schedule a message 18153 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 18154 } 18155 } 18156 } 18157 18158 long callingId = Binder.clearCallingIdentity(); 18159 try { 18160 if (sendNow) { 18161 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18162 sendPackageChangedBroadcast(packageName, 18163 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18164 } 18165 } finally { 18166 Binder.restoreCallingIdentity(callingId); 18167 } 18168 } 18169 18170 @Override 18171 public void flushPackageRestrictionsAsUser(int userId) { 18172 if (!sUserManager.exists(userId)) { 18173 return; 18174 } 18175 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18176 false /* checkShell */, "flushPackageRestrictions"); 18177 synchronized (mPackages) { 18178 mSettings.writePackageRestrictionsLPr(userId); 18179 mDirtyUsers.remove(userId); 18180 if (mDirtyUsers.isEmpty()) { 18181 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18182 } 18183 } 18184 } 18185 18186 private void sendPackageChangedBroadcast(String packageName, 18187 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18188 if (DEBUG_INSTALL) 18189 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18190 + componentNames); 18191 Bundle extras = new Bundle(4); 18192 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18193 String nameList[] = new String[componentNames.size()]; 18194 componentNames.toArray(nameList); 18195 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18196 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18197 extras.putInt(Intent.EXTRA_UID, packageUid); 18198 // If this is not reporting a change of the overall package, then only send it 18199 // to registered receivers. We don't want to launch a swath of apps for every 18200 // little component state change. 18201 final int flags = !componentNames.contains(packageName) 18202 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18203 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18204 new int[] {UserHandle.getUserId(packageUid)}); 18205 } 18206 18207 @Override 18208 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18209 if (!sUserManager.exists(userId)) return; 18210 final int uid = Binder.getCallingUid(); 18211 final int permission = mContext.checkCallingOrSelfPermission( 18212 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18213 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18214 enforceCrossUserPermission(uid, userId, 18215 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18216 // writer 18217 synchronized (mPackages) { 18218 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18219 allowedByPermission, uid, userId)) { 18220 scheduleWritePackageRestrictionsLocked(userId); 18221 } 18222 } 18223 } 18224 18225 @Override 18226 public String getInstallerPackageName(String packageName) { 18227 // reader 18228 synchronized (mPackages) { 18229 return mSettings.getInstallerPackageNameLPr(packageName); 18230 } 18231 } 18232 18233 public boolean isOrphaned(String packageName) { 18234 // reader 18235 synchronized (mPackages) { 18236 return mSettings.isOrphaned(packageName); 18237 } 18238 } 18239 18240 @Override 18241 public int getApplicationEnabledSetting(String packageName, int userId) { 18242 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18243 int uid = Binder.getCallingUid(); 18244 enforceCrossUserPermission(uid, userId, 18245 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18246 // reader 18247 synchronized (mPackages) { 18248 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18249 } 18250 } 18251 18252 @Override 18253 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18254 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18255 int uid = Binder.getCallingUid(); 18256 enforceCrossUserPermission(uid, userId, 18257 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18258 // reader 18259 synchronized (mPackages) { 18260 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18261 } 18262 } 18263 18264 @Override 18265 public void enterSafeMode() { 18266 enforceSystemOrRoot("Only the system can request entering safe mode"); 18267 18268 if (!mSystemReady) { 18269 mSafeMode = true; 18270 } 18271 } 18272 18273 @Override 18274 public void systemReady() { 18275 mSystemReady = true; 18276 18277 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18278 // disabled after already being started. 18279 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18280 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18281 18282 // Read the compatibilty setting when the system is ready. 18283 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18284 mContext.getContentResolver(), 18285 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18286 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18287 if (DEBUG_SETTINGS) { 18288 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18289 } 18290 18291 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18292 18293 synchronized (mPackages) { 18294 // Verify that all of the preferred activity components actually 18295 // exist. It is possible for applications to be updated and at 18296 // that point remove a previously declared activity component that 18297 // had been set as a preferred activity. We try to clean this up 18298 // the next time we encounter that preferred activity, but it is 18299 // possible for the user flow to never be able to return to that 18300 // situation so here we do a sanity check to make sure we haven't 18301 // left any junk around. 18302 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18303 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18304 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18305 removed.clear(); 18306 for (PreferredActivity pa : pir.filterSet()) { 18307 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18308 removed.add(pa); 18309 } 18310 } 18311 if (removed.size() > 0) { 18312 for (int r=0; r<removed.size(); r++) { 18313 PreferredActivity pa = removed.get(r); 18314 Slog.w(TAG, "Removing dangling preferred activity: " 18315 + pa.mPref.mComponent); 18316 pir.removeFilter(pa); 18317 } 18318 mSettings.writePackageRestrictionsLPr( 18319 mSettings.mPreferredActivities.keyAt(i)); 18320 } 18321 } 18322 18323 for (int userId : UserManagerService.getInstance().getUserIds()) { 18324 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18325 grantPermissionsUserIds = ArrayUtils.appendInt( 18326 grantPermissionsUserIds, userId); 18327 } 18328 } 18329 } 18330 sUserManager.systemReady(); 18331 18332 // If we upgraded grant all default permissions before kicking off. 18333 for (int userId : grantPermissionsUserIds) { 18334 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18335 } 18336 18337 // If we did not grant default permissions, we preload from this the 18338 // default permission exceptions lazily to ensure we don't hit the 18339 // disk on a new user creation. 18340 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18341 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18342 } 18343 18344 // Kick off any messages waiting for system ready 18345 if (mPostSystemReadyMessages != null) { 18346 for (Message msg : mPostSystemReadyMessages) { 18347 msg.sendToTarget(); 18348 } 18349 mPostSystemReadyMessages = null; 18350 } 18351 18352 // Watch for external volumes that come and go over time 18353 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18354 storage.registerListener(mStorageListener); 18355 18356 mInstallerService.systemReady(); 18357 mPackageDexOptimizer.systemReady(); 18358 18359 MountServiceInternal mountServiceInternal = LocalServices.getService( 18360 MountServiceInternal.class); 18361 mountServiceInternal.addExternalStoragePolicy( 18362 new MountServiceInternal.ExternalStorageMountPolicy() { 18363 @Override 18364 public int getMountMode(int uid, String packageName) { 18365 if (Process.isIsolated(uid)) { 18366 return Zygote.MOUNT_EXTERNAL_NONE; 18367 } 18368 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18369 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18370 } 18371 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18372 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18373 } 18374 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18375 return Zygote.MOUNT_EXTERNAL_READ; 18376 } 18377 return Zygote.MOUNT_EXTERNAL_WRITE; 18378 } 18379 18380 @Override 18381 public boolean hasExternalStorage(int uid, String packageName) { 18382 return true; 18383 } 18384 }); 18385 18386 // Now that we're mostly running, clean up stale users and apps 18387 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18388 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18389 } 18390 18391 @Override 18392 public boolean isSafeMode() { 18393 return mSafeMode; 18394 } 18395 18396 @Override 18397 public boolean hasSystemUidErrors() { 18398 return mHasSystemUidErrors; 18399 } 18400 18401 static String arrayToString(int[] array) { 18402 StringBuffer buf = new StringBuffer(128); 18403 buf.append('['); 18404 if (array != null) { 18405 for (int i=0; i<array.length; i++) { 18406 if (i > 0) buf.append(", "); 18407 buf.append(array[i]); 18408 } 18409 } 18410 buf.append(']'); 18411 return buf.toString(); 18412 } 18413 18414 static class DumpState { 18415 public static final int DUMP_LIBS = 1 << 0; 18416 public static final int DUMP_FEATURES = 1 << 1; 18417 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18418 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18419 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18420 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18421 public static final int DUMP_PERMISSIONS = 1 << 6; 18422 public static final int DUMP_PACKAGES = 1 << 7; 18423 public static final int DUMP_SHARED_USERS = 1 << 8; 18424 public static final int DUMP_MESSAGES = 1 << 9; 18425 public static final int DUMP_PROVIDERS = 1 << 10; 18426 public static final int DUMP_VERIFIERS = 1 << 11; 18427 public static final int DUMP_PREFERRED = 1 << 12; 18428 public static final int DUMP_PREFERRED_XML = 1 << 13; 18429 public static final int DUMP_KEYSETS = 1 << 14; 18430 public static final int DUMP_VERSION = 1 << 15; 18431 public static final int DUMP_INSTALLS = 1 << 16; 18432 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18433 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18434 public static final int DUMP_FROZEN = 1 << 19; 18435 public static final int DUMP_DEXOPT = 1 << 20; 18436 public static final int DUMP_COMPILER_STATS = 1 << 21; 18437 18438 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18439 18440 private int mTypes; 18441 18442 private int mOptions; 18443 18444 private boolean mTitlePrinted; 18445 18446 private SharedUserSetting mSharedUser; 18447 18448 public boolean isDumping(int type) { 18449 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18450 return true; 18451 } 18452 18453 return (mTypes & type) != 0; 18454 } 18455 18456 public void setDump(int type) { 18457 mTypes |= type; 18458 } 18459 18460 public boolean isOptionEnabled(int option) { 18461 return (mOptions & option) != 0; 18462 } 18463 18464 public void setOptionEnabled(int option) { 18465 mOptions |= option; 18466 } 18467 18468 public boolean onTitlePrinted() { 18469 final boolean printed = mTitlePrinted; 18470 mTitlePrinted = true; 18471 return printed; 18472 } 18473 18474 public boolean getTitlePrinted() { 18475 return mTitlePrinted; 18476 } 18477 18478 public void setTitlePrinted(boolean enabled) { 18479 mTitlePrinted = enabled; 18480 } 18481 18482 public SharedUserSetting getSharedUser() { 18483 return mSharedUser; 18484 } 18485 18486 public void setSharedUser(SharedUserSetting user) { 18487 mSharedUser = user; 18488 } 18489 } 18490 18491 @Override 18492 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18493 FileDescriptor err, String[] args, ShellCallback callback, 18494 ResultReceiver resultReceiver) { 18495 (new PackageManagerShellCommand(this)).exec( 18496 this, in, out, err, args, callback, resultReceiver); 18497 } 18498 18499 @Override 18500 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18501 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18502 != PackageManager.PERMISSION_GRANTED) { 18503 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18504 + Binder.getCallingPid() 18505 + ", uid=" + Binder.getCallingUid() 18506 + " without permission " 18507 + android.Manifest.permission.DUMP); 18508 return; 18509 } 18510 18511 DumpState dumpState = new DumpState(); 18512 boolean fullPreferred = false; 18513 boolean checkin = false; 18514 18515 String packageName = null; 18516 ArraySet<String> permissionNames = null; 18517 18518 int opti = 0; 18519 while (opti < args.length) { 18520 String opt = args[opti]; 18521 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18522 break; 18523 } 18524 opti++; 18525 18526 if ("-a".equals(opt)) { 18527 // Right now we only know how to print all. 18528 } else if ("-h".equals(opt)) { 18529 pw.println("Package manager dump options:"); 18530 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18531 pw.println(" --checkin: dump for a checkin"); 18532 pw.println(" -f: print details of intent filters"); 18533 pw.println(" -h: print this help"); 18534 pw.println(" cmd may be one of:"); 18535 pw.println(" l[ibraries]: list known shared libraries"); 18536 pw.println(" f[eatures]: list device features"); 18537 pw.println(" k[eysets]: print known keysets"); 18538 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18539 pw.println(" perm[issions]: dump permissions"); 18540 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18541 pw.println(" pref[erred]: print preferred package settings"); 18542 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18543 pw.println(" prov[iders]: dump content providers"); 18544 pw.println(" p[ackages]: dump installed packages"); 18545 pw.println(" s[hared-users]: dump shared user IDs"); 18546 pw.println(" m[essages]: print collected runtime messages"); 18547 pw.println(" v[erifiers]: print package verifier info"); 18548 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18549 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18550 pw.println(" version: print database version info"); 18551 pw.println(" write: write current settings now"); 18552 pw.println(" installs: details about install sessions"); 18553 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18554 pw.println(" dexopt: dump dexopt state"); 18555 pw.println(" compiler-stats: dump compiler statistics"); 18556 pw.println(" <package.name>: info about given package"); 18557 return; 18558 } else if ("--checkin".equals(opt)) { 18559 checkin = true; 18560 } else if ("-f".equals(opt)) { 18561 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18562 } else { 18563 pw.println("Unknown argument: " + opt + "; use -h for help"); 18564 } 18565 } 18566 18567 // Is the caller requesting to dump a particular piece of data? 18568 if (opti < args.length) { 18569 String cmd = args[opti]; 18570 opti++; 18571 // Is this a package name? 18572 if ("android".equals(cmd) || cmd.contains(".")) { 18573 packageName = cmd; 18574 // When dumping a single package, we always dump all of its 18575 // filter information since the amount of data will be reasonable. 18576 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18577 } else if ("check-permission".equals(cmd)) { 18578 if (opti >= args.length) { 18579 pw.println("Error: check-permission missing permission argument"); 18580 return; 18581 } 18582 String perm = args[opti]; 18583 opti++; 18584 if (opti >= args.length) { 18585 pw.println("Error: check-permission missing package argument"); 18586 return; 18587 } 18588 String pkg = args[opti]; 18589 opti++; 18590 int user = UserHandle.getUserId(Binder.getCallingUid()); 18591 if (opti < args.length) { 18592 try { 18593 user = Integer.parseInt(args[opti]); 18594 } catch (NumberFormatException e) { 18595 pw.println("Error: check-permission user argument is not a number: " 18596 + args[opti]); 18597 return; 18598 } 18599 } 18600 pw.println(checkPermission(perm, pkg, user)); 18601 return; 18602 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18603 dumpState.setDump(DumpState.DUMP_LIBS); 18604 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18605 dumpState.setDump(DumpState.DUMP_FEATURES); 18606 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18607 if (opti >= args.length) { 18608 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18609 | DumpState.DUMP_SERVICE_RESOLVERS 18610 | DumpState.DUMP_RECEIVER_RESOLVERS 18611 | DumpState.DUMP_CONTENT_RESOLVERS); 18612 } else { 18613 while (opti < args.length) { 18614 String name = args[opti]; 18615 if ("a".equals(name) || "activity".equals(name)) { 18616 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18617 } else if ("s".equals(name) || "service".equals(name)) { 18618 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18619 } else if ("r".equals(name) || "receiver".equals(name)) { 18620 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18621 } else if ("c".equals(name) || "content".equals(name)) { 18622 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18623 } else { 18624 pw.println("Error: unknown resolver table type: " + name); 18625 return; 18626 } 18627 opti++; 18628 } 18629 } 18630 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18631 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18632 } else if ("permission".equals(cmd)) { 18633 if (opti >= args.length) { 18634 pw.println("Error: permission requires permission name"); 18635 return; 18636 } 18637 permissionNames = new ArraySet<>(); 18638 while (opti < args.length) { 18639 permissionNames.add(args[opti]); 18640 opti++; 18641 } 18642 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18643 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18644 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18645 dumpState.setDump(DumpState.DUMP_PREFERRED); 18646 } else if ("preferred-xml".equals(cmd)) { 18647 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18648 if (opti < args.length && "--full".equals(args[opti])) { 18649 fullPreferred = true; 18650 opti++; 18651 } 18652 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18653 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18654 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18655 dumpState.setDump(DumpState.DUMP_PACKAGES); 18656 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18657 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18658 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18659 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18660 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18661 dumpState.setDump(DumpState.DUMP_MESSAGES); 18662 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18663 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18664 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18665 || "intent-filter-verifiers".equals(cmd)) { 18666 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18667 } else if ("version".equals(cmd)) { 18668 dumpState.setDump(DumpState.DUMP_VERSION); 18669 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18670 dumpState.setDump(DumpState.DUMP_KEYSETS); 18671 } else if ("installs".equals(cmd)) { 18672 dumpState.setDump(DumpState.DUMP_INSTALLS); 18673 } else if ("frozen".equals(cmd)) { 18674 dumpState.setDump(DumpState.DUMP_FROZEN); 18675 } else if ("dexopt".equals(cmd)) { 18676 dumpState.setDump(DumpState.DUMP_DEXOPT); 18677 } else if ("compiler-stats".equals(cmd)) { 18678 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18679 } else if ("write".equals(cmd)) { 18680 synchronized (mPackages) { 18681 mSettings.writeLPr(); 18682 pw.println("Settings written."); 18683 return; 18684 } 18685 } 18686 } 18687 18688 if (checkin) { 18689 pw.println("vers,1"); 18690 } 18691 18692 // reader 18693 synchronized (mPackages) { 18694 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18695 if (!checkin) { 18696 if (dumpState.onTitlePrinted()) 18697 pw.println(); 18698 pw.println("Database versions:"); 18699 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18700 } 18701 } 18702 18703 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18704 if (!checkin) { 18705 if (dumpState.onTitlePrinted()) 18706 pw.println(); 18707 pw.println("Verifiers:"); 18708 pw.print(" Required: "); 18709 pw.print(mRequiredVerifierPackage); 18710 pw.print(" (uid="); 18711 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18712 UserHandle.USER_SYSTEM)); 18713 pw.println(")"); 18714 } else if (mRequiredVerifierPackage != null) { 18715 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18716 pw.print(","); 18717 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18718 UserHandle.USER_SYSTEM)); 18719 } 18720 } 18721 18722 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18723 packageName == null) { 18724 if (mIntentFilterVerifierComponent != null) { 18725 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18726 if (!checkin) { 18727 if (dumpState.onTitlePrinted()) 18728 pw.println(); 18729 pw.println("Intent Filter Verifier:"); 18730 pw.print(" Using: "); 18731 pw.print(verifierPackageName); 18732 pw.print(" (uid="); 18733 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18734 UserHandle.USER_SYSTEM)); 18735 pw.println(")"); 18736 } else if (verifierPackageName != null) { 18737 pw.print("ifv,"); pw.print(verifierPackageName); 18738 pw.print(","); 18739 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18740 UserHandle.USER_SYSTEM)); 18741 } 18742 } else { 18743 pw.println(); 18744 pw.println("No Intent Filter Verifier available!"); 18745 } 18746 } 18747 18748 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18749 boolean printedHeader = false; 18750 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18751 while (it.hasNext()) { 18752 String name = it.next(); 18753 SharedLibraryEntry ent = mSharedLibraries.get(name); 18754 if (!checkin) { 18755 if (!printedHeader) { 18756 if (dumpState.onTitlePrinted()) 18757 pw.println(); 18758 pw.println("Libraries:"); 18759 printedHeader = true; 18760 } 18761 pw.print(" "); 18762 } else { 18763 pw.print("lib,"); 18764 } 18765 pw.print(name); 18766 if (!checkin) { 18767 pw.print(" -> "); 18768 } 18769 if (ent.path != null) { 18770 if (!checkin) { 18771 pw.print("(jar) "); 18772 pw.print(ent.path); 18773 } else { 18774 pw.print(",jar,"); 18775 pw.print(ent.path); 18776 } 18777 } else { 18778 if (!checkin) { 18779 pw.print("(apk) "); 18780 pw.print(ent.apk); 18781 } else { 18782 pw.print(",apk,"); 18783 pw.print(ent.apk); 18784 } 18785 } 18786 pw.println(); 18787 } 18788 } 18789 18790 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18791 if (dumpState.onTitlePrinted()) 18792 pw.println(); 18793 if (!checkin) { 18794 pw.println("Features:"); 18795 } 18796 18797 for (FeatureInfo feat : mAvailableFeatures.values()) { 18798 if (checkin) { 18799 pw.print("feat,"); 18800 pw.print(feat.name); 18801 pw.print(","); 18802 pw.println(feat.version); 18803 } else { 18804 pw.print(" "); 18805 pw.print(feat.name); 18806 if (feat.version > 0) { 18807 pw.print(" version="); 18808 pw.print(feat.version); 18809 } 18810 pw.println(); 18811 } 18812 } 18813 } 18814 18815 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18816 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18817 : "Activity Resolver Table:", " ", packageName, 18818 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18819 dumpState.setTitlePrinted(true); 18820 } 18821 } 18822 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18823 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18824 : "Receiver Resolver Table:", " ", packageName, 18825 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18826 dumpState.setTitlePrinted(true); 18827 } 18828 } 18829 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18830 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18831 : "Service Resolver Table:", " ", packageName, 18832 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18833 dumpState.setTitlePrinted(true); 18834 } 18835 } 18836 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18837 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18838 : "Provider Resolver Table:", " ", packageName, 18839 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18840 dumpState.setTitlePrinted(true); 18841 } 18842 } 18843 18844 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18845 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18846 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18847 int user = mSettings.mPreferredActivities.keyAt(i); 18848 if (pir.dump(pw, 18849 dumpState.getTitlePrinted() 18850 ? "\nPreferred Activities User " + user + ":" 18851 : "Preferred Activities User " + user + ":", " ", 18852 packageName, true, false)) { 18853 dumpState.setTitlePrinted(true); 18854 } 18855 } 18856 } 18857 18858 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18859 pw.flush(); 18860 FileOutputStream fout = new FileOutputStream(fd); 18861 BufferedOutputStream str = new BufferedOutputStream(fout); 18862 XmlSerializer serializer = new FastXmlSerializer(); 18863 try { 18864 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18865 serializer.startDocument(null, true); 18866 serializer.setFeature( 18867 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18868 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18869 serializer.endDocument(); 18870 serializer.flush(); 18871 } catch (IllegalArgumentException e) { 18872 pw.println("Failed writing: " + e); 18873 } catch (IllegalStateException e) { 18874 pw.println("Failed writing: " + e); 18875 } catch (IOException e) { 18876 pw.println("Failed writing: " + e); 18877 } 18878 } 18879 18880 if (!checkin 18881 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18882 && packageName == null) { 18883 pw.println(); 18884 int count = mSettings.mPackages.size(); 18885 if (count == 0) { 18886 pw.println("No applications!"); 18887 pw.println(); 18888 } else { 18889 final String prefix = " "; 18890 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18891 if (allPackageSettings.size() == 0) { 18892 pw.println("No domain preferred apps!"); 18893 pw.println(); 18894 } else { 18895 pw.println("App verification status:"); 18896 pw.println(); 18897 count = 0; 18898 for (PackageSetting ps : allPackageSettings) { 18899 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18900 if (ivi == null || ivi.getPackageName() == null) continue; 18901 pw.println(prefix + "Package: " + ivi.getPackageName()); 18902 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18903 pw.println(prefix + "Status: " + ivi.getStatusString()); 18904 pw.println(); 18905 count++; 18906 } 18907 if (count == 0) { 18908 pw.println(prefix + "No app verification established."); 18909 pw.println(); 18910 } 18911 for (int userId : sUserManager.getUserIds()) { 18912 pw.println("App linkages for user " + userId + ":"); 18913 pw.println(); 18914 count = 0; 18915 for (PackageSetting ps : allPackageSettings) { 18916 final long status = ps.getDomainVerificationStatusForUser(userId); 18917 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18918 continue; 18919 } 18920 pw.println(prefix + "Package: " + ps.name); 18921 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18922 String statusStr = IntentFilterVerificationInfo. 18923 getStatusStringFromValue(status); 18924 pw.println(prefix + "Status: " + statusStr); 18925 pw.println(); 18926 count++; 18927 } 18928 if (count == 0) { 18929 pw.println(prefix + "No configured app linkages."); 18930 pw.println(); 18931 } 18932 } 18933 } 18934 } 18935 } 18936 18937 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18938 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18939 if (packageName == null && permissionNames == null) { 18940 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18941 if (iperm == 0) { 18942 if (dumpState.onTitlePrinted()) 18943 pw.println(); 18944 pw.println("AppOp Permissions:"); 18945 } 18946 pw.print(" AppOp Permission "); 18947 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18948 pw.println(":"); 18949 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18950 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18951 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18952 } 18953 } 18954 } 18955 } 18956 18957 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18958 boolean printedSomething = false; 18959 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18960 if (packageName != null && !packageName.equals(p.info.packageName)) { 18961 continue; 18962 } 18963 if (!printedSomething) { 18964 if (dumpState.onTitlePrinted()) 18965 pw.println(); 18966 pw.println("Registered ContentProviders:"); 18967 printedSomething = true; 18968 } 18969 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18970 pw.print(" "); pw.println(p.toString()); 18971 } 18972 printedSomething = false; 18973 for (Map.Entry<String, PackageParser.Provider> entry : 18974 mProvidersByAuthority.entrySet()) { 18975 PackageParser.Provider p = entry.getValue(); 18976 if (packageName != null && !packageName.equals(p.info.packageName)) { 18977 continue; 18978 } 18979 if (!printedSomething) { 18980 if (dumpState.onTitlePrinted()) 18981 pw.println(); 18982 pw.println("ContentProvider Authorities:"); 18983 printedSomething = true; 18984 } 18985 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18986 pw.print(" "); pw.println(p.toString()); 18987 if (p.info != null && p.info.applicationInfo != null) { 18988 final String appInfo = p.info.applicationInfo.toString(); 18989 pw.print(" applicationInfo="); pw.println(appInfo); 18990 } 18991 } 18992 } 18993 18994 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18995 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18996 } 18997 18998 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18999 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 19000 } 19001 19002 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 19003 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 19004 } 19005 19006 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 19007 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 19008 } 19009 19010 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 19011 // XXX should handle packageName != null by dumping only install data that 19012 // the given package is involved with. 19013 if (dumpState.onTitlePrinted()) pw.println(); 19014 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 19015 } 19016 19017 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 19018 // XXX should handle packageName != null by dumping only install data that 19019 // the given package is involved with. 19020 if (dumpState.onTitlePrinted()) pw.println(); 19021 19022 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19023 ipw.println(); 19024 ipw.println("Frozen packages:"); 19025 ipw.increaseIndent(); 19026 if (mFrozenPackages.size() == 0) { 19027 ipw.println("(none)"); 19028 } else { 19029 for (int i = 0; i < mFrozenPackages.size(); i++) { 19030 ipw.println(mFrozenPackages.valueAt(i)); 19031 } 19032 } 19033 ipw.decreaseIndent(); 19034 } 19035 19036 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 19037 if (dumpState.onTitlePrinted()) pw.println(); 19038 dumpDexoptStateLPr(pw, packageName); 19039 } 19040 19041 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 19042 if (dumpState.onTitlePrinted()) pw.println(); 19043 dumpCompilerStatsLPr(pw, packageName); 19044 } 19045 19046 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 19047 if (dumpState.onTitlePrinted()) pw.println(); 19048 mSettings.dumpReadMessagesLPr(pw, dumpState); 19049 19050 pw.println(); 19051 pw.println("Package warning messages:"); 19052 BufferedReader in = null; 19053 String line = null; 19054 try { 19055 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19056 while ((line = in.readLine()) != null) { 19057 if (line.contains("ignored: updated version")) continue; 19058 pw.println(line); 19059 } 19060 } catch (IOException ignored) { 19061 } finally { 19062 IoUtils.closeQuietly(in); 19063 } 19064 } 19065 19066 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 19067 BufferedReader in = null; 19068 String line = null; 19069 try { 19070 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19071 while ((line = in.readLine()) != null) { 19072 if (line.contains("ignored: updated version")) continue; 19073 pw.print("msg,"); 19074 pw.println(line); 19075 } 19076 } catch (IOException ignored) { 19077 } finally { 19078 IoUtils.closeQuietly(in); 19079 } 19080 } 19081 } 19082 } 19083 19084 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 19085 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19086 ipw.println(); 19087 ipw.println("Dexopt state:"); 19088 ipw.increaseIndent(); 19089 Collection<PackageParser.Package> packages = null; 19090 if (packageName != null) { 19091 PackageParser.Package targetPackage = mPackages.get(packageName); 19092 if (targetPackage != null) { 19093 packages = Collections.singletonList(targetPackage); 19094 } else { 19095 ipw.println("Unable to find package: " + packageName); 19096 return; 19097 } 19098 } else { 19099 packages = mPackages.values(); 19100 } 19101 19102 for (PackageParser.Package pkg : packages) { 19103 ipw.println("[" + pkg.packageName + "]"); 19104 ipw.increaseIndent(); 19105 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 19106 ipw.decreaseIndent(); 19107 } 19108 } 19109 19110 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 19111 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19112 ipw.println(); 19113 ipw.println("Compiler stats:"); 19114 ipw.increaseIndent(); 19115 Collection<PackageParser.Package> packages = null; 19116 if (packageName != null) { 19117 PackageParser.Package targetPackage = mPackages.get(packageName); 19118 if (targetPackage != null) { 19119 packages = Collections.singletonList(targetPackage); 19120 } else { 19121 ipw.println("Unable to find package: " + packageName); 19122 return; 19123 } 19124 } else { 19125 packages = mPackages.values(); 19126 } 19127 19128 for (PackageParser.Package pkg : packages) { 19129 ipw.println("[" + pkg.packageName + "]"); 19130 ipw.increaseIndent(); 19131 19132 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 19133 if (stats == null) { 19134 ipw.println("(No recorded stats)"); 19135 } else { 19136 stats.dump(ipw); 19137 } 19138 ipw.decreaseIndent(); 19139 } 19140 } 19141 19142 private String dumpDomainString(String packageName) { 19143 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 19144 .getList(); 19145 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 19146 19147 ArraySet<String> result = new ArraySet<>(); 19148 if (iviList.size() > 0) { 19149 for (IntentFilterVerificationInfo ivi : iviList) { 19150 for (String host : ivi.getDomains()) { 19151 result.add(host); 19152 } 19153 } 19154 } 19155 if (filters != null && filters.size() > 0) { 19156 for (IntentFilter filter : filters) { 19157 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 19158 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19159 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19160 result.addAll(filter.getHostsList()); 19161 } 19162 } 19163 } 19164 19165 StringBuilder sb = new StringBuilder(result.size() * 16); 19166 for (String domain : result) { 19167 if (sb.length() > 0) sb.append(" "); 19168 sb.append(domain); 19169 } 19170 return sb.toString(); 19171 } 19172 19173 // ------- apps on sdcard specific code ------- 19174 static final boolean DEBUG_SD_INSTALL = false; 19175 19176 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19177 19178 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19179 19180 private boolean mMediaMounted = false; 19181 19182 static String getEncryptKey() { 19183 try { 19184 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19185 SD_ENCRYPTION_KEYSTORE_NAME); 19186 if (sdEncKey == null) { 19187 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19188 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19189 if (sdEncKey == null) { 19190 Slog.e(TAG, "Failed to create encryption keys"); 19191 return null; 19192 } 19193 } 19194 return sdEncKey; 19195 } catch (NoSuchAlgorithmException nsae) { 19196 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19197 return null; 19198 } catch (IOException ioe) { 19199 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19200 return null; 19201 } 19202 } 19203 19204 /* 19205 * Update media status on PackageManager. 19206 */ 19207 @Override 19208 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19209 int callingUid = Binder.getCallingUid(); 19210 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19211 throw new SecurityException("Media status can only be updated by the system"); 19212 } 19213 // reader; this apparently protects mMediaMounted, but should probably 19214 // be a different lock in that case. 19215 synchronized (mPackages) { 19216 Log.i(TAG, "Updating external media status from " 19217 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19218 + (mediaStatus ? "mounted" : "unmounted")); 19219 if (DEBUG_SD_INSTALL) 19220 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19221 + ", mMediaMounted=" + mMediaMounted); 19222 if (mediaStatus == mMediaMounted) { 19223 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19224 : 0, -1); 19225 mHandler.sendMessage(msg); 19226 return; 19227 } 19228 mMediaMounted = mediaStatus; 19229 } 19230 // Queue up an async operation since the package installation may take a 19231 // little while. 19232 mHandler.post(new Runnable() { 19233 public void run() { 19234 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19235 } 19236 }); 19237 } 19238 19239 /** 19240 * Called by MountService when the initial ASECs to scan are available. 19241 * Should block until all the ASEC containers are finished being scanned. 19242 */ 19243 public void scanAvailableAsecs() { 19244 updateExternalMediaStatusInner(true, false, false); 19245 } 19246 19247 /* 19248 * Collect information of applications on external media, map them against 19249 * existing containers and update information based on current mount status. 19250 * Please note that we always have to report status if reportStatus has been 19251 * set to true especially when unloading packages. 19252 */ 19253 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19254 boolean externalStorage) { 19255 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19256 int[] uidArr = EmptyArray.INT; 19257 19258 final String[] list = PackageHelper.getSecureContainerList(); 19259 if (ArrayUtils.isEmpty(list)) { 19260 Log.i(TAG, "No secure containers found"); 19261 } else { 19262 // Process list of secure containers and categorize them 19263 // as active or stale based on their package internal state. 19264 19265 // reader 19266 synchronized (mPackages) { 19267 for (String cid : list) { 19268 // Leave stages untouched for now; installer service owns them 19269 if (PackageInstallerService.isStageName(cid)) continue; 19270 19271 if (DEBUG_SD_INSTALL) 19272 Log.i(TAG, "Processing container " + cid); 19273 String pkgName = getAsecPackageName(cid); 19274 if (pkgName == null) { 19275 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19276 continue; 19277 } 19278 if (DEBUG_SD_INSTALL) 19279 Log.i(TAG, "Looking for pkg : " + pkgName); 19280 19281 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19282 if (ps == null) { 19283 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19284 continue; 19285 } 19286 19287 /* 19288 * Skip packages that are not external if we're unmounting 19289 * external storage. 19290 */ 19291 if (externalStorage && !isMounted && !isExternal(ps)) { 19292 continue; 19293 } 19294 19295 final AsecInstallArgs args = new AsecInstallArgs(cid, 19296 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19297 // The package status is changed only if the code path 19298 // matches between settings and the container id. 19299 if (ps.codePathString != null 19300 && ps.codePathString.startsWith(args.getCodePath())) { 19301 if (DEBUG_SD_INSTALL) { 19302 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19303 + " at code path: " + ps.codePathString); 19304 } 19305 19306 // We do have a valid package installed on sdcard 19307 processCids.put(args, ps.codePathString); 19308 final int uid = ps.appId; 19309 if (uid != -1) { 19310 uidArr = ArrayUtils.appendInt(uidArr, uid); 19311 } 19312 } else { 19313 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19314 + ps.codePathString); 19315 } 19316 } 19317 } 19318 19319 Arrays.sort(uidArr); 19320 } 19321 19322 // Process packages with valid entries. 19323 if (isMounted) { 19324 if (DEBUG_SD_INSTALL) 19325 Log.i(TAG, "Loading packages"); 19326 loadMediaPackages(processCids, uidArr, externalStorage); 19327 startCleaningPackages(); 19328 mInstallerService.onSecureContainersAvailable(); 19329 } else { 19330 if (DEBUG_SD_INSTALL) 19331 Log.i(TAG, "Unloading packages"); 19332 unloadMediaPackages(processCids, uidArr, reportStatus); 19333 } 19334 } 19335 19336 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19337 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19338 final int size = infos.size(); 19339 final String[] packageNames = new String[size]; 19340 final int[] packageUids = new int[size]; 19341 for (int i = 0; i < size; i++) { 19342 final ApplicationInfo info = infos.get(i); 19343 packageNames[i] = info.packageName; 19344 packageUids[i] = info.uid; 19345 } 19346 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19347 finishedReceiver); 19348 } 19349 19350 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19351 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19352 sendResourcesChangedBroadcast(mediaStatus, replacing, 19353 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19354 } 19355 19356 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19357 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19358 int size = pkgList.length; 19359 if (size > 0) { 19360 // Send broadcasts here 19361 Bundle extras = new Bundle(); 19362 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19363 if (uidArr != null) { 19364 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19365 } 19366 if (replacing) { 19367 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19368 } 19369 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19370 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19371 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19372 } 19373 } 19374 19375 /* 19376 * Look at potentially valid container ids from processCids If package 19377 * information doesn't match the one on record or package scanning fails, 19378 * the cid is added to list of removeCids. We currently don't delete stale 19379 * containers. 19380 */ 19381 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19382 boolean externalStorage) { 19383 ArrayList<String> pkgList = new ArrayList<String>(); 19384 Set<AsecInstallArgs> keys = processCids.keySet(); 19385 19386 for (AsecInstallArgs args : keys) { 19387 String codePath = processCids.get(args); 19388 if (DEBUG_SD_INSTALL) 19389 Log.i(TAG, "Loading container : " + args.cid); 19390 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19391 try { 19392 // Make sure there are no container errors first. 19393 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19394 Slog.e(TAG, "Failed to mount cid : " + args.cid 19395 + " when installing from sdcard"); 19396 continue; 19397 } 19398 // Check code path here. 19399 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19400 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19401 + " does not match one in settings " + codePath); 19402 continue; 19403 } 19404 // Parse package 19405 int parseFlags = mDefParseFlags; 19406 if (args.isExternalAsec()) { 19407 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19408 } 19409 if (args.isFwdLocked()) { 19410 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19411 } 19412 19413 synchronized (mInstallLock) { 19414 PackageParser.Package pkg = null; 19415 try { 19416 // Sadly we don't know the package name yet to freeze it 19417 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19418 SCAN_IGNORE_FROZEN, 0, null); 19419 } catch (PackageManagerException e) { 19420 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19421 } 19422 // Scan the package 19423 if (pkg != null) { 19424 /* 19425 * TODO why is the lock being held? doPostInstall is 19426 * called in other places without the lock. This needs 19427 * to be straightened out. 19428 */ 19429 // writer 19430 synchronized (mPackages) { 19431 retCode = PackageManager.INSTALL_SUCCEEDED; 19432 pkgList.add(pkg.packageName); 19433 // Post process args 19434 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19435 pkg.applicationInfo.uid); 19436 } 19437 } else { 19438 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19439 } 19440 } 19441 19442 } finally { 19443 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19444 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19445 } 19446 } 19447 } 19448 // writer 19449 synchronized (mPackages) { 19450 // If the platform SDK has changed since the last time we booted, 19451 // we need to re-grant app permission to catch any new ones that 19452 // appear. This is really a hack, and means that apps can in some 19453 // cases get permissions that the user didn't initially explicitly 19454 // allow... it would be nice to have some better way to handle 19455 // this situation. 19456 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19457 : mSettings.getInternalVersion(); 19458 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19459 : StorageManager.UUID_PRIVATE_INTERNAL; 19460 19461 int updateFlags = UPDATE_PERMISSIONS_ALL; 19462 if (ver.sdkVersion != mSdkVersion) { 19463 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19464 + mSdkVersion + "; regranting permissions for external"); 19465 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19466 } 19467 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19468 19469 // Yay, everything is now upgraded 19470 ver.forceCurrent(); 19471 19472 // can downgrade to reader 19473 // Persist settings 19474 mSettings.writeLPr(); 19475 } 19476 // Send a broadcast to let everyone know we are done processing 19477 if (pkgList.size() > 0) { 19478 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19479 } 19480 } 19481 19482 /* 19483 * Utility method to unload a list of specified containers 19484 */ 19485 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19486 // Just unmount all valid containers. 19487 for (AsecInstallArgs arg : cidArgs) { 19488 synchronized (mInstallLock) { 19489 arg.doPostDeleteLI(false); 19490 } 19491 } 19492 } 19493 19494 /* 19495 * Unload packages mounted on external media. This involves deleting package 19496 * data from internal structures, sending broadcasts about disabled packages, 19497 * gc'ing to free up references, unmounting all secure containers 19498 * corresponding to packages on external media, and posting a 19499 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19500 * that we always have to post this message if status has been requested no 19501 * matter what. 19502 */ 19503 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19504 final boolean reportStatus) { 19505 if (DEBUG_SD_INSTALL) 19506 Log.i(TAG, "unloading media packages"); 19507 ArrayList<String> pkgList = new ArrayList<String>(); 19508 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19509 final Set<AsecInstallArgs> keys = processCids.keySet(); 19510 for (AsecInstallArgs args : keys) { 19511 String pkgName = args.getPackageName(); 19512 if (DEBUG_SD_INSTALL) 19513 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19514 // Delete package internally 19515 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19516 synchronized (mInstallLock) { 19517 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19518 final boolean res; 19519 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19520 "unloadMediaPackages")) { 19521 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19522 null); 19523 } 19524 if (res) { 19525 pkgList.add(pkgName); 19526 } else { 19527 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19528 failedList.add(args); 19529 } 19530 } 19531 } 19532 19533 // reader 19534 synchronized (mPackages) { 19535 // We didn't update the settings after removing each package; 19536 // write them now for all packages. 19537 mSettings.writeLPr(); 19538 } 19539 19540 // We have to absolutely send UPDATED_MEDIA_STATUS only 19541 // after confirming that all the receivers processed the ordered 19542 // broadcast when packages get disabled, force a gc to clean things up. 19543 // and unload all the containers. 19544 if (pkgList.size() > 0) { 19545 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19546 new IIntentReceiver.Stub() { 19547 public void performReceive(Intent intent, int resultCode, String data, 19548 Bundle extras, boolean ordered, boolean sticky, 19549 int sendingUser) throws RemoteException { 19550 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19551 reportStatus ? 1 : 0, 1, keys); 19552 mHandler.sendMessage(msg); 19553 } 19554 }); 19555 } else { 19556 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19557 keys); 19558 mHandler.sendMessage(msg); 19559 } 19560 } 19561 19562 private void loadPrivatePackages(final VolumeInfo vol) { 19563 mHandler.post(new Runnable() { 19564 @Override 19565 public void run() { 19566 loadPrivatePackagesInner(vol); 19567 } 19568 }); 19569 } 19570 19571 private void loadPrivatePackagesInner(VolumeInfo vol) { 19572 final String volumeUuid = vol.fsUuid; 19573 if (TextUtils.isEmpty(volumeUuid)) { 19574 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19575 return; 19576 } 19577 19578 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19579 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19580 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19581 19582 final VersionInfo ver; 19583 final List<PackageSetting> packages; 19584 synchronized (mPackages) { 19585 ver = mSettings.findOrCreateVersion(volumeUuid); 19586 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19587 } 19588 19589 for (PackageSetting ps : packages) { 19590 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19591 synchronized (mInstallLock) { 19592 final PackageParser.Package pkg; 19593 try { 19594 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19595 loaded.add(pkg.applicationInfo); 19596 19597 } catch (PackageManagerException e) { 19598 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19599 } 19600 19601 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19602 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19603 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19604 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19605 } 19606 } 19607 } 19608 19609 // Reconcile app data for all started/unlocked users 19610 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19611 final UserManager um = mContext.getSystemService(UserManager.class); 19612 UserManagerInternal umInternal = getUserManagerInternal(); 19613 for (UserInfo user : um.getUsers()) { 19614 final int flags; 19615 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19616 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19617 } else if (umInternal.isUserRunning(user.id)) { 19618 flags = StorageManager.FLAG_STORAGE_DE; 19619 } else { 19620 continue; 19621 } 19622 19623 try { 19624 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19625 synchronized (mInstallLock) { 19626 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 19627 } 19628 } catch (IllegalStateException e) { 19629 // Device was probably ejected, and we'll process that event momentarily 19630 Slog.w(TAG, "Failed to prepare storage: " + e); 19631 } 19632 } 19633 19634 synchronized (mPackages) { 19635 int updateFlags = UPDATE_PERMISSIONS_ALL; 19636 if (ver.sdkVersion != mSdkVersion) { 19637 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19638 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19639 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19640 } 19641 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19642 19643 // Yay, everything is now upgraded 19644 ver.forceCurrent(); 19645 19646 mSettings.writeLPr(); 19647 } 19648 19649 for (PackageFreezer freezer : freezers) { 19650 freezer.close(); 19651 } 19652 19653 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19654 sendResourcesChangedBroadcast(true, false, loaded, null); 19655 } 19656 19657 private void unloadPrivatePackages(final VolumeInfo vol) { 19658 mHandler.post(new Runnable() { 19659 @Override 19660 public void run() { 19661 unloadPrivatePackagesInner(vol); 19662 } 19663 }); 19664 } 19665 19666 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19667 final String volumeUuid = vol.fsUuid; 19668 if (TextUtils.isEmpty(volumeUuid)) { 19669 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19670 return; 19671 } 19672 19673 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19674 synchronized (mInstallLock) { 19675 synchronized (mPackages) { 19676 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19677 for (PackageSetting ps : packages) { 19678 if (ps.pkg == null) continue; 19679 19680 final ApplicationInfo info = ps.pkg.applicationInfo; 19681 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19682 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19683 19684 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19685 "unloadPrivatePackagesInner")) { 19686 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19687 false, null)) { 19688 unloaded.add(info); 19689 } else { 19690 Slog.w(TAG, "Failed to unload " + ps.codePath); 19691 } 19692 } 19693 19694 // Try very hard to release any references to this package 19695 // so we don't risk the system server being killed due to 19696 // open FDs 19697 AttributeCache.instance().removePackage(ps.name); 19698 } 19699 19700 mSettings.writeLPr(); 19701 } 19702 } 19703 19704 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19705 sendResourcesChangedBroadcast(false, false, unloaded, null); 19706 19707 // Try very hard to release any references to this path so we don't risk 19708 // the system server being killed due to open FDs 19709 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19710 19711 for (int i = 0; i < 3; i++) { 19712 System.gc(); 19713 System.runFinalization(); 19714 } 19715 } 19716 19717 /** 19718 * Prepare storage areas for given user on all mounted devices. 19719 */ 19720 void prepareUserData(int userId, int userSerial, int flags) { 19721 synchronized (mInstallLock) { 19722 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19723 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19724 final String volumeUuid = vol.getFsUuid(); 19725 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19726 } 19727 } 19728 } 19729 19730 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19731 boolean allowRecover) { 19732 // Prepare storage and verify that serial numbers are consistent; if 19733 // there's a mismatch we need to destroy to avoid leaking data 19734 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19735 try { 19736 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19737 19738 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19739 UserManagerService.enforceSerialNumber( 19740 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19741 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19742 UserManagerService.enforceSerialNumber( 19743 Environment.getDataSystemDeDirectory(userId), userSerial); 19744 } 19745 } 19746 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19747 UserManagerService.enforceSerialNumber( 19748 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19749 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19750 UserManagerService.enforceSerialNumber( 19751 Environment.getDataSystemCeDirectory(userId), userSerial); 19752 } 19753 } 19754 19755 synchronized (mInstallLock) { 19756 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19757 } 19758 } catch (Exception e) { 19759 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19760 + " because we failed to prepare: " + e); 19761 destroyUserDataLI(volumeUuid, userId, 19762 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19763 19764 if (allowRecover) { 19765 // Try one last time; if we fail again we're really in trouble 19766 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19767 } 19768 } 19769 } 19770 19771 /** 19772 * Destroy storage areas for given user on all mounted devices. 19773 */ 19774 void destroyUserData(int userId, int flags) { 19775 synchronized (mInstallLock) { 19776 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19777 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19778 final String volumeUuid = vol.getFsUuid(); 19779 destroyUserDataLI(volumeUuid, userId, flags); 19780 } 19781 } 19782 } 19783 19784 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19785 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19786 try { 19787 // Clean up app data, profile data, and media data 19788 mInstaller.destroyUserData(volumeUuid, userId, flags); 19789 19790 // Clean up system data 19791 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19792 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19793 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19794 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19795 } 19796 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19797 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19798 } 19799 } 19800 19801 // Data with special labels is now gone, so finish the job 19802 storage.destroyUserStorage(volumeUuid, userId, flags); 19803 19804 } catch (Exception e) { 19805 logCriticalInfo(Log.WARN, 19806 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19807 } 19808 } 19809 19810 /** 19811 * Examine all users present on given mounted volume, and destroy data 19812 * belonging to users that are no longer valid, or whose user ID has been 19813 * recycled. 19814 */ 19815 private void reconcileUsers(String volumeUuid) { 19816 final List<File> files = new ArrayList<>(); 19817 Collections.addAll(files, FileUtils 19818 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19819 Collections.addAll(files, FileUtils 19820 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19821 Collections.addAll(files, FileUtils 19822 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19823 Collections.addAll(files, FileUtils 19824 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19825 for (File file : files) { 19826 if (!file.isDirectory()) continue; 19827 19828 final int userId; 19829 final UserInfo info; 19830 try { 19831 userId = Integer.parseInt(file.getName()); 19832 info = sUserManager.getUserInfo(userId); 19833 } catch (NumberFormatException e) { 19834 Slog.w(TAG, "Invalid user directory " + file); 19835 continue; 19836 } 19837 19838 boolean destroyUser = false; 19839 if (info == null) { 19840 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19841 + " because no matching user was found"); 19842 destroyUser = true; 19843 } else if (!mOnlyCore) { 19844 try { 19845 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19846 } catch (IOException e) { 19847 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19848 + " because we failed to enforce serial number: " + e); 19849 destroyUser = true; 19850 } 19851 } 19852 19853 if (destroyUser) { 19854 synchronized (mInstallLock) { 19855 destroyUserDataLI(volumeUuid, userId, 19856 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19857 } 19858 } 19859 } 19860 } 19861 19862 private void assertPackageKnown(String volumeUuid, String packageName) 19863 throws PackageManagerException { 19864 synchronized (mPackages) { 19865 final PackageSetting ps = mSettings.mPackages.get(packageName); 19866 if (ps == null) { 19867 throw new PackageManagerException("Package " + packageName + " is unknown"); 19868 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19869 throw new PackageManagerException( 19870 "Package " + packageName + " found on unknown volume " + volumeUuid 19871 + "; expected volume " + ps.volumeUuid); 19872 } 19873 } 19874 } 19875 19876 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19877 throws PackageManagerException { 19878 synchronized (mPackages) { 19879 final PackageSetting ps = mSettings.mPackages.get(packageName); 19880 if (ps == null) { 19881 throw new PackageManagerException("Package " + packageName + " is unknown"); 19882 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19883 throw new PackageManagerException( 19884 "Package " + packageName + " found on unknown volume " + volumeUuid 19885 + "; expected volume " + ps.volumeUuid); 19886 } else if (!ps.getInstalled(userId)) { 19887 throw new PackageManagerException( 19888 "Package " + packageName + " not installed for user " + userId); 19889 } 19890 } 19891 } 19892 19893 /** 19894 * Examine all apps present on given mounted volume, and destroy apps that 19895 * aren't expected, either due to uninstallation or reinstallation on 19896 * another volume. 19897 */ 19898 private void reconcileApps(String volumeUuid) { 19899 final File[] files = FileUtils 19900 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19901 for (File file : files) { 19902 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19903 && !PackageInstallerService.isStageName(file.getName()); 19904 if (!isPackage) { 19905 // Ignore entries which are not packages 19906 continue; 19907 } 19908 19909 try { 19910 final PackageLite pkg = PackageParser.parsePackageLite(file, 19911 PackageParser.PARSE_MUST_BE_APK); 19912 assertPackageKnown(volumeUuid, pkg.packageName); 19913 19914 } catch (PackageParserException | PackageManagerException e) { 19915 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19916 synchronized (mInstallLock) { 19917 removeCodePathLI(file); 19918 } 19919 } 19920 } 19921 } 19922 19923 /** 19924 * Reconcile all app data for the given user. 19925 * <p> 19926 * Verifies that directories exist and that ownership and labeling is 19927 * correct for all installed apps on all mounted volumes. 19928 */ 19929 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 19930 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19931 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19932 final String volumeUuid = vol.getFsUuid(); 19933 synchronized (mInstallLock) { 19934 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 19935 } 19936 } 19937 } 19938 19939 /** 19940 * Reconcile all app data on given mounted volume. 19941 * <p> 19942 * Destroys app data that isn't expected, either due to uninstallation or 19943 * reinstallation on another volume. 19944 * <p> 19945 * Verifies that directories exist and that ownership and labeling is 19946 * correct for all installed apps. 19947 */ 19948 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 19949 boolean migrateAppData) { 19950 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19951 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 19952 19953 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19954 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19955 19956 // First look for stale data that doesn't belong, and check if things 19957 // have changed since we did our last restorecon 19958 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19959 if (StorageManager.isFileEncryptedNativeOrEmulated() 19960 && !StorageManager.isUserKeyUnlocked(userId)) { 19961 throw new RuntimeException( 19962 "Yikes, someone asked us to reconcile CE storage while " + userId 19963 + " was still locked; this would have caused massive data loss!"); 19964 } 19965 19966 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19967 for (File file : files) { 19968 final String packageName = file.getName(); 19969 try { 19970 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19971 } catch (PackageManagerException e) { 19972 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19973 try { 19974 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19975 StorageManager.FLAG_STORAGE_CE, 0); 19976 } catch (InstallerException e2) { 19977 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19978 } 19979 } 19980 } 19981 } 19982 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19983 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19984 for (File file : files) { 19985 final String packageName = file.getName(); 19986 try { 19987 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19988 } catch (PackageManagerException e) { 19989 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19990 try { 19991 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19992 StorageManager.FLAG_STORAGE_DE, 0); 19993 } catch (InstallerException e2) { 19994 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19995 } 19996 } 19997 } 19998 } 19999 20000 // Ensure that data directories are ready to roll for all packages 20001 // installed for this volume and user 20002 final List<PackageSetting> packages; 20003 synchronized (mPackages) { 20004 packages = mSettings.getVolumePackagesLPr(volumeUuid); 20005 } 20006 int preparedCount = 0; 20007 for (PackageSetting ps : packages) { 20008 final String packageName = ps.name; 20009 if (ps.pkg == null) { 20010 Slog.w(TAG, "Odd, missing scanned package " + packageName); 20011 // TODO: might be due to legacy ASEC apps; we should circle back 20012 // and reconcile again once they're scanned 20013 continue; 20014 } 20015 20016 if (ps.getInstalled(userId)) { 20017 prepareAppDataLIF(ps.pkg, userId, flags); 20018 20019 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 20020 // We may have just shuffled around app data directories, so 20021 // prepare them one more time 20022 prepareAppDataLIF(ps.pkg, userId, flags); 20023 } 20024 20025 preparedCount++; 20026 } 20027 } 20028 20029 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 20030 } 20031 20032 /** 20033 * Prepare app data for the given app just after it was installed or 20034 * upgraded. This method carefully only touches users that it's installed 20035 * for, and it forces a restorecon to handle any seinfo changes. 20036 * <p> 20037 * Verifies that directories exist and that ownership and labeling is 20038 * correct for all installed apps. If there is an ownership mismatch, it 20039 * will try recovering system apps by wiping data; third-party app data is 20040 * left intact. 20041 * <p> 20042 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 20043 */ 20044 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 20045 final PackageSetting ps; 20046 synchronized (mPackages) { 20047 ps = mSettings.mPackages.get(pkg.packageName); 20048 mSettings.writeKernelMappingLPr(ps); 20049 } 20050 20051 final UserManager um = mContext.getSystemService(UserManager.class); 20052 UserManagerInternal umInternal = getUserManagerInternal(); 20053 for (UserInfo user : um.getUsers()) { 20054 final int flags; 20055 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20056 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20057 } else if (umInternal.isUserRunning(user.id)) { 20058 flags = StorageManager.FLAG_STORAGE_DE; 20059 } else { 20060 continue; 20061 } 20062 20063 if (ps.getInstalled(user.id)) { 20064 // TODO: when user data is locked, mark that we're still dirty 20065 prepareAppDataLIF(pkg, user.id, flags); 20066 } 20067 } 20068 } 20069 20070 /** 20071 * Prepare app data for the given app. 20072 * <p> 20073 * Verifies that directories exist and that ownership and labeling is 20074 * correct for all installed apps. If there is an ownership mismatch, this 20075 * will try recovering system apps by wiping data; third-party app data is 20076 * left intact. 20077 */ 20078 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 20079 if (pkg == null) { 20080 Slog.wtf(TAG, "Package was null!", new Throwable()); 20081 return; 20082 } 20083 prepareAppDataLeafLIF(pkg, userId, flags); 20084 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20085 for (int i = 0; i < childCount; i++) { 20086 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 20087 } 20088 } 20089 20090 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20091 if (DEBUG_APP_DATA) { 20092 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 20093 + Integer.toHexString(flags)); 20094 } 20095 20096 final String volumeUuid = pkg.volumeUuid; 20097 final String packageName = pkg.packageName; 20098 final ApplicationInfo app = pkg.applicationInfo; 20099 final int appId = UserHandle.getAppId(app.uid); 20100 20101 Preconditions.checkNotNull(app.seinfo); 20102 20103 try { 20104 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20105 appId, app.seinfo, app.targetSdkVersion); 20106 } catch (InstallerException e) { 20107 if (app.isSystemApp()) { 20108 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 20109 + ", but trying to recover: " + e); 20110 destroyAppDataLeafLIF(pkg, userId, flags); 20111 try { 20112 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20113 appId, app.seinfo, app.targetSdkVersion); 20114 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 20115 } catch (InstallerException e2) { 20116 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 20117 } 20118 } else { 20119 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 20120 } 20121 } 20122 20123 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20124 try { 20125 // CE storage is unlocked right now, so read out the inode and 20126 // remember for use later when it's locked 20127 // TODO: mark this structure as dirty so we persist it! 20128 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 20129 StorageManager.FLAG_STORAGE_CE); 20130 synchronized (mPackages) { 20131 final PackageSetting ps = mSettings.mPackages.get(packageName); 20132 if (ps != null) { 20133 ps.setCeDataInode(ceDataInode, userId); 20134 } 20135 } 20136 } catch (InstallerException e) { 20137 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 20138 } 20139 } 20140 20141 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20142 } 20143 20144 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 20145 if (pkg == null) { 20146 Slog.wtf(TAG, "Package was null!", new Throwable()); 20147 return; 20148 } 20149 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20150 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20151 for (int i = 0; i < childCount; i++) { 20152 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 20153 } 20154 } 20155 20156 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20157 final String volumeUuid = pkg.volumeUuid; 20158 final String packageName = pkg.packageName; 20159 final ApplicationInfo app = pkg.applicationInfo; 20160 20161 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20162 // Create a native library symlink only if we have native libraries 20163 // and if the native libraries are 32 bit libraries. We do not provide 20164 // this symlink for 64 bit libraries. 20165 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20166 final String nativeLibPath = app.nativeLibraryDir; 20167 try { 20168 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20169 nativeLibPath, userId); 20170 } catch (InstallerException e) { 20171 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20172 } 20173 } 20174 } 20175 } 20176 20177 /** 20178 * For system apps on non-FBE devices, this method migrates any existing 20179 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20180 * requested by the app. 20181 */ 20182 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20183 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20184 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20185 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20186 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20187 try { 20188 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20189 storageTarget); 20190 } catch (InstallerException e) { 20191 logCriticalInfo(Log.WARN, 20192 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20193 } 20194 return true; 20195 } else { 20196 return false; 20197 } 20198 } 20199 20200 public PackageFreezer freezePackage(String packageName, String killReason) { 20201 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20202 } 20203 20204 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20205 return new PackageFreezer(packageName, userId, killReason); 20206 } 20207 20208 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20209 String killReason) { 20210 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20211 } 20212 20213 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20214 String killReason) { 20215 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20216 return new PackageFreezer(); 20217 } else { 20218 return freezePackage(packageName, userId, killReason); 20219 } 20220 } 20221 20222 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20223 String killReason) { 20224 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20225 } 20226 20227 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20228 String killReason) { 20229 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20230 return new PackageFreezer(); 20231 } else { 20232 return freezePackage(packageName, userId, killReason); 20233 } 20234 } 20235 20236 /** 20237 * Class that freezes and kills the given package upon creation, and 20238 * unfreezes it upon closing. This is typically used when doing surgery on 20239 * app code/data to prevent the app from running while you're working. 20240 */ 20241 private class PackageFreezer implements AutoCloseable { 20242 private final String mPackageName; 20243 private final PackageFreezer[] mChildren; 20244 20245 private final boolean mWeFroze; 20246 20247 private final AtomicBoolean mClosed = new AtomicBoolean(); 20248 private final CloseGuard mCloseGuard = CloseGuard.get(); 20249 20250 /** 20251 * Create and return a stub freezer that doesn't actually do anything, 20252 * typically used when someone requested 20253 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20254 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20255 */ 20256 public PackageFreezer() { 20257 mPackageName = null; 20258 mChildren = null; 20259 mWeFroze = false; 20260 mCloseGuard.open("close"); 20261 } 20262 20263 public PackageFreezer(String packageName, int userId, String killReason) { 20264 synchronized (mPackages) { 20265 mPackageName = packageName; 20266 mWeFroze = mFrozenPackages.add(mPackageName); 20267 20268 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20269 if (ps != null) { 20270 killApplication(ps.name, ps.appId, userId, killReason); 20271 } 20272 20273 final PackageParser.Package p = mPackages.get(packageName); 20274 if (p != null && p.childPackages != null) { 20275 final int N = p.childPackages.size(); 20276 mChildren = new PackageFreezer[N]; 20277 for (int i = 0; i < N; i++) { 20278 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20279 userId, killReason); 20280 } 20281 } else { 20282 mChildren = null; 20283 } 20284 } 20285 mCloseGuard.open("close"); 20286 } 20287 20288 @Override 20289 protected void finalize() throws Throwable { 20290 try { 20291 mCloseGuard.warnIfOpen(); 20292 close(); 20293 } finally { 20294 super.finalize(); 20295 } 20296 } 20297 20298 @Override 20299 public void close() { 20300 mCloseGuard.close(); 20301 if (mClosed.compareAndSet(false, true)) { 20302 synchronized (mPackages) { 20303 if (mWeFroze) { 20304 mFrozenPackages.remove(mPackageName); 20305 } 20306 20307 if (mChildren != null) { 20308 for (PackageFreezer freezer : mChildren) { 20309 freezer.close(); 20310 } 20311 } 20312 } 20313 } 20314 } 20315 } 20316 20317 /** 20318 * Verify that given package is currently frozen. 20319 */ 20320 private void checkPackageFrozen(String packageName) { 20321 synchronized (mPackages) { 20322 if (!mFrozenPackages.contains(packageName)) { 20323 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20324 } 20325 } 20326 } 20327 20328 @Override 20329 public int movePackage(final String packageName, final String volumeUuid) { 20330 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20331 20332 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20333 final int moveId = mNextMoveId.getAndIncrement(); 20334 mHandler.post(new Runnable() { 20335 @Override 20336 public void run() { 20337 try { 20338 movePackageInternal(packageName, volumeUuid, moveId, user); 20339 } catch (PackageManagerException e) { 20340 Slog.w(TAG, "Failed to move " + packageName, e); 20341 mMoveCallbacks.notifyStatusChanged(moveId, 20342 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20343 } 20344 } 20345 }); 20346 return moveId; 20347 } 20348 20349 private void movePackageInternal(final String packageName, final String volumeUuid, 20350 final int moveId, UserHandle user) throws PackageManagerException { 20351 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20352 final PackageManager pm = mContext.getPackageManager(); 20353 20354 final boolean currentAsec; 20355 final String currentVolumeUuid; 20356 final File codeFile; 20357 final String installerPackageName; 20358 final String packageAbiOverride; 20359 final int appId; 20360 final String seinfo; 20361 final String label; 20362 final int targetSdkVersion; 20363 final PackageFreezer freezer; 20364 final int[] installedUserIds; 20365 20366 // reader 20367 synchronized (mPackages) { 20368 final PackageParser.Package pkg = mPackages.get(packageName); 20369 final PackageSetting ps = mSettings.mPackages.get(packageName); 20370 if (pkg == null || ps == null) { 20371 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20372 } 20373 20374 if (pkg.applicationInfo.isSystemApp()) { 20375 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20376 "Cannot move system application"); 20377 } 20378 20379 if (pkg.applicationInfo.isExternalAsec()) { 20380 currentAsec = true; 20381 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20382 } else if (pkg.applicationInfo.isForwardLocked()) { 20383 currentAsec = true; 20384 currentVolumeUuid = "forward_locked"; 20385 } else { 20386 currentAsec = false; 20387 currentVolumeUuid = ps.volumeUuid; 20388 20389 final File probe = new File(pkg.codePath); 20390 final File probeOat = new File(probe, "oat"); 20391 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20392 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20393 "Move only supported for modern cluster style installs"); 20394 } 20395 } 20396 20397 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20398 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20399 "Package already moved to " + volumeUuid); 20400 } 20401 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20402 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20403 "Device admin cannot be moved"); 20404 } 20405 20406 if (mFrozenPackages.contains(packageName)) { 20407 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20408 "Failed to move already frozen package"); 20409 } 20410 20411 codeFile = new File(pkg.codePath); 20412 installerPackageName = ps.installerPackageName; 20413 packageAbiOverride = ps.cpuAbiOverrideString; 20414 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20415 seinfo = pkg.applicationInfo.seinfo; 20416 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20417 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20418 freezer = freezePackage(packageName, "movePackageInternal"); 20419 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20420 } 20421 20422 final Bundle extras = new Bundle(); 20423 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20424 extras.putString(Intent.EXTRA_TITLE, label); 20425 mMoveCallbacks.notifyCreated(moveId, extras); 20426 20427 int installFlags; 20428 final boolean moveCompleteApp; 20429 final File measurePath; 20430 20431 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20432 installFlags = INSTALL_INTERNAL; 20433 moveCompleteApp = !currentAsec; 20434 measurePath = Environment.getDataAppDirectory(volumeUuid); 20435 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20436 installFlags = INSTALL_EXTERNAL; 20437 moveCompleteApp = false; 20438 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20439 } else { 20440 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20441 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20442 || !volume.isMountedWritable()) { 20443 freezer.close(); 20444 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20445 "Move location not mounted private volume"); 20446 } 20447 20448 Preconditions.checkState(!currentAsec); 20449 20450 installFlags = INSTALL_INTERNAL; 20451 moveCompleteApp = true; 20452 measurePath = Environment.getDataAppDirectory(volumeUuid); 20453 } 20454 20455 final PackageStats stats = new PackageStats(null, -1); 20456 synchronized (mInstaller) { 20457 for (int userId : installedUserIds) { 20458 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20459 freezer.close(); 20460 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20461 "Failed to measure package size"); 20462 } 20463 } 20464 } 20465 20466 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20467 + stats.dataSize); 20468 20469 final long startFreeBytes = measurePath.getFreeSpace(); 20470 final long sizeBytes; 20471 if (moveCompleteApp) { 20472 sizeBytes = stats.codeSize + stats.dataSize; 20473 } else { 20474 sizeBytes = stats.codeSize; 20475 } 20476 20477 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20478 freezer.close(); 20479 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20480 "Not enough free space to move"); 20481 } 20482 20483 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20484 20485 final CountDownLatch installedLatch = new CountDownLatch(1); 20486 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20487 @Override 20488 public void onUserActionRequired(Intent intent) throws RemoteException { 20489 throw new IllegalStateException(); 20490 } 20491 20492 @Override 20493 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20494 Bundle extras) throws RemoteException { 20495 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20496 + PackageManager.installStatusToString(returnCode, msg)); 20497 20498 installedLatch.countDown(); 20499 freezer.close(); 20500 20501 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20502 switch (status) { 20503 case PackageInstaller.STATUS_SUCCESS: 20504 mMoveCallbacks.notifyStatusChanged(moveId, 20505 PackageManager.MOVE_SUCCEEDED); 20506 break; 20507 case PackageInstaller.STATUS_FAILURE_STORAGE: 20508 mMoveCallbacks.notifyStatusChanged(moveId, 20509 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20510 break; 20511 default: 20512 mMoveCallbacks.notifyStatusChanged(moveId, 20513 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20514 break; 20515 } 20516 } 20517 }; 20518 20519 final MoveInfo move; 20520 if (moveCompleteApp) { 20521 // Kick off a thread to report progress estimates 20522 new Thread() { 20523 @Override 20524 public void run() { 20525 while (true) { 20526 try { 20527 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20528 break; 20529 } 20530 } catch (InterruptedException ignored) { 20531 } 20532 20533 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20534 final int progress = 10 + (int) MathUtils.constrain( 20535 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20536 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20537 } 20538 } 20539 }.start(); 20540 20541 final String dataAppName = codeFile.getName(); 20542 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20543 dataAppName, appId, seinfo, targetSdkVersion); 20544 } else { 20545 move = null; 20546 } 20547 20548 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20549 20550 final Message msg = mHandler.obtainMessage(INIT_COPY); 20551 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20552 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20553 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20554 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20555 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20556 msg.obj = params; 20557 20558 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20559 System.identityHashCode(msg.obj)); 20560 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20561 System.identityHashCode(msg.obj)); 20562 20563 mHandler.sendMessage(msg); 20564 } 20565 20566 @Override 20567 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20568 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20569 20570 final int realMoveId = mNextMoveId.getAndIncrement(); 20571 final Bundle extras = new Bundle(); 20572 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20573 mMoveCallbacks.notifyCreated(realMoveId, extras); 20574 20575 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20576 @Override 20577 public void onCreated(int moveId, Bundle extras) { 20578 // Ignored 20579 } 20580 20581 @Override 20582 public void onStatusChanged(int moveId, int status, long estMillis) { 20583 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20584 } 20585 }; 20586 20587 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20588 storage.setPrimaryStorageUuid(volumeUuid, callback); 20589 return realMoveId; 20590 } 20591 20592 @Override 20593 public int getMoveStatus(int moveId) { 20594 mContext.enforceCallingOrSelfPermission( 20595 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20596 return mMoveCallbacks.mLastStatus.get(moveId); 20597 } 20598 20599 @Override 20600 public void registerMoveCallback(IPackageMoveObserver callback) { 20601 mContext.enforceCallingOrSelfPermission( 20602 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20603 mMoveCallbacks.register(callback); 20604 } 20605 20606 @Override 20607 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20608 mContext.enforceCallingOrSelfPermission( 20609 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20610 mMoveCallbacks.unregister(callback); 20611 } 20612 20613 @Override 20614 public boolean setInstallLocation(int loc) { 20615 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20616 null); 20617 if (getInstallLocation() == loc) { 20618 return true; 20619 } 20620 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20621 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20622 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20623 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20624 return true; 20625 } 20626 return false; 20627 } 20628 20629 @Override 20630 public int getInstallLocation() { 20631 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20632 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20633 PackageHelper.APP_INSTALL_AUTO); 20634 } 20635 20636 /** Called by UserManagerService */ 20637 void cleanUpUser(UserManagerService userManager, int userHandle) { 20638 synchronized (mPackages) { 20639 mDirtyUsers.remove(userHandle); 20640 mUserNeedsBadging.delete(userHandle); 20641 mSettings.removeUserLPw(userHandle); 20642 mPendingBroadcasts.remove(userHandle); 20643 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20644 removeUnusedPackagesLPw(userManager, userHandle); 20645 } 20646 } 20647 20648 /** 20649 * We're removing userHandle and would like to remove any downloaded packages 20650 * that are no longer in use by any other user. 20651 * @param userHandle the user being removed 20652 */ 20653 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20654 final boolean DEBUG_CLEAN_APKS = false; 20655 int [] users = userManager.getUserIds(); 20656 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20657 while (psit.hasNext()) { 20658 PackageSetting ps = psit.next(); 20659 if (ps.pkg == null) { 20660 continue; 20661 } 20662 final String packageName = ps.pkg.packageName; 20663 // Skip over if system app 20664 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20665 continue; 20666 } 20667 if (DEBUG_CLEAN_APKS) { 20668 Slog.i(TAG, "Checking package " + packageName); 20669 } 20670 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20671 if (keep) { 20672 if (DEBUG_CLEAN_APKS) { 20673 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20674 } 20675 } else { 20676 for (int i = 0; i < users.length; i++) { 20677 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20678 keep = true; 20679 if (DEBUG_CLEAN_APKS) { 20680 Slog.i(TAG, " Keeping package " + packageName + " for user " 20681 + users[i]); 20682 } 20683 break; 20684 } 20685 } 20686 } 20687 if (!keep) { 20688 if (DEBUG_CLEAN_APKS) { 20689 Slog.i(TAG, " Removing package " + packageName); 20690 } 20691 mHandler.post(new Runnable() { 20692 public void run() { 20693 deletePackageX(packageName, userHandle, 0); 20694 } //end run 20695 }); 20696 } 20697 } 20698 } 20699 20700 /** Called by UserManagerService */ 20701 void createNewUser(int userId, String[] disallowedPackages) { 20702 synchronized (mInstallLock) { 20703 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 20704 } 20705 synchronized (mPackages) { 20706 scheduleWritePackageRestrictionsLocked(userId); 20707 scheduleWritePackageListLocked(userId); 20708 applyFactoryDefaultBrowserLPw(userId); 20709 primeDomainVerificationsLPw(userId); 20710 } 20711 } 20712 20713 void onNewUserCreated(final int userId) { 20714 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20715 // If permission review for legacy apps is required, we represent 20716 // dagerous permissions for such apps as always granted runtime 20717 // permissions to keep per user flag state whether review is needed. 20718 // Hence, if a new user is added we have to propagate dangerous 20719 // permission grants for these legacy apps. 20720 if (mPermissionReviewRequired) { 20721 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20722 | UPDATE_PERMISSIONS_REPLACE_ALL); 20723 } 20724 } 20725 20726 @Override 20727 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20728 mContext.enforceCallingOrSelfPermission( 20729 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20730 "Only package verification agents can read the verifier device identity"); 20731 20732 synchronized (mPackages) { 20733 return mSettings.getVerifierDeviceIdentityLPw(); 20734 } 20735 } 20736 20737 @Override 20738 public void setPermissionEnforced(String permission, boolean enforced) { 20739 // TODO: Now that we no longer change GID for storage, this should to away. 20740 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20741 "setPermissionEnforced"); 20742 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20743 synchronized (mPackages) { 20744 if (mSettings.mReadExternalStorageEnforced == null 20745 || mSettings.mReadExternalStorageEnforced != enforced) { 20746 mSettings.mReadExternalStorageEnforced = enforced; 20747 mSettings.writeLPr(); 20748 } 20749 } 20750 // kill any non-foreground processes so we restart them and 20751 // grant/revoke the GID. 20752 final IActivityManager am = ActivityManagerNative.getDefault(); 20753 if (am != null) { 20754 final long token = Binder.clearCallingIdentity(); 20755 try { 20756 am.killProcessesBelowForeground("setPermissionEnforcement"); 20757 } catch (RemoteException e) { 20758 } finally { 20759 Binder.restoreCallingIdentity(token); 20760 } 20761 } 20762 } else { 20763 throw new IllegalArgumentException("No selective enforcement for " + permission); 20764 } 20765 } 20766 20767 @Override 20768 @Deprecated 20769 public boolean isPermissionEnforced(String permission) { 20770 return true; 20771 } 20772 20773 @Override 20774 public boolean isStorageLow() { 20775 final long token = Binder.clearCallingIdentity(); 20776 try { 20777 final DeviceStorageMonitorInternal 20778 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20779 if (dsm != null) { 20780 return dsm.isMemoryLow(); 20781 } else { 20782 return false; 20783 } 20784 } finally { 20785 Binder.restoreCallingIdentity(token); 20786 } 20787 } 20788 20789 @Override 20790 public IPackageInstaller getPackageInstaller() { 20791 return mInstallerService; 20792 } 20793 20794 private boolean userNeedsBadging(int userId) { 20795 int index = mUserNeedsBadging.indexOfKey(userId); 20796 if (index < 0) { 20797 final UserInfo userInfo; 20798 final long token = Binder.clearCallingIdentity(); 20799 try { 20800 userInfo = sUserManager.getUserInfo(userId); 20801 } finally { 20802 Binder.restoreCallingIdentity(token); 20803 } 20804 final boolean b; 20805 if (userInfo != null && userInfo.isManagedProfile()) { 20806 b = true; 20807 } else { 20808 b = false; 20809 } 20810 mUserNeedsBadging.put(userId, b); 20811 return b; 20812 } 20813 return mUserNeedsBadging.valueAt(index); 20814 } 20815 20816 @Override 20817 public KeySet getKeySetByAlias(String packageName, String alias) { 20818 if (packageName == null || alias == null) { 20819 return null; 20820 } 20821 synchronized(mPackages) { 20822 final PackageParser.Package pkg = mPackages.get(packageName); 20823 if (pkg == null) { 20824 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20825 throw new IllegalArgumentException("Unknown package: " + packageName); 20826 } 20827 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20828 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20829 } 20830 } 20831 20832 @Override 20833 public KeySet getSigningKeySet(String packageName) { 20834 if (packageName == null) { 20835 return null; 20836 } 20837 synchronized(mPackages) { 20838 final PackageParser.Package pkg = mPackages.get(packageName); 20839 if (pkg == null) { 20840 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20841 throw new IllegalArgumentException("Unknown package: " + packageName); 20842 } 20843 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20844 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20845 throw new SecurityException("May not access signing KeySet of other apps."); 20846 } 20847 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20848 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20849 } 20850 } 20851 20852 @Override 20853 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20854 if (packageName == null || ks == null) { 20855 return false; 20856 } 20857 synchronized(mPackages) { 20858 final PackageParser.Package pkg = mPackages.get(packageName); 20859 if (pkg == null) { 20860 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20861 throw new IllegalArgumentException("Unknown package: " + packageName); 20862 } 20863 IBinder ksh = ks.getToken(); 20864 if (ksh instanceof KeySetHandle) { 20865 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20866 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20867 } 20868 return false; 20869 } 20870 } 20871 20872 @Override 20873 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20874 if (packageName == null || ks == null) { 20875 return false; 20876 } 20877 synchronized(mPackages) { 20878 final PackageParser.Package pkg = mPackages.get(packageName); 20879 if (pkg == null) { 20880 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20881 throw new IllegalArgumentException("Unknown package: " + packageName); 20882 } 20883 IBinder ksh = ks.getToken(); 20884 if (ksh instanceof KeySetHandle) { 20885 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20886 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20887 } 20888 return false; 20889 } 20890 } 20891 20892 private void deletePackageIfUnusedLPr(final String packageName) { 20893 PackageSetting ps = mSettings.mPackages.get(packageName); 20894 if (ps == null) { 20895 return; 20896 } 20897 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20898 // TODO Implement atomic delete if package is unused 20899 // It is currently possible that the package will be deleted even if it is installed 20900 // after this method returns. 20901 mHandler.post(new Runnable() { 20902 public void run() { 20903 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20904 } 20905 }); 20906 } 20907 } 20908 20909 /** 20910 * Check and throw if the given before/after packages would be considered a 20911 * downgrade. 20912 */ 20913 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20914 throws PackageManagerException { 20915 if (after.versionCode < before.mVersionCode) { 20916 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20917 "Update version code " + after.versionCode + " is older than current " 20918 + before.mVersionCode); 20919 } else if (after.versionCode == before.mVersionCode) { 20920 if (after.baseRevisionCode < before.baseRevisionCode) { 20921 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20922 "Update base revision code " + after.baseRevisionCode 20923 + " is older than current " + before.baseRevisionCode); 20924 } 20925 20926 if (!ArrayUtils.isEmpty(after.splitNames)) { 20927 for (int i = 0; i < after.splitNames.length; i++) { 20928 final String splitName = after.splitNames[i]; 20929 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20930 if (j != -1) { 20931 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20932 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20933 "Update split " + splitName + " revision code " 20934 + after.splitRevisionCodes[i] + " is older than current " 20935 + before.splitRevisionCodes[j]); 20936 } 20937 } 20938 } 20939 } 20940 } 20941 } 20942 20943 private static class MoveCallbacks extends Handler { 20944 private static final int MSG_CREATED = 1; 20945 private static final int MSG_STATUS_CHANGED = 2; 20946 20947 private final RemoteCallbackList<IPackageMoveObserver> 20948 mCallbacks = new RemoteCallbackList<>(); 20949 20950 private final SparseIntArray mLastStatus = new SparseIntArray(); 20951 20952 public MoveCallbacks(Looper looper) { 20953 super(looper); 20954 } 20955 20956 public void register(IPackageMoveObserver callback) { 20957 mCallbacks.register(callback); 20958 } 20959 20960 public void unregister(IPackageMoveObserver callback) { 20961 mCallbacks.unregister(callback); 20962 } 20963 20964 @Override 20965 public void handleMessage(Message msg) { 20966 final SomeArgs args = (SomeArgs) msg.obj; 20967 final int n = mCallbacks.beginBroadcast(); 20968 for (int i = 0; i < n; i++) { 20969 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20970 try { 20971 invokeCallback(callback, msg.what, args); 20972 } catch (RemoteException ignored) { 20973 } 20974 } 20975 mCallbacks.finishBroadcast(); 20976 args.recycle(); 20977 } 20978 20979 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20980 throws RemoteException { 20981 switch (what) { 20982 case MSG_CREATED: { 20983 callback.onCreated(args.argi1, (Bundle) args.arg2); 20984 break; 20985 } 20986 case MSG_STATUS_CHANGED: { 20987 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20988 break; 20989 } 20990 } 20991 } 20992 20993 private void notifyCreated(int moveId, Bundle extras) { 20994 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20995 20996 final SomeArgs args = SomeArgs.obtain(); 20997 args.argi1 = moveId; 20998 args.arg2 = extras; 20999 obtainMessage(MSG_CREATED, args).sendToTarget(); 21000 } 21001 21002 private void notifyStatusChanged(int moveId, int status) { 21003 notifyStatusChanged(moveId, status, -1); 21004 } 21005 21006 private void notifyStatusChanged(int moveId, int status, long estMillis) { 21007 Slog.v(TAG, "Move " + moveId + " status " + status); 21008 21009 final SomeArgs args = SomeArgs.obtain(); 21010 args.argi1 = moveId; 21011 args.argi2 = status; 21012 args.arg3 = estMillis; 21013 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 21014 21015 synchronized (mLastStatus) { 21016 mLastStatus.put(moveId, status); 21017 } 21018 } 21019 } 21020 21021 private final static class OnPermissionChangeListeners extends Handler { 21022 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 21023 21024 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 21025 new RemoteCallbackList<>(); 21026 21027 public OnPermissionChangeListeners(Looper looper) { 21028 super(looper); 21029 } 21030 21031 @Override 21032 public void handleMessage(Message msg) { 21033 switch (msg.what) { 21034 case MSG_ON_PERMISSIONS_CHANGED: { 21035 final int uid = msg.arg1; 21036 handleOnPermissionsChanged(uid); 21037 } break; 21038 } 21039 } 21040 21041 public void addListenerLocked(IOnPermissionsChangeListener listener) { 21042 mPermissionListeners.register(listener); 21043 21044 } 21045 21046 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 21047 mPermissionListeners.unregister(listener); 21048 } 21049 21050 public void onPermissionsChanged(int uid) { 21051 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 21052 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 21053 } 21054 } 21055 21056 private void handleOnPermissionsChanged(int uid) { 21057 final int count = mPermissionListeners.beginBroadcast(); 21058 try { 21059 for (int i = 0; i < count; i++) { 21060 IOnPermissionsChangeListener callback = mPermissionListeners 21061 .getBroadcastItem(i); 21062 try { 21063 callback.onPermissionsChanged(uid); 21064 } catch (RemoteException e) { 21065 Log.e(TAG, "Permission listener is dead", e); 21066 } 21067 } 21068 } finally { 21069 mPermissionListeners.finishBroadcast(); 21070 } 21071 } 21072 } 21073 21074 private class PackageManagerInternalImpl extends PackageManagerInternal { 21075 @Override 21076 public void setLocationPackagesProvider(PackagesProvider provider) { 21077 synchronized (mPackages) { 21078 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 21079 } 21080 } 21081 21082 @Override 21083 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 21084 synchronized (mPackages) { 21085 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 21086 } 21087 } 21088 21089 @Override 21090 public void setSmsAppPackagesProvider(PackagesProvider provider) { 21091 synchronized (mPackages) { 21092 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 21093 } 21094 } 21095 21096 @Override 21097 public void setDialerAppPackagesProvider(PackagesProvider provider) { 21098 synchronized (mPackages) { 21099 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 21100 } 21101 } 21102 21103 @Override 21104 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 21105 synchronized (mPackages) { 21106 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 21107 } 21108 } 21109 21110 @Override 21111 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 21112 synchronized (mPackages) { 21113 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 21114 } 21115 } 21116 21117 @Override 21118 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 21119 synchronized (mPackages) { 21120 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 21121 packageName, userId); 21122 } 21123 } 21124 21125 @Override 21126 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 21127 synchronized (mPackages) { 21128 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 21129 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 21130 packageName, userId); 21131 } 21132 } 21133 21134 @Override 21135 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 21136 synchronized (mPackages) { 21137 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 21138 packageName, userId); 21139 } 21140 } 21141 21142 @Override 21143 public void setKeepUninstalledPackages(final List<String> packageList) { 21144 Preconditions.checkNotNull(packageList); 21145 List<String> removedFromList = null; 21146 synchronized (mPackages) { 21147 if (mKeepUninstalledPackages != null) { 21148 final int packagesCount = mKeepUninstalledPackages.size(); 21149 for (int i = 0; i < packagesCount; i++) { 21150 String oldPackage = mKeepUninstalledPackages.get(i); 21151 if (packageList != null && packageList.contains(oldPackage)) { 21152 continue; 21153 } 21154 if (removedFromList == null) { 21155 removedFromList = new ArrayList<>(); 21156 } 21157 removedFromList.add(oldPackage); 21158 } 21159 } 21160 mKeepUninstalledPackages = new ArrayList<>(packageList); 21161 if (removedFromList != null) { 21162 final int removedCount = removedFromList.size(); 21163 for (int i = 0; i < removedCount; i++) { 21164 deletePackageIfUnusedLPr(removedFromList.get(i)); 21165 } 21166 } 21167 } 21168 } 21169 21170 @Override 21171 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21172 synchronized (mPackages) { 21173 // If we do not support permission review, done. 21174 if (!mPermissionReviewRequired) { 21175 return false; 21176 } 21177 21178 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21179 if (packageSetting == null) { 21180 return false; 21181 } 21182 21183 // Permission review applies only to apps not supporting the new permission model. 21184 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21185 return false; 21186 } 21187 21188 // Legacy apps have the permission and get user consent on launch. 21189 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21190 return permissionsState.isPermissionReviewRequired(userId); 21191 } 21192 } 21193 21194 @Override 21195 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21196 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21197 } 21198 21199 @Override 21200 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21201 int userId) { 21202 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21203 } 21204 21205 @Override 21206 public void setDeviceAndProfileOwnerPackages( 21207 int deviceOwnerUserId, String deviceOwnerPackage, 21208 SparseArray<String> profileOwnerPackages) { 21209 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21210 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21211 } 21212 21213 @Override 21214 public boolean isPackageDataProtected(int userId, String packageName) { 21215 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21216 } 21217 21218 @Override 21219 public boolean wasPackageEverLaunched(String packageName, int userId) { 21220 synchronized (mPackages) { 21221 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21222 } 21223 } 21224 21225 @Override 21226 public void grantRuntimePermission(String packageName, String name, int userId, 21227 boolean overridePolicy) { 21228 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 21229 overridePolicy); 21230 } 21231 21232 @Override 21233 public void revokeRuntimePermission(String packageName, String name, int userId, 21234 boolean overridePolicy) { 21235 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 21236 overridePolicy); 21237 } 21238 21239 @Override 21240 public String getNameForUid(int uid) { 21241 return PackageManagerService.this.getNameForUid(uid); 21242 } 21243 21244 @Override 21245 public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 21246 Intent origIntent, String resolvedType, Intent launchIntent, 21247 String callingPackage, int userId) { 21248 PackageManagerService.this.requestEphemeralResolutionPhaseTwo( 21249 responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId); 21250 } 21251 } 21252 21253 @Override 21254 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21255 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21256 synchronized (mPackages) { 21257 final long identity = Binder.clearCallingIdentity(); 21258 try { 21259 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21260 packageNames, userId); 21261 } finally { 21262 Binder.restoreCallingIdentity(identity); 21263 } 21264 } 21265 } 21266 21267 private static void enforceSystemOrPhoneCaller(String tag) { 21268 int callingUid = Binder.getCallingUid(); 21269 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21270 throw new SecurityException( 21271 "Cannot call " + tag + " from UID " + callingUid); 21272 } 21273 } 21274 21275 boolean isHistoricalPackageUsageAvailable() { 21276 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21277 } 21278 21279 /** 21280 * Return a <b>copy</b> of the collection of packages known to the package manager. 21281 * @return A copy of the values of mPackages. 21282 */ 21283 Collection<PackageParser.Package> getPackages() { 21284 synchronized (mPackages) { 21285 return new ArrayList<>(mPackages.values()); 21286 } 21287 } 21288 21289 /** 21290 * Logs process start information (including base APK hash) to the security log. 21291 * @hide 21292 */ 21293 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21294 String apkFile, int pid) { 21295 if (!SecurityLog.isLoggingEnabled()) { 21296 return; 21297 } 21298 Bundle data = new Bundle(); 21299 data.putLong("startTimestamp", System.currentTimeMillis()); 21300 data.putString("processName", processName); 21301 data.putInt("uid", uid); 21302 data.putString("seinfo", seinfo); 21303 data.putString("apkFile", apkFile); 21304 data.putInt("pid", pid); 21305 Message msg = mProcessLoggingHandler.obtainMessage( 21306 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21307 msg.setData(data); 21308 mProcessLoggingHandler.sendMessage(msg); 21309 } 21310 21311 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21312 return mCompilerStats.getPackageStats(pkgName); 21313 } 21314 21315 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21316 return getOrCreateCompilerPackageStats(pkg.packageName); 21317 } 21318 21319 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21320 return mCompilerStats.getOrCreatePackageStats(pkgName); 21321 } 21322 21323 public void deleteCompilerPackageStats(String pkgName) { 21324 mCompilerStats.deletePackageStats(pkgName); 21325 } 21326} 21327