PackageManagerService.java revision 98802f6007eef7a36237087111c38a998a388903
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_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Process.PACKAGE_INFO_GID; 80import static android.os.Process.SYSTEM_UID; 81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 82import static android.system.OsConstants.O_CREAT; 83import static android.system.OsConstants.O_RDWR; 84 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 89import static com.android.internal.util.ArrayUtils.appendInt; 90import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 101 102import android.Manifest; 103import android.annotation.NonNull; 104import android.annotation.Nullable; 105import android.annotation.UserIdInt; 106import android.app.ActivityManager; 107import android.app.ActivityManagerNative; 108import android.app.IActivityManager; 109import android.app.ResourcesManager; 110import android.app.admin.IDevicePolicyManager; 111import android.app.admin.SecurityLog; 112import android.app.backup.IBackupManager; 113import android.content.BroadcastReceiver; 114import android.content.ComponentName; 115import android.content.Context; 116import android.content.IIntentReceiver; 117import android.content.Intent; 118import android.content.IntentFilter; 119import android.content.IntentSender; 120import android.content.IntentSender.SendIntentException; 121import android.content.ServiceConnection; 122import android.content.pm.ActivityInfo; 123import android.content.pm.ApplicationInfo; 124import android.content.pm.AppsQueryHelper; 125import android.content.pm.ComponentInfo; 126import android.content.pm.EphemeralApplicationInfo; 127import android.content.pm.EphemeralResolveInfo; 128import android.content.pm.EphemeralResolveInfo.EphemeralDigest; 129import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 130import android.content.pm.FeatureInfo; 131import android.content.pm.IOnPermissionsChangeListener; 132import android.content.pm.IPackageDataObserver; 133import android.content.pm.IPackageDeleteObserver; 134import android.content.pm.IPackageDeleteObserver2; 135import android.content.pm.IPackageInstallObserver2; 136import android.content.pm.IPackageInstaller; 137import android.content.pm.IPackageManager; 138import android.content.pm.IPackageMoveObserver; 139import android.content.pm.IPackageStatsObserver; 140import android.content.pm.InstrumentationInfo; 141import android.content.pm.IntentFilterVerificationInfo; 142import android.content.pm.KeySet; 143import android.content.pm.PackageCleanItem; 144import android.content.pm.PackageInfo; 145import android.content.pm.PackageInfoLite; 146import android.content.pm.PackageInstaller; 147import android.content.pm.PackageManager; 148import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 149import android.content.pm.PackageManagerInternal; 150import android.content.pm.PackageParser; 151import android.content.pm.PackageParser.ActivityIntentInfo; 152import android.content.pm.PackageParser.PackageLite; 153import android.content.pm.PackageParser.PackageParserException; 154import android.content.pm.PackageStats; 155import android.content.pm.PackageUserState; 156import android.content.pm.ParceledListSlice; 157import android.content.pm.PermissionGroupInfo; 158import android.content.pm.PermissionInfo; 159import android.content.pm.ProviderInfo; 160import android.content.pm.ResolveInfo; 161import android.content.pm.ServiceInfo; 162import android.content.pm.ShortcutServiceInternal; 163import android.content.pm.Signature; 164import android.content.pm.UserInfo; 165import android.content.pm.VerifierDeviceIdentity; 166import android.content.pm.VerifierInfo; 167import android.content.res.Resources; 168import android.graphics.Bitmap; 169import android.hardware.display.DisplayManager; 170import android.net.Uri; 171import android.os.Binder; 172import android.os.Build; 173import android.os.Bundle; 174import android.os.Debug; 175import android.os.Environment; 176import android.os.Environment.UserEnvironment; 177import android.os.FileUtils; 178import android.os.Handler; 179import android.os.IBinder; 180import android.os.Looper; 181import android.os.Message; 182import android.os.Parcel; 183import android.os.ParcelFileDescriptor; 184import android.os.Process; 185import android.os.RemoteCallbackList; 186import android.os.RemoteException; 187import android.os.ResultReceiver; 188import android.os.SELinux; 189import android.os.ServiceManager; 190import android.os.SystemClock; 191import android.os.SystemProperties; 192import android.os.Trace; 193import android.os.UserHandle; 194import android.os.UserManager; 195import android.os.UserManagerInternal; 196import android.os.storage.IMountService; 197import android.os.storage.MountServiceInternal; 198import android.os.storage.StorageEventListener; 199import android.os.storage.StorageManager; 200import android.os.storage.VolumeInfo; 201import android.os.storage.VolumeRecord; 202import android.provider.Settings.Global; 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.AtomicFile; 212import android.util.DisplayMetrics; 213import android.util.EventLog; 214import android.util.ExceptionUtils; 215import android.util.Log; 216import android.util.LogPrinter; 217import android.util.MathUtils; 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.BufferedInputStream; 271import java.io.BufferedOutputStream; 272import java.io.BufferedReader; 273import java.io.ByteArrayInputStream; 274import java.io.ByteArrayOutputStream; 275import java.io.File; 276import java.io.FileDescriptor; 277import java.io.FileInputStream; 278import java.io.FileNotFoundException; 279import java.io.FileOutputStream; 280import java.io.FileReader; 281import java.io.FilenameFilter; 282import java.io.IOException; 283import java.io.InputStream; 284import java.io.PrintWriter; 285import java.nio.charset.StandardCharsets; 286import java.security.DigestInputStream; 287import java.security.MessageDigest; 288import java.security.NoSuchAlgorithmException; 289import java.security.PublicKey; 290import java.security.cert.Certificate; 291import java.security.cert.CertificateEncodingException; 292import java.security.cert.CertificateException; 293import java.text.SimpleDateFormat; 294import java.util.ArrayList; 295import java.util.Arrays; 296import java.util.Collection; 297import java.util.Collections; 298import java.util.Comparator; 299import java.util.Date; 300import java.util.HashSet; 301import java.util.Iterator; 302import java.util.List; 303import java.util.Map; 304import java.util.Objects; 305import java.util.Set; 306import java.util.concurrent.CountDownLatch; 307import java.util.concurrent.TimeUnit; 308import java.util.concurrent.atomic.AtomicBoolean; 309import java.util.concurrent.atomic.AtomicInteger; 310import java.util.concurrent.atomic.AtomicLong; 311 312/** 313 * Keep track of all those APKs everywhere. 314 * <p> 315 * Internally there are two important locks: 316 * <ul> 317 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 318 * and other related state. It is a fine-grained lock that should only be held 319 * momentarily, as it's one of the most contended locks in the system. 320 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 321 * operations typically involve heavy lifting of application data on disk. Since 322 * {@code installd} is single-threaded, and it's operations can often be slow, 323 * this lock should never be acquired while already holding {@link #mPackages}. 324 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 325 * holding {@link #mInstallLock}. 326 * </ul> 327 * Many internal methods rely on the caller to hold the appropriate locks, and 328 * this contract is expressed through method name suffixes: 329 * <ul> 330 * <li>fooLI(): the caller must hold {@link #mInstallLock} 331 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 332 * being modified must be frozen 333 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 334 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 335 * </ul> 336 * <p> 337 * Because this class is very central to the platform's security; please run all 338 * CTS and unit tests whenever making modifications: 339 * 340 * <pre> 341 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 342 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 343 * </pre> 344 */ 345public class PackageManagerService extends IPackageManager.Stub { 346 static final String TAG = "PackageManager"; 347 static final boolean DEBUG_SETTINGS = false; 348 static final boolean DEBUG_PREFERRED = false; 349 static final boolean DEBUG_UPGRADE = false; 350 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 351 private static final boolean DEBUG_BACKUP = false; 352 private static final boolean DEBUG_INSTALL = false; 353 private static final boolean DEBUG_REMOVE = false; 354 private static final boolean DEBUG_BROADCASTS = false; 355 private static final boolean DEBUG_SHOW_INFO = false; 356 private static final boolean DEBUG_PACKAGE_INFO = false; 357 private static final boolean DEBUG_INTENT_MATCHING = false; 358 private static final boolean DEBUG_PACKAGE_SCANNING = false; 359 private static final boolean DEBUG_VERIFY = false; 360 private static final boolean DEBUG_FILTERS = false; 361 362 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 363 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 364 // user, but by default initialize to this. 365 static final boolean DEBUG_DEXOPT = false; 366 367 private static final boolean DEBUG_ABI_SELECTION = false; 368 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 369 private static final boolean DEBUG_TRIAGED_MISSING = false; 370 private static final boolean DEBUG_APP_DATA = false; 371 372 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 373 374 private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE; 375 376 private static final int RADIO_UID = Process.PHONE_UID; 377 private static final int LOG_UID = Process.LOG_UID; 378 private static final int NFC_UID = Process.NFC_UID; 379 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 380 private static final int SHELL_UID = Process.SHELL_UID; 381 382 // Cap the size of permission trees that 3rd party apps can define 383 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 384 385 // Suffix used during package installation when copying/moving 386 // package apks to install directory. 387 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 388 389 static final int SCAN_NO_DEX = 1<<1; 390 static final int SCAN_FORCE_DEX = 1<<2; 391 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 392 static final int SCAN_NEW_INSTALL = 1<<4; 393 static final int SCAN_NO_PATHS = 1<<5; 394 static final int SCAN_UPDATE_TIME = 1<<6; 395 static final int SCAN_DEFER_DEX = 1<<7; 396 static final int SCAN_BOOTING = 1<<8; 397 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 398 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 399 static final int SCAN_REPLACING = 1<<11; 400 static final int SCAN_REQUIRE_KNOWN = 1<<12; 401 static final int SCAN_MOVE = 1<<13; 402 static final int SCAN_INITIAL = 1<<14; 403 static final int SCAN_CHECK_ONLY = 1<<15; 404 static final int SCAN_DONT_KILL_APP = 1<<17; 405 static final int SCAN_IGNORE_FROZEN = 1<<18; 406 407 static final int REMOVE_CHATTY = 1<<16; 408 409 private static final int[] EMPTY_INT_ARRAY = new int[0]; 410 411 /** 412 * Timeout (in milliseconds) after which the watchdog should declare that 413 * our handler thread is wedged. The usual default for such things is one 414 * minute but we sometimes do very lengthy I/O operations on this thread, 415 * such as installing multi-gigabyte applications, so ours needs to be longer. 416 */ 417 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 418 419 /** 420 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 421 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 422 * settings entry if available, otherwise we use the hardcoded default. If it's been 423 * more than this long since the last fstrim, we force one during the boot sequence. 424 * 425 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 426 * one gets run at the next available charging+idle time. This final mandatory 427 * no-fstrim check kicks in only of the other scheduling criteria is never met. 428 */ 429 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 430 431 /** 432 * Whether verification is enabled by default. 433 */ 434 private static final boolean DEFAULT_VERIFY_ENABLE = true; 435 436 /** 437 * The default maximum time to wait for the verification agent to return in 438 * milliseconds. 439 */ 440 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 441 442 /** 443 * The default response for package verification timeout. 444 * 445 * This can be either PackageManager.VERIFICATION_ALLOW or 446 * PackageManager.VERIFICATION_REJECT. 447 */ 448 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 449 450 static final String PLATFORM_PACKAGE_NAME = "android"; 451 452 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 453 454 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 455 DEFAULT_CONTAINER_PACKAGE, 456 "com.android.defcontainer.DefaultContainerService"); 457 458 private static final String KILL_APP_REASON_GIDS_CHANGED = 459 "permission grant or revoke changed gids"; 460 461 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 462 "permissions revoked"; 463 464 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 465 466 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 467 468 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000; 469 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5; 470 471 /** Permission grant: not grant the permission. */ 472 private static final int GRANT_DENIED = 1; 473 474 /** Permission grant: grant the permission as an install permission. */ 475 private static final int GRANT_INSTALL = 2; 476 477 /** Permission grant: grant the permission as a runtime one. */ 478 private static final int GRANT_RUNTIME = 3; 479 480 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 481 private static final int GRANT_UPGRADE = 4; 482 483 /** Canonical intent used to identify what counts as a "web browser" app */ 484 private static final Intent sBrowserIntent; 485 static { 486 sBrowserIntent = new Intent(); 487 sBrowserIntent.setAction(Intent.ACTION_VIEW); 488 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 489 sBrowserIntent.setData(Uri.parse("http:")); 490 } 491 492 /** 493 * The set of all protected actions [i.e. those actions for which a high priority 494 * intent filter is disallowed]. 495 */ 496 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 497 static { 498 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 499 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 500 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 501 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 502 } 503 504 // Compilation reasons. 505 public static final int REASON_FIRST_BOOT = 0; 506 public static final int REASON_BOOT = 1; 507 public static final int REASON_INSTALL = 2; 508 public static final int REASON_BACKGROUND_DEXOPT = 3; 509 public static final int REASON_AB_OTA = 4; 510 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 511 public static final int REASON_SHARED_APK = 6; 512 public static final int REASON_FORCED_DEXOPT = 7; 513 public static final int REASON_CORE_APP = 8; 514 515 public static final int REASON_LAST = REASON_CORE_APP; 516 517 /** Special library name that skips shared libraries check during compilation. */ 518 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 519 520 final ServiceThread mHandlerThread; 521 522 final PackageHandler mHandler; 523 524 private final ProcessLoggingHandler mProcessLoggingHandler; 525 526 /** 527 * Messages for {@link #mHandler} that need to wait for system ready before 528 * being dispatched. 529 */ 530 private ArrayList<Message> mPostSystemReadyMessages; 531 532 final int mSdkVersion = Build.VERSION.SDK_INT; 533 534 final Context mContext; 535 final boolean mFactoryTest; 536 final boolean mOnlyCore; 537 final DisplayMetrics mMetrics; 538 final int mDefParseFlags; 539 final String[] mSeparateProcesses; 540 final boolean mIsUpgrade; 541 final boolean mIsPreNUpgrade; 542 543 /** The location for ASEC container files on internal storage. */ 544 final String mAsecInternalPath; 545 546 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 547 // LOCK HELD. Can be called with mInstallLock held. 548 @GuardedBy("mInstallLock") 549 final Installer mInstaller; 550 551 /** Directory where installed third-party apps stored */ 552 final File mAppInstallDir; 553 final File mEphemeralInstallDir; 554 555 /** 556 * Directory to which applications installed internally have their 557 * 32 bit native libraries copied. 558 */ 559 private File mAppLib32InstallDir; 560 561 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 562 // apps. 563 final File mDrmAppPrivateInstallDir; 564 565 // ---------------------------------------------------------------- 566 567 // Lock for state used when installing and doing other long running 568 // operations. Methods that must be called with this lock held have 569 // the suffix "LI". 570 final Object mInstallLock = new Object(); 571 572 // ---------------------------------------------------------------- 573 574 // Keys are String (package name), values are Package. This also serves 575 // as the lock for the global state. Methods that must be called with 576 // this lock held have the prefix "LP". 577 @GuardedBy("mPackages") 578 final ArrayMap<String, PackageParser.Package> mPackages = 579 new ArrayMap<String, PackageParser.Package>(); 580 581 final ArrayMap<String, Set<String>> mKnownCodebase = 582 new ArrayMap<String, Set<String>>(); 583 584 // Tracks available target package names -> overlay package paths. 585 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 586 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 587 588 /** 589 * Tracks new system packages [received in an OTA] that we expect to 590 * find updated user-installed versions. Keys are package name, values 591 * are package location. 592 */ 593 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 594 /** 595 * Tracks high priority intent filters for protected actions. During boot, certain 596 * filter actions are protected and should never be allowed to have a high priority 597 * intent filter for them. However, there is one, and only one exception -- the 598 * setup wizard. It must be able to define a high priority intent filter for these 599 * actions to ensure there are no escapes from the wizard. We need to delay processing 600 * of these during boot as we need to look at all of the system packages in order 601 * to know which component is the setup wizard. 602 */ 603 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 604 /** 605 * Whether or not processing protected filters should be deferred. 606 */ 607 private boolean mDeferProtectedFilters = true; 608 609 /** 610 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 611 */ 612 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 613 /** 614 * Whether or not system app permissions should be promoted from install to runtime. 615 */ 616 boolean mPromoteSystemApps; 617 618 @GuardedBy("mPackages") 619 final Settings mSettings; 620 621 /** 622 * Set of package names that are currently "frozen", which means active 623 * surgery is being done on the code/data for that package. The platform 624 * will refuse to launch frozen packages to avoid race conditions. 625 * 626 * @see PackageFreezer 627 */ 628 @GuardedBy("mPackages") 629 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 630 631 final ProtectedPackages mProtectedPackages; 632 633 boolean mFirstBoot; 634 635 // System configuration read by SystemConfig. 636 final int[] mGlobalGids; 637 final SparseArray<ArraySet<String>> mSystemPermissions; 638 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 639 640 // If mac_permissions.xml was found for seinfo labeling. 641 boolean mFoundPolicyFile; 642 643 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 644 645 public static final class SharedLibraryEntry { 646 public final String path; 647 public final String apk; 648 649 SharedLibraryEntry(String _path, String _apk) { 650 path = _path; 651 apk = _apk; 652 } 653 } 654 655 // Currently known shared libraries. 656 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 657 new ArrayMap<String, SharedLibraryEntry>(); 658 659 // All available activities, for your resolving pleasure. 660 final ActivityIntentResolver mActivities = 661 new ActivityIntentResolver(); 662 663 // All available receivers, for your resolving pleasure. 664 final ActivityIntentResolver mReceivers = 665 new ActivityIntentResolver(); 666 667 // All available services, for your resolving pleasure. 668 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 669 670 // All available providers, for your resolving pleasure. 671 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 672 673 // Mapping from provider base names (first directory in content URI codePath) 674 // to the provider information. 675 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 676 new ArrayMap<String, PackageParser.Provider>(); 677 678 // Mapping from instrumentation class names to info about them. 679 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 680 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 681 682 // Mapping from permission names to info about them. 683 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 684 new ArrayMap<String, PackageParser.PermissionGroup>(); 685 686 // Packages whose data we have transfered into another package, thus 687 // should no longer exist. 688 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 689 690 // Broadcast actions that are only available to the system. 691 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 692 693 /** List of packages waiting for verification. */ 694 final SparseArray<PackageVerificationState> mPendingVerification 695 = new SparseArray<PackageVerificationState>(); 696 697 /** Set of packages associated with each app op permission. */ 698 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 699 700 final PackageInstallerService mInstallerService; 701 702 private final PackageDexOptimizer mPackageDexOptimizer; 703 704 private AtomicInteger mNextMoveId = new AtomicInteger(); 705 private final MoveCallbacks mMoveCallbacks; 706 707 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 708 709 // Cache of users who need badging. 710 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 711 712 /** Token for keys in mPendingVerification. */ 713 private int mPendingVerificationToken = 0; 714 715 volatile boolean mSystemReady; 716 volatile boolean mSafeMode; 717 volatile boolean mHasSystemUidErrors; 718 719 ApplicationInfo mAndroidApplication; 720 final ActivityInfo mResolveActivity = new ActivityInfo(); 721 final ResolveInfo mResolveInfo = new ResolveInfo(); 722 ComponentName mResolveComponentName; 723 PackageParser.Package mPlatformPackage; 724 ComponentName mCustomResolverComponentName; 725 726 boolean mResolverReplaced = false; 727 728 private final @Nullable ComponentName mIntentFilterVerifierComponent; 729 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 730 731 private int mIntentFilterVerificationToken = 0; 732 733 /** Component that knows whether or not an ephemeral application exists */ 734 final ComponentName mEphemeralResolverComponent; 735 /** The service connection to the ephemeral resolver */ 736 final EphemeralResolverConnection mEphemeralResolverConnection; 737 738 /** Component used to install ephemeral applications */ 739 final ComponentName mEphemeralInstallerComponent; 740 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 741 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 742 743 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 744 = new SparseArray<IntentFilterVerificationState>(); 745 746 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 747 new DefaultPermissionGrantPolicy(this); 748 749 // List of packages names to keep cached, even if they are uninstalled for all users 750 private List<String> mKeepUninstalledPackages; 751 752 private UserManagerInternal mUserManagerInternal; 753 754 private static class IFVerificationParams { 755 PackageParser.Package pkg; 756 boolean replacing; 757 int userId; 758 int verifierUid; 759 760 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 761 int _userId, int _verifierUid) { 762 pkg = _pkg; 763 replacing = _replacing; 764 userId = _userId; 765 replacing = _replacing; 766 verifierUid = _verifierUid; 767 } 768 } 769 770 private interface IntentFilterVerifier<T extends IntentFilter> { 771 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 772 T filter, String packageName); 773 void startVerifications(int userId); 774 void receiveVerificationResponse(int verificationId); 775 } 776 777 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 778 private Context mContext; 779 private ComponentName mIntentFilterVerifierComponent; 780 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 781 782 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 783 mContext = context; 784 mIntentFilterVerifierComponent = verifierComponent; 785 } 786 787 private String getDefaultScheme() { 788 return IntentFilter.SCHEME_HTTPS; 789 } 790 791 @Override 792 public void startVerifications(int userId) { 793 // Launch verifications requests 794 int count = mCurrentIntentFilterVerifications.size(); 795 for (int n=0; n<count; n++) { 796 int verificationId = mCurrentIntentFilterVerifications.get(n); 797 final IntentFilterVerificationState ivs = 798 mIntentFilterVerificationStates.get(verificationId); 799 800 String packageName = ivs.getPackageName(); 801 802 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 803 final int filterCount = filters.size(); 804 ArraySet<String> domainsSet = new ArraySet<>(); 805 for (int m=0; m<filterCount; m++) { 806 PackageParser.ActivityIntentInfo filter = filters.get(m); 807 domainsSet.addAll(filter.getHostsList()); 808 } 809 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 810 synchronized (mPackages) { 811 if (mSettings.createIntentFilterVerificationIfNeededLPw( 812 packageName, domainsList) != null) { 813 scheduleWriteSettingsLocked(); 814 } 815 } 816 sendVerificationRequest(userId, verificationId, ivs); 817 } 818 mCurrentIntentFilterVerifications.clear(); 819 } 820 821 private void sendVerificationRequest(int userId, int verificationId, 822 IntentFilterVerificationState ivs) { 823 824 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 825 verificationIntent.putExtra( 826 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 827 verificationId); 828 verificationIntent.putExtra( 829 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 830 getDefaultScheme()); 831 verificationIntent.putExtra( 832 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 833 ivs.getHostsString()); 834 verificationIntent.putExtra( 835 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 836 ivs.getPackageName()); 837 verificationIntent.setComponent(mIntentFilterVerifierComponent); 838 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 839 840 UserHandle user = new UserHandle(userId); 841 mContext.sendBroadcastAsUser(verificationIntent, user); 842 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 843 "Sending IntentFilter verification broadcast"); 844 } 845 846 public void receiveVerificationResponse(int verificationId) { 847 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 848 849 final boolean verified = ivs.isVerified(); 850 851 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 852 final int count = filters.size(); 853 if (DEBUG_DOMAIN_VERIFICATION) { 854 Slog.i(TAG, "Received verification response " + verificationId 855 + " for " + count + " filters, verified=" + verified); 856 } 857 for (int n=0; n<count; n++) { 858 PackageParser.ActivityIntentInfo filter = filters.get(n); 859 filter.setVerified(verified); 860 861 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 862 + " verified with result:" + verified + " and hosts:" 863 + ivs.getHostsString()); 864 } 865 866 mIntentFilterVerificationStates.remove(verificationId); 867 868 final String packageName = ivs.getPackageName(); 869 IntentFilterVerificationInfo ivi = null; 870 871 synchronized (mPackages) { 872 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 873 } 874 if (ivi == null) { 875 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 876 + verificationId + " packageName:" + packageName); 877 return; 878 } 879 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 880 "Updating IntentFilterVerificationInfo for package " + packageName 881 +" verificationId:" + verificationId); 882 883 synchronized (mPackages) { 884 if (verified) { 885 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 886 } else { 887 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 888 } 889 scheduleWriteSettingsLocked(); 890 891 final int userId = ivs.getUserId(); 892 if (userId != UserHandle.USER_ALL) { 893 final int userStatus = 894 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 895 896 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 897 boolean needUpdate = false; 898 899 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 900 // already been set by the User thru the Disambiguation dialog 901 switch (userStatus) { 902 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 903 if (verified) { 904 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 905 } else { 906 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 907 } 908 needUpdate = true; 909 break; 910 911 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 912 if (verified) { 913 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 914 needUpdate = true; 915 } 916 break; 917 918 default: 919 // Nothing to do 920 } 921 922 if (needUpdate) { 923 mSettings.updateIntentFilterVerificationStatusLPw( 924 packageName, updatedStatus, userId); 925 scheduleWritePackageRestrictionsLocked(userId); 926 } 927 } 928 } 929 } 930 931 @Override 932 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 933 ActivityIntentInfo filter, String packageName) { 934 if (!hasValidDomains(filter)) { 935 return false; 936 } 937 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 938 if (ivs == null) { 939 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 940 packageName); 941 } 942 if (DEBUG_DOMAIN_VERIFICATION) { 943 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 944 } 945 ivs.addFilter(filter); 946 return true; 947 } 948 949 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 950 int userId, int verificationId, String packageName) { 951 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 952 verifierUid, userId, packageName); 953 ivs.setPendingState(); 954 synchronized (mPackages) { 955 mIntentFilterVerificationStates.append(verificationId, ivs); 956 mCurrentIntentFilterVerifications.add(verificationId); 957 } 958 return ivs; 959 } 960 } 961 962 private static boolean hasValidDomains(ActivityIntentInfo filter) { 963 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 964 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 965 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 966 } 967 968 // Set of pending broadcasts for aggregating enable/disable of components. 969 static class PendingPackageBroadcasts { 970 // for each user id, a map of <package name -> components within that package> 971 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 972 973 public PendingPackageBroadcasts() { 974 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 975 } 976 977 public ArrayList<String> get(int userId, String packageName) { 978 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 979 return packages.get(packageName); 980 } 981 982 public void put(int userId, String packageName, ArrayList<String> components) { 983 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 984 packages.put(packageName, components); 985 } 986 987 public void remove(int userId, String packageName) { 988 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 989 if (packages != null) { 990 packages.remove(packageName); 991 } 992 } 993 994 public void remove(int userId) { 995 mUidMap.remove(userId); 996 } 997 998 public int userIdCount() { 999 return mUidMap.size(); 1000 } 1001 1002 public int userIdAt(int n) { 1003 return mUidMap.keyAt(n); 1004 } 1005 1006 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1007 return mUidMap.get(userId); 1008 } 1009 1010 public int size() { 1011 // total number of pending broadcast entries across all userIds 1012 int num = 0; 1013 for (int i = 0; i< mUidMap.size(); i++) { 1014 num += mUidMap.valueAt(i).size(); 1015 } 1016 return num; 1017 } 1018 1019 public void clear() { 1020 mUidMap.clear(); 1021 } 1022 1023 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1024 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1025 if (map == null) { 1026 map = new ArrayMap<String, ArrayList<String>>(); 1027 mUidMap.put(userId, map); 1028 } 1029 return map; 1030 } 1031 } 1032 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1033 1034 // Service Connection to remote media container service to copy 1035 // package uri's from external media onto secure containers 1036 // or internal storage. 1037 private IMediaContainerService mContainerService = null; 1038 1039 static final int SEND_PENDING_BROADCAST = 1; 1040 static final int MCS_BOUND = 3; 1041 static final int END_COPY = 4; 1042 static final int INIT_COPY = 5; 1043 static final int MCS_UNBIND = 6; 1044 static final int START_CLEANING_PACKAGE = 7; 1045 static final int FIND_INSTALL_LOC = 8; 1046 static final int POST_INSTALL = 9; 1047 static final int MCS_RECONNECT = 10; 1048 static final int MCS_GIVE_UP = 11; 1049 static final int UPDATED_MEDIA_STATUS = 12; 1050 static final int WRITE_SETTINGS = 13; 1051 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1052 static final int PACKAGE_VERIFIED = 15; 1053 static final int CHECK_PENDING_VERIFICATION = 16; 1054 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1055 static final int INTENT_FILTER_VERIFIED = 18; 1056 static final int WRITE_PACKAGE_LIST = 19; 1057 1058 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1059 1060 // Delay time in millisecs 1061 static final int BROADCAST_DELAY = 10 * 1000; 1062 1063 static UserManagerService sUserManager; 1064 1065 // Stores a list of users whose package restrictions file needs to be updated 1066 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1067 1068 final private DefaultContainerConnection mDefContainerConn = 1069 new DefaultContainerConnection(); 1070 class DefaultContainerConnection implements ServiceConnection { 1071 public void onServiceConnected(ComponentName name, IBinder service) { 1072 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1073 IMediaContainerService imcs = 1074 IMediaContainerService.Stub.asInterface(service); 1075 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1076 } 1077 1078 public void onServiceDisconnected(ComponentName name) { 1079 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1080 } 1081 } 1082 1083 // Recordkeeping of restore-after-install operations that are currently in flight 1084 // between the Package Manager and the Backup Manager 1085 static class PostInstallData { 1086 public InstallArgs args; 1087 public PackageInstalledInfo res; 1088 1089 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1090 args = _a; 1091 res = _r; 1092 } 1093 } 1094 1095 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1096 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1097 1098 // XML tags for backup/restore of various bits of state 1099 private static final String TAG_PREFERRED_BACKUP = "pa"; 1100 private static final String TAG_DEFAULT_APPS = "da"; 1101 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1102 1103 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1104 private static final String TAG_ALL_GRANTS = "rt-grants"; 1105 private static final String TAG_GRANT = "grant"; 1106 private static final String ATTR_PACKAGE_NAME = "pkg"; 1107 1108 private static final String TAG_PERMISSION = "perm"; 1109 private static final String ATTR_PERMISSION_NAME = "name"; 1110 private static final String ATTR_IS_GRANTED = "g"; 1111 private static final String ATTR_USER_SET = "set"; 1112 private static final String ATTR_USER_FIXED = "fixed"; 1113 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1114 1115 // System/policy permission grants are not backed up 1116 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1117 FLAG_PERMISSION_POLICY_FIXED 1118 | FLAG_PERMISSION_SYSTEM_FIXED 1119 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1120 1121 // And we back up these user-adjusted states 1122 private static final int USER_RUNTIME_GRANT_MASK = 1123 FLAG_PERMISSION_USER_SET 1124 | FLAG_PERMISSION_USER_FIXED 1125 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1126 1127 final @Nullable String mRequiredVerifierPackage; 1128 final @NonNull String mRequiredInstallerPackage; 1129 final @Nullable String mSetupWizardPackage; 1130 final @NonNull String mServicesSystemSharedLibraryPackageName; 1131 final @NonNull String mSharedSystemSharedLibraryPackageName; 1132 1133 private final PackageUsage mPackageUsage = new PackageUsage(); 1134 1135 private class PackageUsage { 1136 private static final int WRITE_INTERVAL 1137 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1138 1139 private final Object mFileLock = new Object(); 1140 private final AtomicLong mLastWritten = new AtomicLong(0); 1141 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1142 1143 private boolean mIsHistoricalPackageUsageAvailable = true; 1144 1145 boolean isHistoricalPackageUsageAvailable() { 1146 return mIsHistoricalPackageUsageAvailable; 1147 } 1148 1149 void write(boolean force) { 1150 if (force) { 1151 writeInternal(); 1152 return; 1153 } 1154 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1155 && !DEBUG_DEXOPT) { 1156 return; 1157 } 1158 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1159 new Thread("PackageUsage_DiskWriter") { 1160 @Override 1161 public void run() { 1162 try { 1163 writeInternal(); 1164 } finally { 1165 mBackgroundWriteRunning.set(false); 1166 } 1167 } 1168 }.start(); 1169 } 1170 } 1171 1172 private void writeInternal() { 1173 synchronized (mPackages) { 1174 synchronized (mFileLock) { 1175 AtomicFile file = getFile(); 1176 FileOutputStream f = null; 1177 try { 1178 f = file.startWrite(); 1179 BufferedOutputStream out = new BufferedOutputStream(f); 1180 FileUtils.setPermissions(file.getBaseFile().getPath(), 1181 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1182 StringBuilder sb = new StringBuilder(); 1183 1184 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1185 sb.append('\n'); 1186 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1187 1188 for (PackageParser.Package pkg : mPackages.values()) { 1189 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1190 continue; 1191 } 1192 sb.setLength(0); 1193 sb.append(pkg.packageName); 1194 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1195 sb.append(' '); 1196 sb.append(usageTimeInMillis); 1197 } 1198 sb.append('\n'); 1199 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1200 } 1201 out.flush(); 1202 file.finishWrite(f); 1203 } catch (IOException e) { 1204 if (f != null) { 1205 file.failWrite(f); 1206 } 1207 Log.e(TAG, "Failed to write package usage times", e); 1208 } 1209 } 1210 } 1211 mLastWritten.set(SystemClock.elapsedRealtime()); 1212 } 1213 1214 void readLP() { 1215 synchronized (mFileLock) { 1216 AtomicFile file = getFile(); 1217 BufferedInputStream in = null; 1218 try { 1219 in = new BufferedInputStream(file.openRead()); 1220 StringBuffer sb = new StringBuffer(); 1221 1222 String firstLine = readLine(in, sb); 1223 if (firstLine == null) { 1224 // Empty file. Do nothing. 1225 } else if (USAGE_FILE_MAGIC_VERSION_1.equals(firstLine)) { 1226 readVersion1LP(in, sb); 1227 } else { 1228 readVersion0LP(in, sb, firstLine); 1229 } 1230 } catch (FileNotFoundException expected) { 1231 mIsHistoricalPackageUsageAvailable = false; 1232 } catch (IOException e) { 1233 Log.w(TAG, "Failed to read package usage times", e); 1234 } finally { 1235 IoUtils.closeQuietly(in); 1236 } 1237 } 1238 mLastWritten.set(SystemClock.elapsedRealtime()); 1239 } 1240 1241 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1242 throws IOException { 1243 // Initial version of the file had no version number and stored one 1244 // package-timestamp pair per line. 1245 // Note that the first line has already been read from the InputStream. 1246 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1247 String[] tokens = line.split(" "); 1248 if (tokens.length != 2) { 1249 throw new IOException("Failed to parse " + line + 1250 " as package-timestamp pair."); 1251 } 1252 1253 String packageName = tokens[0]; 1254 PackageParser.Package pkg = mPackages.get(packageName); 1255 if (pkg == null) { 1256 continue; 1257 } 1258 1259 long timestamp = parseAsLong(tokens[1]); 1260 for (int reason = 0; 1261 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1262 reason++) { 1263 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1264 } 1265 } 1266 } 1267 1268 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1269 // Version 1 of the file started with the corresponding version 1270 // number and then stored a package name and eight timestamps per line. 1271 String line; 1272 while ((line = readLine(in, sb)) != null) { 1273 String[] tokens = line.split(" "); 1274 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1275 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1276 } 1277 1278 String packageName = tokens[0]; 1279 PackageParser.Package pkg = mPackages.get(packageName); 1280 if (pkg == null) { 1281 continue; 1282 } 1283 1284 for (int reason = 0; 1285 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1286 reason++) { 1287 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1288 } 1289 } 1290 } 1291 1292 private long parseAsLong(String token) throws IOException { 1293 try { 1294 return Long.parseLong(token); 1295 } catch (NumberFormatException e) { 1296 throw new IOException("Failed to parse " + token + " as a long.", e); 1297 } 1298 } 1299 1300 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1301 return readToken(in, sb, '\n'); 1302 } 1303 1304 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1305 throws IOException { 1306 sb.setLength(0); 1307 while (true) { 1308 int ch = in.read(); 1309 if (ch == -1) { 1310 if (sb.length() == 0) { 1311 return null; 1312 } 1313 throw new IOException("Unexpected EOF"); 1314 } 1315 if (ch == endOfToken) { 1316 return sb.toString(); 1317 } 1318 sb.append((char)ch); 1319 } 1320 } 1321 1322 private AtomicFile getFile() { 1323 File dataDir = Environment.getDataDirectory(); 1324 File systemDir = new File(dataDir, "system"); 1325 File fname = new File(systemDir, "package-usage.list"); 1326 return new AtomicFile(fname); 1327 } 1328 1329 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1330 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1331 } 1332 1333 class PackageHandler extends Handler { 1334 private boolean mBound = false; 1335 final ArrayList<HandlerParams> mPendingInstalls = 1336 new ArrayList<HandlerParams>(); 1337 1338 private boolean connectToService() { 1339 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1340 " DefaultContainerService"); 1341 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1342 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1343 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1344 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1345 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1346 mBound = true; 1347 return true; 1348 } 1349 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1350 return false; 1351 } 1352 1353 private void disconnectService() { 1354 mContainerService = null; 1355 mBound = false; 1356 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1357 mContext.unbindService(mDefContainerConn); 1358 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1359 } 1360 1361 PackageHandler(Looper looper) { 1362 super(looper); 1363 } 1364 1365 public void handleMessage(Message msg) { 1366 try { 1367 doHandleMessage(msg); 1368 } finally { 1369 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1370 } 1371 } 1372 1373 void doHandleMessage(Message msg) { 1374 switch (msg.what) { 1375 case INIT_COPY: { 1376 HandlerParams params = (HandlerParams) msg.obj; 1377 int idx = mPendingInstalls.size(); 1378 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1379 // If a bind was already initiated we dont really 1380 // need to do anything. The pending install 1381 // will be processed later on. 1382 if (!mBound) { 1383 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1384 System.identityHashCode(mHandler)); 1385 // If this is the only one pending we might 1386 // have to bind to the service again. 1387 if (!connectToService()) { 1388 Slog.e(TAG, "Failed to bind to media container service"); 1389 params.serviceError(); 1390 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1391 System.identityHashCode(mHandler)); 1392 if (params.traceMethod != null) { 1393 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1394 params.traceCookie); 1395 } 1396 return; 1397 } else { 1398 // Once we bind to the service, the first 1399 // pending request will be processed. 1400 mPendingInstalls.add(idx, params); 1401 } 1402 } else { 1403 mPendingInstalls.add(idx, params); 1404 // Already bound to the service. Just make 1405 // sure we trigger off processing the first request. 1406 if (idx == 0) { 1407 mHandler.sendEmptyMessage(MCS_BOUND); 1408 } 1409 } 1410 break; 1411 } 1412 case MCS_BOUND: { 1413 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1414 if (msg.obj != null) { 1415 mContainerService = (IMediaContainerService) msg.obj; 1416 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1417 System.identityHashCode(mHandler)); 1418 } 1419 if (mContainerService == null) { 1420 if (!mBound) { 1421 // Something seriously wrong since we are not bound and we are not 1422 // waiting for connection. Bail out. 1423 Slog.e(TAG, "Cannot bind to media container service"); 1424 for (HandlerParams params : mPendingInstalls) { 1425 // Indicate service bind error 1426 params.serviceError(); 1427 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1428 System.identityHashCode(params)); 1429 if (params.traceMethod != null) { 1430 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1431 params.traceMethod, params.traceCookie); 1432 } 1433 return; 1434 } 1435 mPendingInstalls.clear(); 1436 } else { 1437 Slog.w(TAG, "Waiting to connect to media container service"); 1438 } 1439 } else if (mPendingInstalls.size() > 0) { 1440 HandlerParams params = mPendingInstalls.get(0); 1441 if (params != null) { 1442 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1443 System.identityHashCode(params)); 1444 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1445 if (params.startCopy()) { 1446 // We are done... look for more work or to 1447 // go idle. 1448 if (DEBUG_SD_INSTALL) Log.i(TAG, 1449 "Checking for more work or unbind..."); 1450 // Delete pending install 1451 if (mPendingInstalls.size() > 0) { 1452 mPendingInstalls.remove(0); 1453 } 1454 if (mPendingInstalls.size() == 0) { 1455 if (mBound) { 1456 if (DEBUG_SD_INSTALL) Log.i(TAG, 1457 "Posting delayed MCS_UNBIND"); 1458 removeMessages(MCS_UNBIND); 1459 Message ubmsg = obtainMessage(MCS_UNBIND); 1460 // Unbind after a little delay, to avoid 1461 // continual thrashing. 1462 sendMessageDelayed(ubmsg, 10000); 1463 } 1464 } else { 1465 // There are more pending requests in queue. 1466 // Just post MCS_BOUND message to trigger processing 1467 // of next pending install. 1468 if (DEBUG_SD_INSTALL) Log.i(TAG, 1469 "Posting MCS_BOUND for next work"); 1470 mHandler.sendEmptyMessage(MCS_BOUND); 1471 } 1472 } 1473 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1474 } 1475 } else { 1476 // Should never happen ideally. 1477 Slog.w(TAG, "Empty queue"); 1478 } 1479 break; 1480 } 1481 case MCS_RECONNECT: { 1482 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1483 if (mPendingInstalls.size() > 0) { 1484 if (mBound) { 1485 disconnectService(); 1486 } 1487 if (!connectToService()) { 1488 Slog.e(TAG, "Failed to bind to media container service"); 1489 for (HandlerParams params : mPendingInstalls) { 1490 // Indicate service bind error 1491 params.serviceError(); 1492 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1493 System.identityHashCode(params)); 1494 } 1495 mPendingInstalls.clear(); 1496 } 1497 } 1498 break; 1499 } 1500 case MCS_UNBIND: { 1501 // If there is no actual work left, then time to unbind. 1502 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1503 1504 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1505 if (mBound) { 1506 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1507 1508 disconnectService(); 1509 } 1510 } else if (mPendingInstalls.size() > 0) { 1511 // There are more pending requests in queue. 1512 // Just post MCS_BOUND message to trigger processing 1513 // of next pending install. 1514 mHandler.sendEmptyMessage(MCS_BOUND); 1515 } 1516 1517 break; 1518 } 1519 case MCS_GIVE_UP: { 1520 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1521 HandlerParams params = mPendingInstalls.remove(0); 1522 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1523 System.identityHashCode(params)); 1524 break; 1525 } 1526 case SEND_PENDING_BROADCAST: { 1527 String packages[]; 1528 ArrayList<String> components[]; 1529 int size = 0; 1530 int uids[]; 1531 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1532 synchronized (mPackages) { 1533 if (mPendingBroadcasts == null) { 1534 return; 1535 } 1536 size = mPendingBroadcasts.size(); 1537 if (size <= 0) { 1538 // Nothing to be done. Just return 1539 return; 1540 } 1541 packages = new String[size]; 1542 components = new ArrayList[size]; 1543 uids = new int[size]; 1544 int i = 0; // filling out the above arrays 1545 1546 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1547 int packageUserId = mPendingBroadcasts.userIdAt(n); 1548 Iterator<Map.Entry<String, ArrayList<String>>> it 1549 = mPendingBroadcasts.packagesForUserId(packageUserId) 1550 .entrySet().iterator(); 1551 while (it.hasNext() && i < size) { 1552 Map.Entry<String, ArrayList<String>> ent = it.next(); 1553 packages[i] = ent.getKey(); 1554 components[i] = ent.getValue(); 1555 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1556 uids[i] = (ps != null) 1557 ? UserHandle.getUid(packageUserId, ps.appId) 1558 : -1; 1559 i++; 1560 } 1561 } 1562 size = i; 1563 mPendingBroadcasts.clear(); 1564 } 1565 // Send broadcasts 1566 for (int i = 0; i < size; i++) { 1567 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1568 } 1569 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1570 break; 1571 } 1572 case START_CLEANING_PACKAGE: { 1573 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1574 final String packageName = (String)msg.obj; 1575 final int userId = msg.arg1; 1576 final boolean andCode = msg.arg2 != 0; 1577 synchronized (mPackages) { 1578 if (userId == UserHandle.USER_ALL) { 1579 int[] users = sUserManager.getUserIds(); 1580 for (int user : users) { 1581 mSettings.addPackageToCleanLPw( 1582 new PackageCleanItem(user, packageName, andCode)); 1583 } 1584 } else { 1585 mSettings.addPackageToCleanLPw( 1586 new PackageCleanItem(userId, packageName, andCode)); 1587 } 1588 } 1589 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1590 startCleaningPackages(); 1591 } break; 1592 case POST_INSTALL: { 1593 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1594 1595 PostInstallData data = mRunningInstalls.get(msg.arg1); 1596 final boolean didRestore = (msg.arg2 != 0); 1597 mRunningInstalls.delete(msg.arg1); 1598 1599 if (data != null) { 1600 InstallArgs args = data.args; 1601 PackageInstalledInfo parentRes = data.res; 1602 1603 final boolean grantPermissions = (args.installFlags 1604 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1605 final boolean killApp = (args.installFlags 1606 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1607 final String[] grantedPermissions = args.installGrantPermissions; 1608 1609 // Handle the parent package 1610 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1611 grantedPermissions, didRestore, args.installerPackageName, 1612 args.observer); 1613 1614 // Handle the child packages 1615 final int childCount = (parentRes.addedChildPackages != null) 1616 ? parentRes.addedChildPackages.size() : 0; 1617 for (int i = 0; i < childCount; i++) { 1618 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1619 handlePackagePostInstall(childRes, grantPermissions, killApp, 1620 grantedPermissions, false, args.installerPackageName, 1621 args.observer); 1622 } 1623 1624 // Log tracing if needed 1625 if (args.traceMethod != null) { 1626 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1627 args.traceCookie); 1628 } 1629 } else { 1630 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1631 } 1632 1633 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1634 } break; 1635 case UPDATED_MEDIA_STATUS: { 1636 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1637 boolean reportStatus = msg.arg1 == 1; 1638 boolean doGc = msg.arg2 == 1; 1639 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1640 if (doGc) { 1641 // Force a gc to clear up stale containers. 1642 Runtime.getRuntime().gc(); 1643 } 1644 if (msg.obj != null) { 1645 @SuppressWarnings("unchecked") 1646 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1647 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1648 // Unload containers 1649 unloadAllContainers(args); 1650 } 1651 if (reportStatus) { 1652 try { 1653 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1654 PackageHelper.getMountService().finishMediaUpdate(); 1655 } catch (RemoteException e) { 1656 Log.e(TAG, "MountService not running?"); 1657 } 1658 } 1659 } break; 1660 case WRITE_SETTINGS: { 1661 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1662 synchronized (mPackages) { 1663 removeMessages(WRITE_SETTINGS); 1664 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1665 mSettings.writeLPr(); 1666 mDirtyUsers.clear(); 1667 } 1668 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1669 } break; 1670 case WRITE_PACKAGE_RESTRICTIONS: { 1671 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1672 synchronized (mPackages) { 1673 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1674 for (int userId : mDirtyUsers) { 1675 mSettings.writePackageRestrictionsLPr(userId); 1676 } 1677 mDirtyUsers.clear(); 1678 } 1679 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1680 } break; 1681 case WRITE_PACKAGE_LIST: { 1682 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1683 synchronized (mPackages) { 1684 removeMessages(WRITE_PACKAGE_LIST); 1685 mSettings.writePackageListLPr(msg.arg1); 1686 } 1687 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1688 } break; 1689 case CHECK_PENDING_VERIFICATION: { 1690 final int verificationId = msg.arg1; 1691 final PackageVerificationState state = mPendingVerification.get(verificationId); 1692 1693 if ((state != null) && !state.timeoutExtended()) { 1694 final InstallArgs args = state.getInstallArgs(); 1695 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1696 1697 Slog.i(TAG, "Verification timed out for " + originUri); 1698 mPendingVerification.remove(verificationId); 1699 1700 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1701 1702 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1703 Slog.i(TAG, "Continuing with installation of " + originUri); 1704 state.setVerifierResponse(Binder.getCallingUid(), 1705 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1706 broadcastPackageVerified(verificationId, originUri, 1707 PackageManager.VERIFICATION_ALLOW, 1708 state.getInstallArgs().getUser()); 1709 try { 1710 ret = args.copyApk(mContainerService, true); 1711 } catch (RemoteException e) { 1712 Slog.e(TAG, "Could not contact the ContainerService"); 1713 } 1714 } else { 1715 broadcastPackageVerified(verificationId, originUri, 1716 PackageManager.VERIFICATION_REJECT, 1717 state.getInstallArgs().getUser()); 1718 } 1719 1720 Trace.asyncTraceEnd( 1721 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1722 1723 processPendingInstall(args, ret); 1724 mHandler.sendEmptyMessage(MCS_UNBIND); 1725 } 1726 break; 1727 } 1728 case PACKAGE_VERIFIED: { 1729 final int verificationId = msg.arg1; 1730 1731 final PackageVerificationState state = mPendingVerification.get(verificationId); 1732 if (state == null) { 1733 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1734 break; 1735 } 1736 1737 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1738 1739 state.setVerifierResponse(response.callerUid, response.code); 1740 1741 if (state.isVerificationComplete()) { 1742 mPendingVerification.remove(verificationId); 1743 1744 final InstallArgs args = state.getInstallArgs(); 1745 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1746 1747 int ret; 1748 if (state.isInstallAllowed()) { 1749 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1750 broadcastPackageVerified(verificationId, originUri, 1751 response.code, state.getInstallArgs().getUser()); 1752 try { 1753 ret = args.copyApk(mContainerService, true); 1754 } catch (RemoteException e) { 1755 Slog.e(TAG, "Could not contact the ContainerService"); 1756 } 1757 } else { 1758 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1759 } 1760 1761 Trace.asyncTraceEnd( 1762 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1763 1764 processPendingInstall(args, ret); 1765 mHandler.sendEmptyMessage(MCS_UNBIND); 1766 } 1767 1768 break; 1769 } 1770 case START_INTENT_FILTER_VERIFICATIONS: { 1771 IFVerificationParams params = (IFVerificationParams) msg.obj; 1772 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1773 params.replacing, params.pkg); 1774 break; 1775 } 1776 case INTENT_FILTER_VERIFIED: { 1777 final int verificationId = msg.arg1; 1778 1779 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1780 verificationId); 1781 if (state == null) { 1782 Slog.w(TAG, "Invalid IntentFilter verification token " 1783 + verificationId + " received"); 1784 break; 1785 } 1786 1787 final int userId = state.getUserId(); 1788 1789 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1790 "Processing IntentFilter verification with token:" 1791 + verificationId + " and userId:" + userId); 1792 1793 final IntentFilterVerificationResponse response = 1794 (IntentFilterVerificationResponse) msg.obj; 1795 1796 state.setVerifierResponse(response.callerUid, response.code); 1797 1798 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1799 "IntentFilter verification with token:" + verificationId 1800 + " and userId:" + userId 1801 + " is settings verifier response with response code:" 1802 + response.code); 1803 1804 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1805 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1806 + response.getFailedDomainsString()); 1807 } 1808 1809 if (state.isVerificationComplete()) { 1810 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1811 } else { 1812 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1813 "IntentFilter verification with token:" + verificationId 1814 + " was not said to be complete"); 1815 } 1816 1817 break; 1818 } 1819 } 1820 } 1821 } 1822 1823 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1824 boolean killApp, String[] grantedPermissions, 1825 boolean launchedForRestore, String installerPackage, 1826 IPackageInstallObserver2 installObserver) { 1827 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1828 // Send the removed broadcasts 1829 if (res.removedInfo != null) { 1830 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1831 } 1832 1833 // Now that we successfully installed the package, grant runtime 1834 // permissions if requested before broadcasting the install. 1835 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1836 >= Build.VERSION_CODES.M) { 1837 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1838 } 1839 1840 final boolean update = res.removedInfo != null 1841 && res.removedInfo.removedPackage != null; 1842 1843 // If this is the first time we have child packages for a disabled privileged 1844 // app that had no children, we grant requested runtime permissions to the new 1845 // children if the parent on the system image had them already granted. 1846 if (res.pkg.parentPackage != null) { 1847 synchronized (mPackages) { 1848 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1849 } 1850 } 1851 1852 synchronized (mPackages) { 1853 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1854 } 1855 1856 final String packageName = res.pkg.applicationInfo.packageName; 1857 Bundle extras = new Bundle(1); 1858 extras.putInt(Intent.EXTRA_UID, res.uid); 1859 1860 // Determine the set of users who are adding this package for 1861 // the first time vs. those who are seeing an update. 1862 int[] firstUsers = EMPTY_INT_ARRAY; 1863 int[] updateUsers = EMPTY_INT_ARRAY; 1864 if (res.origUsers == null || res.origUsers.length == 0) { 1865 firstUsers = res.newUsers; 1866 } else { 1867 for (int newUser : res.newUsers) { 1868 boolean isNew = true; 1869 for (int origUser : res.origUsers) { 1870 if (origUser == newUser) { 1871 isNew = false; 1872 break; 1873 } 1874 } 1875 if (isNew) { 1876 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1877 } else { 1878 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1879 } 1880 } 1881 } 1882 1883 // Send installed broadcasts if the install/update is not ephemeral 1884 if (!isEphemeral(res.pkg)) { 1885 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1886 1887 // Send added for users that see the package for the first time 1888 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1889 extras, 0 /*flags*/, null /*targetPackage*/, 1890 null /*finishedReceiver*/, firstUsers); 1891 1892 // Send added for users that don't see the package for the first time 1893 if (update) { 1894 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1895 } 1896 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1897 extras, 0 /*flags*/, null /*targetPackage*/, 1898 null /*finishedReceiver*/, updateUsers); 1899 1900 // Send replaced for users that don't see the package for the first time 1901 if (update) { 1902 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1903 packageName, extras, 0 /*flags*/, 1904 null /*targetPackage*/, null /*finishedReceiver*/, 1905 updateUsers); 1906 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1907 null /*package*/, null /*extras*/, 0 /*flags*/, 1908 packageName /*targetPackage*/, 1909 null /*finishedReceiver*/, updateUsers); 1910 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1911 // First-install and we did a restore, so we're responsible for the 1912 // first-launch broadcast. 1913 if (DEBUG_BACKUP) { 1914 Slog.i(TAG, "Post-restore of " + packageName 1915 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1916 } 1917 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1918 } 1919 1920 // Send broadcast package appeared if forward locked/external for all users 1921 // treat asec-hosted packages like removable media on upgrade 1922 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1923 if (DEBUG_INSTALL) { 1924 Slog.i(TAG, "upgrading pkg " + res.pkg 1925 + " is ASEC-hosted -> AVAILABLE"); 1926 } 1927 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1928 ArrayList<String> pkgList = new ArrayList<>(1); 1929 pkgList.add(packageName); 1930 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1931 } 1932 } 1933 1934 // Work that needs to happen on first install within each user 1935 if (firstUsers != null && firstUsers.length > 0) { 1936 synchronized (mPackages) { 1937 for (int userId : firstUsers) { 1938 // If this app is a browser and it's newly-installed for some 1939 // users, clear any default-browser state in those users. The 1940 // app's nature doesn't depend on the user, so we can just check 1941 // its browser nature in any user and generalize. 1942 if (packageIsBrowser(packageName, userId)) { 1943 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1944 } 1945 1946 // We may also need to apply pending (restored) runtime 1947 // permission grants within these users. 1948 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1949 } 1950 } 1951 } 1952 1953 // Log current value of "unknown sources" setting 1954 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1955 getUnknownSourcesSettings()); 1956 1957 // Force a gc to clear up things 1958 Runtime.getRuntime().gc(); 1959 1960 // Remove the replaced package's older resources safely now 1961 // We delete after a gc for applications on sdcard. 1962 if (res.removedInfo != null && res.removedInfo.args != null) { 1963 synchronized (mInstallLock) { 1964 res.removedInfo.args.doPostDeleteLI(true); 1965 } 1966 } 1967 } 1968 1969 // If someone is watching installs - notify them 1970 if (installObserver != null) { 1971 try { 1972 Bundle extras = extrasForInstallResult(res); 1973 installObserver.onPackageInstalled(res.name, res.returnCode, 1974 res.returnMsg, extras); 1975 } catch (RemoteException e) { 1976 Slog.i(TAG, "Observer no longer exists."); 1977 } 1978 } 1979 } 1980 1981 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1982 PackageParser.Package pkg) { 1983 if (pkg.parentPackage == null) { 1984 return; 1985 } 1986 if (pkg.requestedPermissions == null) { 1987 return; 1988 } 1989 final PackageSetting disabledSysParentPs = mSettings 1990 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1991 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1992 || !disabledSysParentPs.isPrivileged() 1993 || (disabledSysParentPs.childPackageNames != null 1994 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1995 return; 1996 } 1997 final int[] allUserIds = sUserManager.getUserIds(); 1998 final int permCount = pkg.requestedPermissions.size(); 1999 for (int i = 0; i < permCount; i++) { 2000 String permission = pkg.requestedPermissions.get(i); 2001 BasePermission bp = mSettings.mPermissions.get(permission); 2002 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 2003 continue; 2004 } 2005 for (int userId : allUserIds) { 2006 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 2007 permission, userId)) { 2008 grantRuntimePermission(pkg.packageName, permission, userId); 2009 } 2010 } 2011 } 2012 } 2013 2014 private StorageEventListener mStorageListener = new StorageEventListener() { 2015 @Override 2016 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2017 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2018 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2019 final String volumeUuid = vol.getFsUuid(); 2020 2021 // Clean up any users or apps that were removed or recreated 2022 // while this volume was missing 2023 reconcileUsers(volumeUuid); 2024 reconcileApps(volumeUuid); 2025 2026 // Clean up any install sessions that expired or were 2027 // cancelled while this volume was missing 2028 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2029 2030 loadPrivatePackages(vol); 2031 2032 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2033 unloadPrivatePackages(vol); 2034 } 2035 } 2036 2037 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2038 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2039 updateExternalMediaStatus(true, false); 2040 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2041 updateExternalMediaStatus(false, false); 2042 } 2043 } 2044 } 2045 2046 @Override 2047 public void onVolumeForgotten(String fsUuid) { 2048 if (TextUtils.isEmpty(fsUuid)) { 2049 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2050 return; 2051 } 2052 2053 // Remove any apps installed on the forgotten volume 2054 synchronized (mPackages) { 2055 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2056 for (PackageSetting ps : packages) { 2057 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2058 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2059 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2060 } 2061 2062 mSettings.onVolumeForgotten(fsUuid); 2063 mSettings.writeLPr(); 2064 } 2065 } 2066 }; 2067 2068 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2069 String[] grantedPermissions) { 2070 for (int userId : userIds) { 2071 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2072 } 2073 2074 // We could have touched GID membership, so flush out packages.list 2075 synchronized (mPackages) { 2076 mSettings.writePackageListLPr(); 2077 } 2078 } 2079 2080 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2081 String[] grantedPermissions) { 2082 SettingBase sb = (SettingBase) pkg.mExtras; 2083 if (sb == null) { 2084 return; 2085 } 2086 2087 PermissionsState permissionsState = sb.getPermissionsState(); 2088 2089 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2090 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2091 2092 for (String permission : pkg.requestedPermissions) { 2093 final BasePermission bp; 2094 synchronized (mPackages) { 2095 bp = mSettings.mPermissions.get(permission); 2096 } 2097 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2098 && (grantedPermissions == null 2099 || ArrayUtils.contains(grantedPermissions, permission))) { 2100 final int flags = permissionsState.getPermissionFlags(permission, userId); 2101 // Installer cannot change immutable permissions. 2102 if ((flags & immutableFlags) == 0) { 2103 grantRuntimePermission(pkg.packageName, permission, userId); 2104 } 2105 } 2106 } 2107 } 2108 2109 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2110 Bundle extras = null; 2111 switch (res.returnCode) { 2112 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2113 extras = new Bundle(); 2114 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2115 res.origPermission); 2116 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2117 res.origPackage); 2118 break; 2119 } 2120 case PackageManager.INSTALL_SUCCEEDED: { 2121 extras = new Bundle(); 2122 extras.putBoolean(Intent.EXTRA_REPLACING, 2123 res.removedInfo != null && res.removedInfo.removedPackage != null); 2124 break; 2125 } 2126 } 2127 return extras; 2128 } 2129 2130 void scheduleWriteSettingsLocked() { 2131 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2132 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2133 } 2134 } 2135 2136 void scheduleWritePackageListLocked(int userId) { 2137 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2138 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2139 msg.arg1 = userId; 2140 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2141 } 2142 } 2143 2144 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2145 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2146 scheduleWritePackageRestrictionsLocked(userId); 2147 } 2148 2149 void scheduleWritePackageRestrictionsLocked(int userId) { 2150 final int[] userIds = (userId == UserHandle.USER_ALL) 2151 ? sUserManager.getUserIds() : new int[]{userId}; 2152 for (int nextUserId : userIds) { 2153 if (!sUserManager.exists(nextUserId)) return; 2154 mDirtyUsers.add(nextUserId); 2155 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2156 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2157 } 2158 } 2159 } 2160 2161 public static PackageManagerService main(Context context, Installer installer, 2162 boolean factoryTest, boolean onlyCore) { 2163 // Self-check for initial settings. 2164 PackageManagerServiceCompilerMapping.checkProperties(); 2165 2166 PackageManagerService m = new PackageManagerService(context, installer, 2167 factoryTest, onlyCore); 2168 m.enableSystemUserPackages(); 2169 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2170 // disabled after already being started. 2171 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2172 UserHandle.USER_SYSTEM); 2173 ServiceManager.addService("package", m); 2174 return m; 2175 } 2176 2177 private void enableSystemUserPackages() { 2178 if (!UserManager.isSplitSystemUser()) { 2179 return; 2180 } 2181 // For system user, enable apps based on the following conditions: 2182 // - app is whitelisted or belong to one of these groups: 2183 // -- system app which has no launcher icons 2184 // -- system app which has INTERACT_ACROSS_USERS permission 2185 // -- system IME app 2186 // - app is not in the blacklist 2187 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2188 Set<String> enableApps = new ArraySet<>(); 2189 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2190 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2191 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2192 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2193 enableApps.addAll(wlApps); 2194 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2195 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2196 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2197 enableApps.removeAll(blApps); 2198 Log.i(TAG, "Applications installed for system user: " + enableApps); 2199 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2200 UserHandle.SYSTEM); 2201 final int allAppsSize = allAps.size(); 2202 synchronized (mPackages) { 2203 for (int i = 0; i < allAppsSize; i++) { 2204 String pName = allAps.get(i); 2205 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2206 // Should not happen, but we shouldn't be failing if it does 2207 if (pkgSetting == null) { 2208 continue; 2209 } 2210 boolean install = enableApps.contains(pName); 2211 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2212 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2213 + " for system user"); 2214 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2215 } 2216 } 2217 } 2218 } 2219 2220 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2221 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2222 Context.DISPLAY_SERVICE); 2223 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2224 } 2225 2226 /** 2227 * Requests that files preopted on a secondary system partition be copied to the data partition 2228 * if possible. Note that the actual copying of the files is accomplished by init for security 2229 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2230 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2231 */ 2232 private static void requestCopyPreoptedFiles() { 2233 final int WAIT_TIME_MS = 100; 2234 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2235 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2236 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2237 // We will wait for up to 100 seconds. 2238 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2239 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2240 try { 2241 Thread.sleep(WAIT_TIME_MS); 2242 } catch (InterruptedException e) { 2243 // Do nothing 2244 } 2245 if (SystemClock.uptimeMillis() > timeEnd) { 2246 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2247 Slog.wtf(TAG, "cppreopt did not finish!"); 2248 break; 2249 } 2250 } 2251 } 2252 } 2253 2254 public PackageManagerService(Context context, Installer installer, 2255 boolean factoryTest, boolean onlyCore) { 2256 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2257 SystemClock.uptimeMillis()); 2258 2259 if (mSdkVersion <= 0) { 2260 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2261 } 2262 2263 mContext = context; 2264 mFactoryTest = factoryTest; 2265 mOnlyCore = onlyCore; 2266 mMetrics = new DisplayMetrics(); 2267 mSettings = new Settings(mPackages); 2268 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2269 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2270 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2271 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2272 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2273 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2274 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2275 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2276 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2277 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2278 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2279 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2280 2281 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2282 if (separateProcesses != null && separateProcesses.length() > 0) { 2283 if ("*".equals(separateProcesses)) { 2284 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2285 mSeparateProcesses = null; 2286 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2287 } else { 2288 mDefParseFlags = 0; 2289 mSeparateProcesses = separateProcesses.split(","); 2290 Slog.w(TAG, "Running with debug.separate_processes: " 2291 + separateProcesses); 2292 } 2293 } else { 2294 mDefParseFlags = 0; 2295 mSeparateProcesses = null; 2296 } 2297 2298 mInstaller = installer; 2299 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2300 "*dexopt*"); 2301 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2302 2303 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2304 FgThread.get().getLooper()); 2305 2306 getDefaultDisplayMetrics(context, mMetrics); 2307 2308 SystemConfig systemConfig = SystemConfig.getInstance(); 2309 mGlobalGids = systemConfig.getGlobalGids(); 2310 mSystemPermissions = systemConfig.getSystemPermissions(); 2311 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2312 2313 mProtectedPackages = new ProtectedPackages(mContext); 2314 2315 synchronized (mInstallLock) { 2316 // writer 2317 synchronized (mPackages) { 2318 mHandlerThread = new ServiceThread(TAG, 2319 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2320 mHandlerThread.start(); 2321 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2322 mProcessLoggingHandler = new ProcessLoggingHandler(); 2323 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2324 2325 File dataDir = Environment.getDataDirectory(); 2326 mAppInstallDir = new File(dataDir, "app"); 2327 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2328 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2329 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2330 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2331 2332 sUserManager = new UserManagerService(context, this, mPackages); 2333 2334 // Propagate permission configuration in to package manager. 2335 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2336 = systemConfig.getPermissions(); 2337 for (int i=0; i<permConfig.size(); i++) { 2338 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2339 BasePermission bp = mSettings.mPermissions.get(perm.name); 2340 if (bp == null) { 2341 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2342 mSettings.mPermissions.put(perm.name, bp); 2343 } 2344 if (perm.gids != null) { 2345 bp.setGids(perm.gids, perm.perUser); 2346 } 2347 } 2348 2349 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2350 for (int i=0; i<libConfig.size(); i++) { 2351 mSharedLibraries.put(libConfig.keyAt(i), 2352 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2353 } 2354 2355 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2356 2357 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2358 2359 if (mFirstBoot) { 2360 requestCopyPreoptedFiles(); 2361 } 2362 2363 String customResolverActivity = Resources.getSystem().getString( 2364 R.string.config_customResolverActivity); 2365 if (TextUtils.isEmpty(customResolverActivity)) { 2366 customResolverActivity = null; 2367 } else { 2368 mCustomResolverComponentName = ComponentName.unflattenFromString( 2369 customResolverActivity); 2370 } 2371 2372 long startTime = SystemClock.uptimeMillis(); 2373 2374 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2375 startTime); 2376 2377 // Set flag to monitor and not change apk file paths when 2378 // scanning install directories. 2379 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2380 2381 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2382 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2383 2384 if (bootClassPath == null) { 2385 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2386 } 2387 2388 if (systemServerClassPath == null) { 2389 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2390 } 2391 2392 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2393 final String[] dexCodeInstructionSets = 2394 getDexCodeInstructionSets( 2395 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2396 2397 /** 2398 * Ensure all external libraries have had dexopt run on them. 2399 */ 2400 if (mSharedLibraries.size() > 0) { 2401 // NOTE: For now, we're compiling these system "shared libraries" 2402 // (and framework jars) into all available architectures. It's possible 2403 // to compile them only when we come across an app that uses them (there's 2404 // already logic for that in scanPackageLI) but that adds some complexity. 2405 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2406 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2407 final String lib = libEntry.path; 2408 if (lib == null) { 2409 continue; 2410 } 2411 2412 try { 2413 // Shared libraries do not have profiles so we perform a full 2414 // AOT compilation (if needed). 2415 int dexoptNeeded = DexFile.getDexOptNeeded( 2416 lib, dexCodeInstructionSet, 2417 getCompilerFilterForReason(REASON_SHARED_APK), 2418 false /* newProfile */); 2419 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2420 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2421 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2422 getCompilerFilterForReason(REASON_SHARED_APK), 2423 StorageManager.UUID_PRIVATE_INTERNAL, 2424 SKIP_SHARED_LIBRARY_CHECK); 2425 } 2426 } catch (FileNotFoundException e) { 2427 Slog.w(TAG, "Library not found: " + lib); 2428 } catch (IOException | InstallerException e) { 2429 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2430 + e.getMessage()); 2431 } 2432 } 2433 } 2434 } 2435 2436 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2437 2438 final VersionInfo ver = mSettings.getInternalVersion(); 2439 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2440 2441 // when upgrading from pre-M, promote system app permissions from install to runtime 2442 mPromoteSystemApps = 2443 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2444 2445 // When upgrading from pre-N, we need to handle package extraction like first boot, 2446 // as there is no profiling data available. 2447 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2448 2449 // save off the names of pre-existing system packages prior to scanning; we don't 2450 // want to automatically grant runtime permissions for new system apps 2451 if (mPromoteSystemApps) { 2452 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2453 while (pkgSettingIter.hasNext()) { 2454 PackageSetting ps = pkgSettingIter.next(); 2455 if (isSystemApp(ps)) { 2456 mExistingSystemPackages.add(ps.name); 2457 } 2458 } 2459 } 2460 2461 // Collect vendor overlay packages. 2462 // (Do this before scanning any apps.) 2463 // For security and version matching reason, only consider 2464 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2465 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2466 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2467 | PackageParser.PARSE_IS_SYSTEM 2468 | PackageParser.PARSE_IS_SYSTEM_DIR 2469 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2470 2471 // Find base frameworks (resource packages without code). 2472 scanDirTracedLI(frameworkDir, mDefParseFlags 2473 | PackageParser.PARSE_IS_SYSTEM 2474 | PackageParser.PARSE_IS_SYSTEM_DIR 2475 | PackageParser.PARSE_IS_PRIVILEGED, 2476 scanFlags | SCAN_NO_DEX, 0); 2477 2478 // Collected privileged system packages. 2479 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2480 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2481 | PackageParser.PARSE_IS_SYSTEM 2482 | PackageParser.PARSE_IS_SYSTEM_DIR 2483 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2484 2485 // Collect ordinary system packages. 2486 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2487 scanDirTracedLI(systemAppDir, mDefParseFlags 2488 | PackageParser.PARSE_IS_SYSTEM 2489 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2490 2491 // Collect all vendor packages. 2492 File vendorAppDir = new File("/vendor/app"); 2493 try { 2494 vendorAppDir = vendorAppDir.getCanonicalFile(); 2495 } catch (IOException e) { 2496 // failed to look up canonical path, continue with original one 2497 } 2498 scanDirTracedLI(vendorAppDir, mDefParseFlags 2499 | PackageParser.PARSE_IS_SYSTEM 2500 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2501 2502 // Collect all OEM packages. 2503 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2504 scanDirTracedLI(oemAppDir, mDefParseFlags 2505 | PackageParser.PARSE_IS_SYSTEM 2506 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2507 2508 // Prune any system packages that no longer exist. 2509 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2510 if (!mOnlyCore) { 2511 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2512 while (psit.hasNext()) { 2513 PackageSetting ps = psit.next(); 2514 2515 /* 2516 * If this is not a system app, it can't be a 2517 * disable system app. 2518 */ 2519 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2520 continue; 2521 } 2522 2523 /* 2524 * If the package is scanned, it's not erased. 2525 */ 2526 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2527 if (scannedPkg != null) { 2528 /* 2529 * If the system app is both scanned and in the 2530 * disabled packages list, then it must have been 2531 * added via OTA. Remove it from the currently 2532 * scanned package so the previously user-installed 2533 * application can be scanned. 2534 */ 2535 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2536 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2537 + ps.name + "; removing system app. Last known codePath=" 2538 + ps.codePathString + ", installStatus=" + ps.installStatus 2539 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2540 + scannedPkg.mVersionCode); 2541 removePackageLI(scannedPkg, true); 2542 mExpectingBetter.put(ps.name, ps.codePath); 2543 } 2544 2545 continue; 2546 } 2547 2548 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2549 psit.remove(); 2550 logCriticalInfo(Log.WARN, "System package " + ps.name 2551 + " no longer exists; it's data will be wiped"); 2552 // Actual deletion of code and data will be handled by later 2553 // reconciliation step 2554 } else { 2555 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2556 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2557 possiblyDeletedUpdatedSystemApps.add(ps.name); 2558 } 2559 } 2560 } 2561 } 2562 2563 //look for any incomplete package installations 2564 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2565 for (int i = 0; i < deletePkgsList.size(); i++) { 2566 // Actual deletion of code and data will be handled by later 2567 // reconciliation step 2568 final String packageName = deletePkgsList.get(i).name; 2569 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2570 synchronized (mPackages) { 2571 mSettings.removePackageLPw(packageName); 2572 } 2573 } 2574 2575 //delete tmp files 2576 deleteTempPackageFiles(); 2577 2578 // Remove any shared userIDs that have no associated packages 2579 mSettings.pruneSharedUsersLPw(); 2580 2581 if (!mOnlyCore) { 2582 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2583 SystemClock.uptimeMillis()); 2584 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2585 2586 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2587 | PackageParser.PARSE_FORWARD_LOCK, 2588 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2589 2590 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2591 | PackageParser.PARSE_IS_EPHEMERAL, 2592 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2593 2594 /** 2595 * Remove disable package settings for any updated system 2596 * apps that were removed via an OTA. If they're not a 2597 * previously-updated app, remove them completely. 2598 * Otherwise, just revoke their system-level permissions. 2599 */ 2600 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2601 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2602 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2603 2604 String msg; 2605 if (deletedPkg == null) { 2606 msg = "Updated system package " + deletedAppName 2607 + " no longer exists; it's data will be wiped"; 2608 // Actual deletion of code and data will be handled by later 2609 // reconciliation step 2610 } else { 2611 msg = "Updated system app + " + deletedAppName 2612 + " no longer present; removing system privileges for " 2613 + deletedAppName; 2614 2615 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2616 2617 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2618 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2619 } 2620 logCriticalInfo(Log.WARN, msg); 2621 } 2622 2623 /** 2624 * Make sure all system apps that we expected to appear on 2625 * the userdata partition actually showed up. If they never 2626 * appeared, crawl back and revive the system version. 2627 */ 2628 for (int i = 0; i < mExpectingBetter.size(); i++) { 2629 final String packageName = mExpectingBetter.keyAt(i); 2630 if (!mPackages.containsKey(packageName)) { 2631 final File scanFile = mExpectingBetter.valueAt(i); 2632 2633 logCriticalInfo(Log.WARN, "Expected better " + packageName 2634 + " but never showed up; reverting to system"); 2635 2636 int reparseFlags = mDefParseFlags; 2637 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2638 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2639 | PackageParser.PARSE_IS_SYSTEM_DIR 2640 | PackageParser.PARSE_IS_PRIVILEGED; 2641 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2642 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2643 | PackageParser.PARSE_IS_SYSTEM_DIR; 2644 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2645 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2646 | PackageParser.PARSE_IS_SYSTEM_DIR; 2647 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2648 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2649 | PackageParser.PARSE_IS_SYSTEM_DIR; 2650 } else { 2651 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2652 continue; 2653 } 2654 2655 mSettings.enableSystemPackageLPw(packageName); 2656 2657 try { 2658 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2659 } catch (PackageManagerException e) { 2660 Slog.e(TAG, "Failed to parse original system package: " 2661 + e.getMessage()); 2662 } 2663 } 2664 } 2665 } 2666 mExpectingBetter.clear(); 2667 2668 // Resolve protected action filters. Only the setup wizard is allowed to 2669 // have a high priority filter for these actions. 2670 mSetupWizardPackage = getSetupWizardPackageName(); 2671 if (mProtectedFilters.size() > 0) { 2672 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2673 Slog.i(TAG, "No setup wizard;" 2674 + " All protected intents capped to priority 0"); 2675 } 2676 for (ActivityIntentInfo filter : mProtectedFilters) { 2677 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2678 if (DEBUG_FILTERS) { 2679 Slog.i(TAG, "Found setup wizard;" 2680 + " allow priority " + filter.getPriority() + ";" 2681 + " package: " + filter.activity.info.packageName 2682 + " activity: " + filter.activity.className 2683 + " priority: " + filter.getPriority()); 2684 } 2685 // skip setup wizard; allow it to keep the high priority filter 2686 continue; 2687 } 2688 Slog.w(TAG, "Protected action; cap priority to 0;" 2689 + " package: " + filter.activity.info.packageName 2690 + " activity: " + filter.activity.className 2691 + " origPrio: " + filter.getPriority()); 2692 filter.setPriority(0); 2693 } 2694 } 2695 mDeferProtectedFilters = false; 2696 mProtectedFilters.clear(); 2697 2698 // Now that we know all of the shared libraries, update all clients to have 2699 // the correct library paths. 2700 updateAllSharedLibrariesLPw(); 2701 2702 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2703 // NOTE: We ignore potential failures here during a system scan (like 2704 // the rest of the commands above) because there's precious little we 2705 // can do about it. A settings error is reported, though. 2706 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2707 false /* boot complete */); 2708 } 2709 2710 // Now that we know all the packages we are keeping, 2711 // read and update their last usage times. 2712 mPackageUsage.readLP(); 2713 2714 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2715 SystemClock.uptimeMillis()); 2716 Slog.i(TAG, "Time to scan packages: " 2717 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2718 + " seconds"); 2719 2720 // If the platform SDK has changed since the last time we booted, 2721 // we need to re-grant app permission to catch any new ones that 2722 // appear. This is really a hack, and means that apps can in some 2723 // cases get permissions that the user didn't initially explicitly 2724 // allow... it would be nice to have some better way to handle 2725 // this situation. 2726 int updateFlags = UPDATE_PERMISSIONS_ALL; 2727 if (ver.sdkVersion != mSdkVersion) { 2728 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2729 + mSdkVersion + "; regranting permissions for internal storage"); 2730 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2731 } 2732 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2733 ver.sdkVersion = mSdkVersion; 2734 2735 // If this is the first boot or an update from pre-M, and it is a normal 2736 // boot, then we need to initialize the default preferred apps across 2737 // all defined users. 2738 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2739 for (UserInfo user : sUserManager.getUsers(true)) { 2740 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2741 applyFactoryDefaultBrowserLPw(user.id); 2742 primeDomainVerificationsLPw(user.id); 2743 } 2744 } 2745 2746 // Prepare storage for system user really early during boot, 2747 // since core system apps like SettingsProvider and SystemUI 2748 // can't wait for user to start 2749 final int storageFlags; 2750 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2751 storageFlags = StorageManager.FLAG_STORAGE_DE; 2752 } else { 2753 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2754 } 2755 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2756 storageFlags); 2757 2758 // If this is first boot after an OTA, and a normal boot, then 2759 // we need to clear code cache directories. 2760 // Note that we do *not* clear the application profiles. These remain valid 2761 // across OTAs and are used to drive profile verification (post OTA) and 2762 // profile compilation (without waiting to collect a fresh set of profiles). 2763 if (mIsUpgrade && !onlyCore) { 2764 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2765 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2766 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2767 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2768 // No apps are running this early, so no need to freeze 2769 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2770 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2771 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2772 } 2773 } 2774 ver.fingerprint = Build.FINGERPRINT; 2775 } 2776 2777 checkDefaultBrowser(); 2778 2779 // clear only after permissions and other defaults have been updated 2780 mExistingSystemPackages.clear(); 2781 mPromoteSystemApps = false; 2782 2783 // All the changes are done during package scanning. 2784 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2785 2786 // can downgrade to reader 2787 mSettings.writeLPr(); 2788 2789 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2790 // early on (before the package manager declares itself as early) because other 2791 // components in the system server might ask for package contexts for these apps. 2792 // 2793 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2794 // (i.e, that the data partition is unavailable). 2795 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2796 long start = System.nanoTime(); 2797 List<PackageParser.Package> coreApps = new ArrayList<>(); 2798 for (PackageParser.Package pkg : mPackages.values()) { 2799 if (pkg.coreApp) { 2800 coreApps.add(pkg); 2801 } 2802 } 2803 2804 int[] stats = performDexOpt(coreApps, false, 2805 getCompilerFilterForReason(REASON_CORE_APP)); 2806 2807 final int elapsedTimeSeconds = 2808 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2809 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2810 2811 if (DEBUG_DEXOPT) { 2812 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2813 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2814 } 2815 2816 2817 // TODO: Should we log these stats to tron too ? 2818 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2819 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2820 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2821 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2822 } 2823 2824 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2825 SystemClock.uptimeMillis()); 2826 2827 if (!mOnlyCore) { 2828 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2829 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2830 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2831 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2832 mIntentFilterVerifierComponent); 2833 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2834 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2835 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2836 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2837 } else { 2838 mRequiredVerifierPackage = null; 2839 mRequiredInstallerPackage = null; 2840 mIntentFilterVerifierComponent = null; 2841 mIntentFilterVerifier = null; 2842 mServicesSystemSharedLibraryPackageName = null; 2843 mSharedSystemSharedLibraryPackageName = null; 2844 } 2845 2846 mInstallerService = new PackageInstallerService(context, this); 2847 2848 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2849 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2850 // both the installer and resolver must be present to enable ephemeral 2851 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2852 if (DEBUG_EPHEMERAL) { 2853 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2854 + " installer:" + ephemeralInstallerComponent); 2855 } 2856 mEphemeralResolverComponent = ephemeralResolverComponent; 2857 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2858 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2859 mEphemeralResolverConnection = 2860 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2861 } else { 2862 if (DEBUG_EPHEMERAL) { 2863 final String missingComponent = 2864 (ephemeralResolverComponent == null) 2865 ? (ephemeralInstallerComponent == null) 2866 ? "resolver and installer" 2867 : "resolver" 2868 : "installer"; 2869 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2870 } 2871 mEphemeralResolverComponent = null; 2872 mEphemeralInstallerComponent = null; 2873 mEphemeralResolverConnection = null; 2874 } 2875 2876 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2877 } // synchronized (mPackages) 2878 } // synchronized (mInstallLock) 2879 2880 // Now after opening every single application zip, make sure they 2881 // are all flushed. Not really needed, but keeps things nice and 2882 // tidy. 2883 Runtime.getRuntime().gc(); 2884 2885 // The initial scanning above does many calls into installd while 2886 // holding the mPackages lock, but we're mostly interested in yelling 2887 // once we have a booted system. 2888 mInstaller.setWarnIfHeld(mPackages); 2889 2890 // Expose private service for system components to use. 2891 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2892 } 2893 2894 @Override 2895 public boolean isFirstBoot() { 2896 return mFirstBoot; 2897 } 2898 2899 @Override 2900 public boolean isOnlyCoreApps() { 2901 return mOnlyCore; 2902 } 2903 2904 @Override 2905 public boolean isUpgrade() { 2906 return mIsUpgrade; 2907 } 2908 2909 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2910 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2911 2912 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2913 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2914 UserHandle.USER_SYSTEM); 2915 if (matches.size() == 1) { 2916 return matches.get(0).getComponentInfo().packageName; 2917 } else { 2918 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2919 return null; 2920 } 2921 } 2922 2923 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2924 synchronized (mPackages) { 2925 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2926 if (libraryEntry == null) { 2927 throw new IllegalStateException("Missing required shared library:" + libraryName); 2928 } 2929 return libraryEntry.apk; 2930 } 2931 } 2932 2933 private @NonNull String getRequiredInstallerLPr() { 2934 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2935 intent.addCategory(Intent.CATEGORY_DEFAULT); 2936 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2937 2938 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2939 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2940 UserHandle.USER_SYSTEM); 2941 if (matches.size() == 1) { 2942 ResolveInfo resolveInfo = matches.get(0); 2943 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2944 throw new RuntimeException("The installer must be a privileged app"); 2945 } 2946 return matches.get(0).getComponentInfo().packageName; 2947 } else { 2948 throw new RuntimeException("There must be exactly one installer; found " + matches); 2949 } 2950 } 2951 2952 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2953 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2954 2955 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2956 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2957 UserHandle.USER_SYSTEM); 2958 ResolveInfo best = null; 2959 final int N = matches.size(); 2960 for (int i = 0; i < N; i++) { 2961 final ResolveInfo cur = matches.get(i); 2962 final String packageName = cur.getComponentInfo().packageName; 2963 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2964 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2965 continue; 2966 } 2967 2968 if (best == null || cur.priority > best.priority) { 2969 best = cur; 2970 } 2971 } 2972 2973 if (best != null) { 2974 return best.getComponentInfo().getComponentName(); 2975 } else { 2976 throw new RuntimeException("There must be at least one intent filter verifier"); 2977 } 2978 } 2979 2980 private @Nullable ComponentName getEphemeralResolverLPr() { 2981 final String[] packageArray = 2982 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2983 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2984 if (DEBUG_EPHEMERAL) { 2985 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2986 } 2987 return null; 2988 } 2989 2990 final int resolveFlags = 2991 MATCH_DIRECT_BOOT_AWARE 2992 | MATCH_DIRECT_BOOT_UNAWARE 2993 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2994 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2995 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2996 resolveFlags, UserHandle.USER_SYSTEM); 2997 2998 final int N = resolvers.size(); 2999 if (N == 0) { 3000 if (DEBUG_EPHEMERAL) { 3001 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3002 } 3003 return null; 3004 } 3005 3006 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3007 for (int i = 0; i < N; i++) { 3008 final ResolveInfo info = resolvers.get(i); 3009 3010 if (info.serviceInfo == null) { 3011 continue; 3012 } 3013 3014 final String packageName = info.serviceInfo.packageName; 3015 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3016 if (DEBUG_EPHEMERAL) { 3017 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3018 + " pkg: " + packageName + ", info:" + info); 3019 } 3020 continue; 3021 } 3022 3023 if (DEBUG_EPHEMERAL) { 3024 Slog.v(TAG, "Ephemeral resolver found;" 3025 + " pkg: " + packageName + ", info:" + info); 3026 } 3027 return new ComponentName(packageName, info.serviceInfo.name); 3028 } 3029 if (DEBUG_EPHEMERAL) { 3030 Slog.v(TAG, "Ephemeral resolver NOT found"); 3031 } 3032 return null; 3033 } 3034 3035 private @Nullable ComponentName getEphemeralInstallerLPr() { 3036 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3037 intent.addCategory(Intent.CATEGORY_DEFAULT); 3038 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3039 3040 final int resolveFlags = 3041 MATCH_DIRECT_BOOT_AWARE 3042 | MATCH_DIRECT_BOOT_UNAWARE 3043 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3044 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3045 resolveFlags, UserHandle.USER_SYSTEM); 3046 if (matches.size() == 0) { 3047 return null; 3048 } else if (matches.size() == 1) { 3049 return matches.get(0).getComponentInfo().getComponentName(); 3050 } else { 3051 throw new RuntimeException( 3052 "There must be at most one ephemeral installer; found " + matches); 3053 } 3054 } 3055 3056 private void primeDomainVerificationsLPw(int userId) { 3057 if (DEBUG_DOMAIN_VERIFICATION) { 3058 Slog.d(TAG, "Priming domain verifications in user " + userId); 3059 } 3060 3061 SystemConfig systemConfig = SystemConfig.getInstance(); 3062 ArraySet<String> packages = systemConfig.getLinkedApps(); 3063 ArraySet<String> domains = new ArraySet<String>(); 3064 3065 for (String packageName : packages) { 3066 PackageParser.Package pkg = mPackages.get(packageName); 3067 if (pkg != null) { 3068 if (!pkg.isSystemApp()) { 3069 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3070 continue; 3071 } 3072 3073 domains.clear(); 3074 for (PackageParser.Activity a : pkg.activities) { 3075 for (ActivityIntentInfo filter : a.intents) { 3076 if (hasValidDomains(filter)) { 3077 domains.addAll(filter.getHostsList()); 3078 } 3079 } 3080 } 3081 3082 if (domains.size() > 0) { 3083 if (DEBUG_DOMAIN_VERIFICATION) { 3084 Slog.v(TAG, " + " + packageName); 3085 } 3086 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3087 // state w.r.t. the formal app-linkage "no verification attempted" state; 3088 // and then 'always' in the per-user state actually used for intent resolution. 3089 final IntentFilterVerificationInfo ivi; 3090 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 3091 new ArrayList<String>(domains)); 3092 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3093 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3094 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3095 } else { 3096 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3097 + "' does not handle web links"); 3098 } 3099 } else { 3100 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3101 } 3102 } 3103 3104 scheduleWritePackageRestrictionsLocked(userId); 3105 scheduleWriteSettingsLocked(); 3106 } 3107 3108 private void applyFactoryDefaultBrowserLPw(int userId) { 3109 // The default browser app's package name is stored in a string resource, 3110 // with a product-specific overlay used for vendor customization. 3111 String browserPkg = mContext.getResources().getString( 3112 com.android.internal.R.string.default_browser); 3113 if (!TextUtils.isEmpty(browserPkg)) { 3114 // non-empty string => required to be a known package 3115 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3116 if (ps == null) { 3117 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3118 browserPkg = null; 3119 } else { 3120 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3121 } 3122 } 3123 3124 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3125 // default. If there's more than one, just leave everything alone. 3126 if (browserPkg == null) { 3127 calculateDefaultBrowserLPw(userId); 3128 } 3129 } 3130 3131 private void calculateDefaultBrowserLPw(int userId) { 3132 List<String> allBrowsers = resolveAllBrowserApps(userId); 3133 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3134 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3135 } 3136 3137 private List<String> resolveAllBrowserApps(int userId) { 3138 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3139 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3140 PackageManager.MATCH_ALL, userId); 3141 3142 final int count = list.size(); 3143 List<String> result = new ArrayList<String>(count); 3144 for (int i=0; i<count; i++) { 3145 ResolveInfo info = list.get(i); 3146 if (info.activityInfo == null 3147 || !info.handleAllWebDataURI 3148 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3149 || result.contains(info.activityInfo.packageName)) { 3150 continue; 3151 } 3152 result.add(info.activityInfo.packageName); 3153 } 3154 3155 return result; 3156 } 3157 3158 private boolean packageIsBrowser(String packageName, int userId) { 3159 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3160 PackageManager.MATCH_ALL, userId); 3161 final int N = list.size(); 3162 for (int i = 0; i < N; i++) { 3163 ResolveInfo info = list.get(i); 3164 if (packageName.equals(info.activityInfo.packageName)) { 3165 return true; 3166 } 3167 } 3168 return false; 3169 } 3170 3171 private void checkDefaultBrowser() { 3172 final int myUserId = UserHandle.myUserId(); 3173 final String packageName = getDefaultBrowserPackageName(myUserId); 3174 if (packageName != null) { 3175 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3176 if (info == null) { 3177 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3178 synchronized (mPackages) { 3179 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3180 } 3181 } 3182 } 3183 } 3184 3185 @Override 3186 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3187 throws RemoteException { 3188 try { 3189 return super.onTransact(code, data, reply, flags); 3190 } catch (RuntimeException e) { 3191 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3192 Slog.wtf(TAG, "Package Manager Crash", e); 3193 } 3194 throw e; 3195 } 3196 } 3197 3198 static int[] appendInts(int[] cur, int[] add) { 3199 if (add == null) return cur; 3200 if (cur == null) return add; 3201 final int N = add.length; 3202 for (int i=0; i<N; i++) { 3203 cur = appendInt(cur, add[i]); 3204 } 3205 return cur; 3206 } 3207 3208 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3209 if (!sUserManager.exists(userId)) return null; 3210 if (ps == null) { 3211 return null; 3212 } 3213 final PackageParser.Package p = ps.pkg; 3214 if (p == null) { 3215 return null; 3216 } 3217 3218 final PermissionsState permissionsState = ps.getPermissionsState(); 3219 3220 // Compute GIDs only if requested 3221 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3222 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3223 // Compute granted permissions only if package has requested permissions 3224 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3225 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3226 final PackageUserState state = ps.readUserState(userId); 3227 3228 return PackageParser.generatePackageInfo(p, gids, flags, 3229 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3230 } 3231 3232 @Override 3233 public void checkPackageStartable(String packageName, int userId) { 3234 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3235 3236 synchronized (mPackages) { 3237 final PackageSetting ps = mSettings.mPackages.get(packageName); 3238 if (ps == null) { 3239 throw new SecurityException("Package " + packageName + " was not found!"); 3240 } 3241 3242 if (!ps.getInstalled(userId)) { 3243 throw new SecurityException( 3244 "Package " + packageName + " was not installed for user " + userId + "!"); 3245 } 3246 3247 if (mSafeMode && !ps.isSystem()) { 3248 throw new SecurityException("Package " + packageName + " not a system app!"); 3249 } 3250 3251 if (mFrozenPackages.contains(packageName)) { 3252 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3253 } 3254 3255 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3256 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3257 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3258 } 3259 } 3260 } 3261 3262 @Override 3263 public boolean isPackageAvailable(String packageName, int userId) { 3264 if (!sUserManager.exists(userId)) return false; 3265 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3266 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3267 synchronized (mPackages) { 3268 PackageParser.Package p = mPackages.get(packageName); 3269 if (p != null) { 3270 final PackageSetting ps = (PackageSetting) p.mExtras; 3271 if (ps != null) { 3272 final PackageUserState state = ps.readUserState(userId); 3273 if (state != null) { 3274 return PackageParser.isAvailable(state); 3275 } 3276 } 3277 } 3278 } 3279 return false; 3280 } 3281 3282 @Override 3283 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3284 if (!sUserManager.exists(userId)) return null; 3285 flags = updateFlagsForPackage(flags, userId, packageName); 3286 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3287 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3288 // reader 3289 synchronized (mPackages) { 3290 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3291 PackageParser.Package p = null; 3292 if (matchFactoryOnly) { 3293 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3294 if (ps != null) { 3295 return generatePackageInfo(ps, flags, userId); 3296 } 3297 } 3298 if (p == null) { 3299 p = mPackages.get(packageName); 3300 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3301 return null; 3302 } 3303 } 3304 if (DEBUG_PACKAGE_INFO) 3305 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3306 if (p != null) { 3307 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3308 } 3309 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3310 final PackageSetting ps = mSettings.mPackages.get(packageName); 3311 return generatePackageInfo(ps, flags, userId); 3312 } 3313 } 3314 return null; 3315 } 3316 3317 @Override 3318 public String[] currentToCanonicalPackageNames(String[] names) { 3319 String[] out = new String[names.length]; 3320 // reader 3321 synchronized (mPackages) { 3322 for (int i=names.length-1; i>=0; i--) { 3323 PackageSetting ps = mSettings.mPackages.get(names[i]); 3324 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3325 } 3326 } 3327 return out; 3328 } 3329 3330 @Override 3331 public String[] canonicalToCurrentPackageNames(String[] names) { 3332 String[] out = new String[names.length]; 3333 // reader 3334 synchronized (mPackages) { 3335 for (int i=names.length-1; i>=0; i--) { 3336 String cur = mSettings.mRenamedPackages.get(names[i]); 3337 out[i] = cur != null ? cur : names[i]; 3338 } 3339 } 3340 return out; 3341 } 3342 3343 @Override 3344 public int getPackageUid(String packageName, int flags, int userId) { 3345 if (!sUserManager.exists(userId)) return -1; 3346 flags = updateFlagsForPackage(flags, userId, packageName); 3347 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3348 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3349 3350 // reader 3351 synchronized (mPackages) { 3352 final PackageParser.Package p = mPackages.get(packageName); 3353 if (p != null && p.isMatch(flags)) { 3354 return UserHandle.getUid(userId, p.applicationInfo.uid); 3355 } 3356 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3357 final PackageSetting ps = mSettings.mPackages.get(packageName); 3358 if (ps != null && ps.isMatch(flags)) { 3359 return UserHandle.getUid(userId, ps.appId); 3360 } 3361 } 3362 } 3363 3364 return -1; 3365 } 3366 3367 @Override 3368 public int[] getPackageGids(String packageName, int flags, int userId) { 3369 if (!sUserManager.exists(userId)) return null; 3370 flags = updateFlagsForPackage(flags, userId, packageName); 3371 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3372 false /* requireFullPermission */, false /* checkShell */, 3373 "getPackageGids"); 3374 3375 // reader 3376 synchronized (mPackages) { 3377 final PackageParser.Package p = mPackages.get(packageName); 3378 if (p != null && p.isMatch(flags)) { 3379 PackageSetting ps = (PackageSetting) p.mExtras; 3380 return ps.getPermissionsState().computeGids(userId); 3381 } 3382 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3383 final PackageSetting ps = mSettings.mPackages.get(packageName); 3384 if (ps != null && ps.isMatch(flags)) { 3385 return ps.getPermissionsState().computeGids(userId); 3386 } 3387 } 3388 } 3389 3390 return null; 3391 } 3392 3393 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3394 if (bp.perm != null) { 3395 return PackageParser.generatePermissionInfo(bp.perm, flags); 3396 } 3397 PermissionInfo pi = new PermissionInfo(); 3398 pi.name = bp.name; 3399 pi.packageName = bp.sourcePackage; 3400 pi.nonLocalizedLabel = bp.name; 3401 pi.protectionLevel = bp.protectionLevel; 3402 return pi; 3403 } 3404 3405 @Override 3406 public PermissionInfo getPermissionInfo(String name, int flags) { 3407 // reader 3408 synchronized (mPackages) { 3409 final BasePermission p = mSettings.mPermissions.get(name); 3410 if (p != null) { 3411 return generatePermissionInfo(p, flags); 3412 } 3413 return null; 3414 } 3415 } 3416 3417 @Override 3418 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3419 int flags) { 3420 // reader 3421 synchronized (mPackages) { 3422 if (group != null && !mPermissionGroups.containsKey(group)) { 3423 // This is thrown as NameNotFoundException 3424 return null; 3425 } 3426 3427 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3428 for (BasePermission p : mSettings.mPermissions.values()) { 3429 if (group == null) { 3430 if (p.perm == null || p.perm.info.group == null) { 3431 out.add(generatePermissionInfo(p, flags)); 3432 } 3433 } else { 3434 if (p.perm != null && group.equals(p.perm.info.group)) { 3435 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3436 } 3437 } 3438 } 3439 return new ParceledListSlice<>(out); 3440 } 3441 } 3442 3443 @Override 3444 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3445 // reader 3446 synchronized (mPackages) { 3447 return PackageParser.generatePermissionGroupInfo( 3448 mPermissionGroups.get(name), flags); 3449 } 3450 } 3451 3452 @Override 3453 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3454 // reader 3455 synchronized (mPackages) { 3456 final int N = mPermissionGroups.size(); 3457 ArrayList<PermissionGroupInfo> out 3458 = new ArrayList<PermissionGroupInfo>(N); 3459 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3460 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3461 } 3462 return new ParceledListSlice<>(out); 3463 } 3464 } 3465 3466 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3467 int userId) { 3468 if (!sUserManager.exists(userId)) return null; 3469 PackageSetting ps = mSettings.mPackages.get(packageName); 3470 if (ps != null) { 3471 if (ps.pkg == null) { 3472 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3473 if (pInfo != null) { 3474 return pInfo.applicationInfo; 3475 } 3476 return null; 3477 } 3478 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3479 ps.readUserState(userId), userId); 3480 } 3481 return null; 3482 } 3483 3484 @Override 3485 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3486 if (!sUserManager.exists(userId)) return null; 3487 flags = updateFlagsForApplication(flags, userId, packageName); 3488 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3489 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3490 // writer 3491 synchronized (mPackages) { 3492 PackageParser.Package p = mPackages.get(packageName); 3493 if (DEBUG_PACKAGE_INFO) Log.v( 3494 TAG, "getApplicationInfo " + packageName 3495 + ": " + p); 3496 if (p != null) { 3497 PackageSetting ps = mSettings.mPackages.get(packageName); 3498 if (ps == null) return null; 3499 // Note: isEnabledLP() does not apply here - always return info 3500 return PackageParser.generateApplicationInfo( 3501 p, flags, ps.readUserState(userId), userId); 3502 } 3503 if ("android".equals(packageName)||"system".equals(packageName)) { 3504 return mAndroidApplication; 3505 } 3506 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3507 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3508 } 3509 } 3510 return null; 3511 } 3512 3513 @Override 3514 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3515 final IPackageDataObserver observer) { 3516 mContext.enforceCallingOrSelfPermission( 3517 android.Manifest.permission.CLEAR_APP_CACHE, null); 3518 // Queue up an async operation since clearing cache may take a little while. 3519 mHandler.post(new Runnable() { 3520 public void run() { 3521 mHandler.removeCallbacks(this); 3522 boolean success = true; 3523 synchronized (mInstallLock) { 3524 try { 3525 mInstaller.freeCache(volumeUuid, freeStorageSize); 3526 } catch (InstallerException e) { 3527 Slog.w(TAG, "Couldn't clear application caches: " + e); 3528 success = false; 3529 } 3530 } 3531 if (observer != null) { 3532 try { 3533 observer.onRemoveCompleted(null, success); 3534 } catch (RemoteException e) { 3535 Slog.w(TAG, "RemoveException when invoking call back"); 3536 } 3537 } 3538 } 3539 }); 3540 } 3541 3542 @Override 3543 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3544 final IntentSender pi) { 3545 mContext.enforceCallingOrSelfPermission( 3546 android.Manifest.permission.CLEAR_APP_CACHE, null); 3547 // Queue up an async operation since clearing cache may take a little while. 3548 mHandler.post(new Runnable() { 3549 public void run() { 3550 mHandler.removeCallbacks(this); 3551 boolean success = true; 3552 synchronized (mInstallLock) { 3553 try { 3554 mInstaller.freeCache(volumeUuid, freeStorageSize); 3555 } catch (InstallerException e) { 3556 Slog.w(TAG, "Couldn't clear application caches: " + e); 3557 success = false; 3558 } 3559 } 3560 if(pi != null) { 3561 try { 3562 // Callback via pending intent 3563 int code = success ? 1 : 0; 3564 pi.sendIntent(null, code, null, 3565 null, null); 3566 } catch (SendIntentException e1) { 3567 Slog.i(TAG, "Failed to send pending intent"); 3568 } 3569 } 3570 } 3571 }); 3572 } 3573 3574 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3575 synchronized (mInstallLock) { 3576 try { 3577 mInstaller.freeCache(volumeUuid, freeStorageSize); 3578 } catch (InstallerException e) { 3579 throw new IOException("Failed to free enough space", e); 3580 } 3581 } 3582 } 3583 3584 /** 3585 * Update given flags based on encryption status of current user. 3586 */ 3587 private int updateFlags(int flags, int userId) { 3588 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3589 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3590 // Caller expressed an explicit opinion about what encryption 3591 // aware/unaware components they want to see, so fall through and 3592 // give them what they want 3593 } else { 3594 // Caller expressed no opinion, so match based on user state 3595 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3596 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3597 } else { 3598 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3599 } 3600 } 3601 return flags; 3602 } 3603 3604 private UserManagerInternal getUserManagerInternal() { 3605 if (mUserManagerInternal == null) { 3606 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3607 } 3608 return mUserManagerInternal; 3609 } 3610 3611 /** 3612 * Update given flags when being used to request {@link PackageInfo}. 3613 */ 3614 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3615 boolean triaged = true; 3616 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3617 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3618 // Caller is asking for component details, so they'd better be 3619 // asking for specific encryption matching behavior, or be triaged 3620 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3621 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3622 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3623 triaged = false; 3624 } 3625 } 3626 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3627 | PackageManager.MATCH_SYSTEM_ONLY 3628 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3629 triaged = false; 3630 } 3631 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3632 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3633 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3634 } 3635 return updateFlags(flags, userId); 3636 } 3637 3638 /** 3639 * Update given flags when being used to request {@link ApplicationInfo}. 3640 */ 3641 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3642 return updateFlagsForPackage(flags, userId, cookie); 3643 } 3644 3645 /** 3646 * Update given flags when being used to request {@link ComponentInfo}. 3647 */ 3648 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3649 if (cookie instanceof Intent) { 3650 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3651 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3652 } 3653 } 3654 3655 boolean triaged = true; 3656 // Caller is asking for component details, so they'd better be 3657 // asking for specific encryption matching behavior, or be triaged 3658 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3659 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3660 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3661 triaged = false; 3662 } 3663 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3664 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3665 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3666 } 3667 3668 return updateFlags(flags, userId); 3669 } 3670 3671 /** 3672 * Update given flags when being used to request {@link ResolveInfo}. 3673 */ 3674 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3675 // Safe mode means we shouldn't match any third-party components 3676 if (mSafeMode) { 3677 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3678 } 3679 3680 return updateFlagsForComponent(flags, userId, cookie); 3681 } 3682 3683 @Override 3684 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3685 if (!sUserManager.exists(userId)) return null; 3686 flags = updateFlagsForComponent(flags, userId, component); 3687 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3688 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3689 synchronized (mPackages) { 3690 PackageParser.Activity a = mActivities.mActivities.get(component); 3691 3692 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3693 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3694 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3695 if (ps == null) return null; 3696 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3697 userId); 3698 } 3699 if (mResolveComponentName.equals(component)) { 3700 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3701 new PackageUserState(), userId); 3702 } 3703 } 3704 return null; 3705 } 3706 3707 @Override 3708 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3709 String resolvedType) { 3710 synchronized (mPackages) { 3711 if (component.equals(mResolveComponentName)) { 3712 // The resolver supports EVERYTHING! 3713 return true; 3714 } 3715 PackageParser.Activity a = mActivities.mActivities.get(component); 3716 if (a == null) { 3717 return false; 3718 } 3719 for (int i=0; i<a.intents.size(); i++) { 3720 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3721 intent.getData(), intent.getCategories(), TAG) >= 0) { 3722 return true; 3723 } 3724 } 3725 return false; 3726 } 3727 } 3728 3729 @Override 3730 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3731 if (!sUserManager.exists(userId)) return null; 3732 flags = updateFlagsForComponent(flags, userId, component); 3733 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3734 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3735 synchronized (mPackages) { 3736 PackageParser.Activity a = mReceivers.mActivities.get(component); 3737 if (DEBUG_PACKAGE_INFO) Log.v( 3738 TAG, "getReceiverInfo " + component + ": " + a); 3739 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3740 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3741 if (ps == null) return null; 3742 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3743 userId); 3744 } 3745 } 3746 return null; 3747 } 3748 3749 @Override 3750 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3751 if (!sUserManager.exists(userId)) return null; 3752 flags = updateFlagsForComponent(flags, userId, component); 3753 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3754 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3755 synchronized (mPackages) { 3756 PackageParser.Service s = mServices.mServices.get(component); 3757 if (DEBUG_PACKAGE_INFO) Log.v( 3758 TAG, "getServiceInfo " + component + ": " + s); 3759 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3760 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3761 if (ps == null) return null; 3762 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3763 userId); 3764 } 3765 } 3766 return null; 3767 } 3768 3769 @Override 3770 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3771 if (!sUserManager.exists(userId)) return null; 3772 flags = updateFlagsForComponent(flags, userId, component); 3773 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3774 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3775 synchronized (mPackages) { 3776 PackageParser.Provider p = mProviders.mProviders.get(component); 3777 if (DEBUG_PACKAGE_INFO) Log.v( 3778 TAG, "getProviderInfo " + component + ": " + p); 3779 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3780 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3781 if (ps == null) return null; 3782 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3783 userId); 3784 } 3785 } 3786 return null; 3787 } 3788 3789 @Override 3790 public String[] getSystemSharedLibraryNames() { 3791 Set<String> libSet; 3792 synchronized (mPackages) { 3793 libSet = mSharedLibraries.keySet(); 3794 int size = libSet.size(); 3795 if (size > 0) { 3796 String[] libs = new String[size]; 3797 libSet.toArray(libs); 3798 return libs; 3799 } 3800 } 3801 return null; 3802 } 3803 3804 @Override 3805 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3806 synchronized (mPackages) { 3807 return mServicesSystemSharedLibraryPackageName; 3808 } 3809 } 3810 3811 @Override 3812 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3813 synchronized (mPackages) { 3814 return mSharedSystemSharedLibraryPackageName; 3815 } 3816 } 3817 3818 @Override 3819 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3820 synchronized (mPackages) { 3821 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3822 3823 final FeatureInfo fi = new FeatureInfo(); 3824 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3825 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3826 res.add(fi); 3827 3828 return new ParceledListSlice<>(res); 3829 } 3830 } 3831 3832 @Override 3833 public boolean hasSystemFeature(String name, int version) { 3834 synchronized (mPackages) { 3835 final FeatureInfo feat = mAvailableFeatures.get(name); 3836 if (feat == null) { 3837 return false; 3838 } else { 3839 return feat.version >= version; 3840 } 3841 } 3842 } 3843 3844 @Override 3845 public int checkPermission(String permName, String pkgName, int userId) { 3846 if (!sUserManager.exists(userId)) { 3847 return PackageManager.PERMISSION_DENIED; 3848 } 3849 3850 synchronized (mPackages) { 3851 final PackageParser.Package p = mPackages.get(pkgName); 3852 if (p != null && p.mExtras != null) { 3853 final PackageSetting ps = (PackageSetting) p.mExtras; 3854 final PermissionsState permissionsState = ps.getPermissionsState(); 3855 if (permissionsState.hasPermission(permName, userId)) { 3856 return PackageManager.PERMISSION_GRANTED; 3857 } 3858 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3859 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3860 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3861 return PackageManager.PERMISSION_GRANTED; 3862 } 3863 } 3864 } 3865 3866 return PackageManager.PERMISSION_DENIED; 3867 } 3868 3869 @Override 3870 public int checkUidPermission(String permName, int uid) { 3871 final int userId = UserHandle.getUserId(uid); 3872 3873 if (!sUserManager.exists(userId)) { 3874 return PackageManager.PERMISSION_DENIED; 3875 } 3876 3877 synchronized (mPackages) { 3878 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3879 if (obj != null) { 3880 final SettingBase ps = (SettingBase) obj; 3881 final PermissionsState permissionsState = ps.getPermissionsState(); 3882 if (permissionsState.hasPermission(permName, userId)) { 3883 return PackageManager.PERMISSION_GRANTED; 3884 } 3885 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3886 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3887 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3888 return PackageManager.PERMISSION_GRANTED; 3889 } 3890 } else { 3891 ArraySet<String> perms = mSystemPermissions.get(uid); 3892 if (perms != null) { 3893 if (perms.contains(permName)) { 3894 return PackageManager.PERMISSION_GRANTED; 3895 } 3896 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3897 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3898 return PackageManager.PERMISSION_GRANTED; 3899 } 3900 } 3901 } 3902 } 3903 3904 return PackageManager.PERMISSION_DENIED; 3905 } 3906 3907 @Override 3908 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3909 if (UserHandle.getCallingUserId() != userId) { 3910 mContext.enforceCallingPermission( 3911 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3912 "isPermissionRevokedByPolicy for user " + userId); 3913 } 3914 3915 if (checkPermission(permission, packageName, userId) 3916 == PackageManager.PERMISSION_GRANTED) { 3917 return false; 3918 } 3919 3920 final long identity = Binder.clearCallingIdentity(); 3921 try { 3922 final int flags = getPermissionFlags(permission, packageName, userId); 3923 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3924 } finally { 3925 Binder.restoreCallingIdentity(identity); 3926 } 3927 } 3928 3929 @Override 3930 public String getPermissionControllerPackageName() { 3931 synchronized (mPackages) { 3932 return mRequiredInstallerPackage; 3933 } 3934 } 3935 3936 /** 3937 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3938 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3939 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3940 * @param message the message to log on security exception 3941 */ 3942 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3943 boolean checkShell, String message) { 3944 if (userId < 0) { 3945 throw new IllegalArgumentException("Invalid userId " + userId); 3946 } 3947 if (checkShell) { 3948 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3949 } 3950 if (userId == UserHandle.getUserId(callingUid)) return; 3951 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3952 if (requireFullPermission) { 3953 mContext.enforceCallingOrSelfPermission( 3954 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3955 } else { 3956 try { 3957 mContext.enforceCallingOrSelfPermission( 3958 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3959 } catch (SecurityException se) { 3960 mContext.enforceCallingOrSelfPermission( 3961 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3962 } 3963 } 3964 } 3965 } 3966 3967 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3968 if (callingUid == Process.SHELL_UID) { 3969 if (userHandle >= 0 3970 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3971 throw new SecurityException("Shell does not have permission to access user " 3972 + userHandle); 3973 } else if (userHandle < 0) { 3974 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3975 + Debug.getCallers(3)); 3976 } 3977 } 3978 } 3979 3980 private BasePermission findPermissionTreeLP(String permName) { 3981 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3982 if (permName.startsWith(bp.name) && 3983 permName.length() > bp.name.length() && 3984 permName.charAt(bp.name.length()) == '.') { 3985 return bp; 3986 } 3987 } 3988 return null; 3989 } 3990 3991 private BasePermission checkPermissionTreeLP(String permName) { 3992 if (permName != null) { 3993 BasePermission bp = findPermissionTreeLP(permName); 3994 if (bp != null) { 3995 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3996 return bp; 3997 } 3998 throw new SecurityException("Calling uid " 3999 + Binder.getCallingUid() 4000 + " is not allowed to add to permission tree " 4001 + bp.name + " owned by uid " + bp.uid); 4002 } 4003 } 4004 throw new SecurityException("No permission tree found for " + permName); 4005 } 4006 4007 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4008 if (s1 == null) { 4009 return s2 == null; 4010 } 4011 if (s2 == null) { 4012 return false; 4013 } 4014 if (s1.getClass() != s2.getClass()) { 4015 return false; 4016 } 4017 return s1.equals(s2); 4018 } 4019 4020 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4021 if (pi1.icon != pi2.icon) return false; 4022 if (pi1.logo != pi2.logo) return false; 4023 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4024 if (!compareStrings(pi1.name, pi2.name)) return false; 4025 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4026 // We'll take care of setting this one. 4027 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4028 // These are not currently stored in settings. 4029 //if (!compareStrings(pi1.group, pi2.group)) return false; 4030 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4031 //if (pi1.labelRes != pi2.labelRes) return false; 4032 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4033 return true; 4034 } 4035 4036 int permissionInfoFootprint(PermissionInfo info) { 4037 int size = info.name.length(); 4038 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4039 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4040 return size; 4041 } 4042 4043 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4044 int size = 0; 4045 for (BasePermission perm : mSettings.mPermissions.values()) { 4046 if (perm.uid == tree.uid) { 4047 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4048 } 4049 } 4050 return size; 4051 } 4052 4053 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4054 // We calculate the max size of permissions defined by this uid and throw 4055 // if that plus the size of 'info' would exceed our stated maximum. 4056 if (tree.uid != Process.SYSTEM_UID) { 4057 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4058 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4059 throw new SecurityException("Permission tree size cap exceeded"); 4060 } 4061 } 4062 } 4063 4064 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4065 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4066 throw new SecurityException("Label must be specified in permission"); 4067 } 4068 BasePermission tree = checkPermissionTreeLP(info.name); 4069 BasePermission bp = mSettings.mPermissions.get(info.name); 4070 boolean added = bp == null; 4071 boolean changed = true; 4072 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4073 if (added) { 4074 enforcePermissionCapLocked(info, tree); 4075 bp = new BasePermission(info.name, tree.sourcePackage, 4076 BasePermission.TYPE_DYNAMIC); 4077 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4078 throw new SecurityException( 4079 "Not allowed to modify non-dynamic permission " 4080 + info.name); 4081 } else { 4082 if (bp.protectionLevel == fixedLevel 4083 && bp.perm.owner.equals(tree.perm.owner) 4084 && bp.uid == tree.uid 4085 && comparePermissionInfos(bp.perm.info, info)) { 4086 changed = false; 4087 } 4088 } 4089 bp.protectionLevel = fixedLevel; 4090 info = new PermissionInfo(info); 4091 info.protectionLevel = fixedLevel; 4092 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4093 bp.perm.info.packageName = tree.perm.info.packageName; 4094 bp.uid = tree.uid; 4095 if (added) { 4096 mSettings.mPermissions.put(info.name, bp); 4097 } 4098 if (changed) { 4099 if (!async) { 4100 mSettings.writeLPr(); 4101 } else { 4102 scheduleWriteSettingsLocked(); 4103 } 4104 } 4105 return added; 4106 } 4107 4108 @Override 4109 public boolean addPermission(PermissionInfo info) { 4110 synchronized (mPackages) { 4111 return addPermissionLocked(info, false); 4112 } 4113 } 4114 4115 @Override 4116 public boolean addPermissionAsync(PermissionInfo info) { 4117 synchronized (mPackages) { 4118 return addPermissionLocked(info, true); 4119 } 4120 } 4121 4122 @Override 4123 public void removePermission(String name) { 4124 synchronized (mPackages) { 4125 checkPermissionTreeLP(name); 4126 BasePermission bp = mSettings.mPermissions.get(name); 4127 if (bp != null) { 4128 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4129 throw new SecurityException( 4130 "Not allowed to modify non-dynamic permission " 4131 + name); 4132 } 4133 mSettings.mPermissions.remove(name); 4134 mSettings.writeLPr(); 4135 } 4136 } 4137 } 4138 4139 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4140 BasePermission bp) { 4141 int index = pkg.requestedPermissions.indexOf(bp.name); 4142 if (index == -1) { 4143 throw new SecurityException("Package " + pkg.packageName 4144 + " has not requested permission " + bp.name); 4145 } 4146 if (!bp.isRuntime() && !bp.isDevelopment()) { 4147 throw new SecurityException("Permission " + bp.name 4148 + " is not a changeable permission type"); 4149 } 4150 } 4151 4152 @Override 4153 public void grantRuntimePermission(String packageName, String name, final int userId) { 4154 if (!sUserManager.exists(userId)) { 4155 Log.e(TAG, "No such user:" + userId); 4156 return; 4157 } 4158 4159 mContext.enforceCallingOrSelfPermission( 4160 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4161 "grantRuntimePermission"); 4162 4163 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4164 true /* requireFullPermission */, true /* checkShell */, 4165 "grantRuntimePermission"); 4166 4167 final int uid; 4168 final SettingBase sb; 4169 4170 synchronized (mPackages) { 4171 final PackageParser.Package pkg = mPackages.get(packageName); 4172 if (pkg == null) { 4173 throw new IllegalArgumentException("Unknown package: " + packageName); 4174 } 4175 4176 final BasePermission bp = mSettings.mPermissions.get(name); 4177 if (bp == null) { 4178 throw new IllegalArgumentException("Unknown permission: " + name); 4179 } 4180 4181 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4182 4183 // If a permission review is required for legacy apps we represent 4184 // their permissions as always granted runtime ones since we need 4185 // to keep the review required permission flag per user while an 4186 // install permission's state is shared across all users. 4187 if (Build.PERMISSIONS_REVIEW_REQUIRED 4188 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4189 && bp.isRuntime()) { 4190 return; 4191 } 4192 4193 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4194 sb = (SettingBase) pkg.mExtras; 4195 if (sb == null) { 4196 throw new IllegalArgumentException("Unknown package: " + packageName); 4197 } 4198 4199 final PermissionsState permissionsState = sb.getPermissionsState(); 4200 4201 final int flags = permissionsState.getPermissionFlags(name, userId); 4202 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4203 throw new SecurityException("Cannot grant system fixed permission " 4204 + name + " for package " + packageName); 4205 } 4206 4207 if (bp.isDevelopment()) { 4208 // Development permissions must be handled specially, since they are not 4209 // normal runtime permissions. For now they apply to all users. 4210 if (permissionsState.grantInstallPermission(bp) != 4211 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4212 scheduleWriteSettingsLocked(); 4213 } 4214 return; 4215 } 4216 4217 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4218 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4219 return; 4220 } 4221 4222 final int result = permissionsState.grantRuntimePermission(bp, userId); 4223 switch (result) { 4224 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4225 return; 4226 } 4227 4228 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4229 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4230 mHandler.post(new Runnable() { 4231 @Override 4232 public void run() { 4233 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4234 } 4235 }); 4236 } 4237 break; 4238 } 4239 4240 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4241 4242 // Not critical if that is lost - app has to request again. 4243 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4244 } 4245 4246 // Only need to do this if user is initialized. Otherwise it's a new user 4247 // and there are no processes running as the user yet and there's no need 4248 // to make an expensive call to remount processes for the changed permissions. 4249 if (READ_EXTERNAL_STORAGE.equals(name) 4250 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4251 final long token = Binder.clearCallingIdentity(); 4252 try { 4253 if (sUserManager.isInitialized(userId)) { 4254 MountServiceInternal mountServiceInternal = LocalServices.getService( 4255 MountServiceInternal.class); 4256 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4257 } 4258 } finally { 4259 Binder.restoreCallingIdentity(token); 4260 } 4261 } 4262 } 4263 4264 @Override 4265 public void revokeRuntimePermission(String packageName, String name, int userId) { 4266 if (!sUserManager.exists(userId)) { 4267 Log.e(TAG, "No such user:" + userId); 4268 return; 4269 } 4270 4271 mContext.enforceCallingOrSelfPermission( 4272 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4273 "revokeRuntimePermission"); 4274 4275 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4276 true /* requireFullPermission */, true /* checkShell */, 4277 "revokeRuntimePermission"); 4278 4279 final int appId; 4280 4281 synchronized (mPackages) { 4282 final PackageParser.Package pkg = mPackages.get(packageName); 4283 if (pkg == null) { 4284 throw new IllegalArgumentException("Unknown package: " + packageName); 4285 } 4286 4287 final BasePermission bp = mSettings.mPermissions.get(name); 4288 if (bp == null) { 4289 throw new IllegalArgumentException("Unknown permission: " + name); 4290 } 4291 4292 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4293 4294 // If a permission review is required for legacy apps we represent 4295 // their permissions as always granted runtime ones since we need 4296 // to keep the review required permission flag per user while an 4297 // install permission's state is shared across all users. 4298 if (Build.PERMISSIONS_REVIEW_REQUIRED 4299 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4300 && bp.isRuntime()) { 4301 return; 4302 } 4303 4304 SettingBase sb = (SettingBase) pkg.mExtras; 4305 if (sb == null) { 4306 throw new IllegalArgumentException("Unknown package: " + packageName); 4307 } 4308 4309 final PermissionsState permissionsState = sb.getPermissionsState(); 4310 4311 final int flags = permissionsState.getPermissionFlags(name, userId); 4312 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4313 throw new SecurityException("Cannot revoke system fixed permission " 4314 + name + " for package " + packageName); 4315 } 4316 4317 if (bp.isDevelopment()) { 4318 // Development permissions must be handled specially, since they are not 4319 // normal runtime permissions. For now they apply to all users. 4320 if (permissionsState.revokeInstallPermission(bp) != 4321 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4322 scheduleWriteSettingsLocked(); 4323 } 4324 return; 4325 } 4326 4327 if (permissionsState.revokeRuntimePermission(bp, userId) == 4328 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4329 return; 4330 } 4331 4332 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4333 4334 // Critical, after this call app should never have the permission. 4335 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4336 4337 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4338 } 4339 4340 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4341 } 4342 4343 @Override 4344 public void resetRuntimePermissions() { 4345 mContext.enforceCallingOrSelfPermission( 4346 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4347 "revokeRuntimePermission"); 4348 4349 int callingUid = Binder.getCallingUid(); 4350 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4351 mContext.enforceCallingOrSelfPermission( 4352 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4353 "resetRuntimePermissions"); 4354 } 4355 4356 synchronized (mPackages) { 4357 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4358 for (int userId : UserManagerService.getInstance().getUserIds()) { 4359 final int packageCount = mPackages.size(); 4360 for (int i = 0; i < packageCount; i++) { 4361 PackageParser.Package pkg = mPackages.valueAt(i); 4362 if (!(pkg.mExtras instanceof PackageSetting)) { 4363 continue; 4364 } 4365 PackageSetting ps = (PackageSetting) pkg.mExtras; 4366 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4367 } 4368 } 4369 } 4370 } 4371 4372 @Override 4373 public int getPermissionFlags(String name, String packageName, int userId) { 4374 if (!sUserManager.exists(userId)) { 4375 return 0; 4376 } 4377 4378 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4379 4380 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4381 true /* requireFullPermission */, false /* checkShell */, 4382 "getPermissionFlags"); 4383 4384 synchronized (mPackages) { 4385 final PackageParser.Package pkg = mPackages.get(packageName); 4386 if (pkg == null) { 4387 return 0; 4388 } 4389 4390 final BasePermission bp = mSettings.mPermissions.get(name); 4391 if (bp == null) { 4392 return 0; 4393 } 4394 4395 SettingBase sb = (SettingBase) pkg.mExtras; 4396 if (sb == null) { 4397 return 0; 4398 } 4399 4400 PermissionsState permissionsState = sb.getPermissionsState(); 4401 return permissionsState.getPermissionFlags(name, userId); 4402 } 4403 } 4404 4405 @Override 4406 public void updatePermissionFlags(String name, String packageName, int flagMask, 4407 int flagValues, int userId) { 4408 if (!sUserManager.exists(userId)) { 4409 return; 4410 } 4411 4412 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4413 4414 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4415 true /* requireFullPermission */, true /* checkShell */, 4416 "updatePermissionFlags"); 4417 4418 // Only the system can change these flags and nothing else. 4419 if (getCallingUid() != Process.SYSTEM_UID) { 4420 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4421 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4422 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4423 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4424 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4425 } 4426 4427 synchronized (mPackages) { 4428 final PackageParser.Package pkg = mPackages.get(packageName); 4429 if (pkg == null) { 4430 throw new IllegalArgumentException("Unknown package: " + packageName); 4431 } 4432 4433 final BasePermission bp = mSettings.mPermissions.get(name); 4434 if (bp == null) { 4435 throw new IllegalArgumentException("Unknown permission: " + name); 4436 } 4437 4438 SettingBase sb = (SettingBase) pkg.mExtras; 4439 if (sb == null) { 4440 throw new IllegalArgumentException("Unknown package: " + packageName); 4441 } 4442 4443 PermissionsState permissionsState = sb.getPermissionsState(); 4444 4445 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4446 4447 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4448 // Install and runtime permissions are stored in different places, 4449 // so figure out what permission changed and persist the change. 4450 if (permissionsState.getInstallPermissionState(name) != null) { 4451 scheduleWriteSettingsLocked(); 4452 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4453 || hadState) { 4454 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4455 } 4456 } 4457 } 4458 } 4459 4460 /** 4461 * Update the permission flags for all packages and runtime permissions of a user in order 4462 * to allow device or profile owner to remove POLICY_FIXED. 4463 */ 4464 @Override 4465 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4466 if (!sUserManager.exists(userId)) { 4467 return; 4468 } 4469 4470 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4471 4472 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4473 true /* requireFullPermission */, true /* checkShell */, 4474 "updatePermissionFlagsForAllApps"); 4475 4476 // Only the system can change system fixed flags. 4477 if (getCallingUid() != Process.SYSTEM_UID) { 4478 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4479 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4480 } 4481 4482 synchronized (mPackages) { 4483 boolean changed = false; 4484 final int packageCount = mPackages.size(); 4485 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4486 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4487 SettingBase sb = (SettingBase) pkg.mExtras; 4488 if (sb == null) { 4489 continue; 4490 } 4491 PermissionsState permissionsState = sb.getPermissionsState(); 4492 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4493 userId, flagMask, flagValues); 4494 } 4495 if (changed) { 4496 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4497 } 4498 } 4499 } 4500 4501 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4502 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4503 != PackageManager.PERMISSION_GRANTED 4504 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4505 != PackageManager.PERMISSION_GRANTED) { 4506 throw new SecurityException(message + " requires " 4507 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4508 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4509 } 4510 } 4511 4512 @Override 4513 public boolean shouldShowRequestPermissionRationale(String permissionName, 4514 String packageName, int userId) { 4515 if (UserHandle.getCallingUserId() != userId) { 4516 mContext.enforceCallingPermission( 4517 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4518 "canShowRequestPermissionRationale for user " + userId); 4519 } 4520 4521 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4522 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4523 return false; 4524 } 4525 4526 if (checkPermission(permissionName, packageName, userId) 4527 == PackageManager.PERMISSION_GRANTED) { 4528 return false; 4529 } 4530 4531 final int flags; 4532 4533 final long identity = Binder.clearCallingIdentity(); 4534 try { 4535 flags = getPermissionFlags(permissionName, 4536 packageName, userId); 4537 } finally { 4538 Binder.restoreCallingIdentity(identity); 4539 } 4540 4541 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4542 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4543 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4544 4545 if ((flags & fixedFlags) != 0) { 4546 return false; 4547 } 4548 4549 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4550 } 4551 4552 @Override 4553 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4554 mContext.enforceCallingOrSelfPermission( 4555 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4556 "addOnPermissionsChangeListener"); 4557 4558 synchronized (mPackages) { 4559 mOnPermissionChangeListeners.addListenerLocked(listener); 4560 } 4561 } 4562 4563 @Override 4564 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4565 synchronized (mPackages) { 4566 mOnPermissionChangeListeners.removeListenerLocked(listener); 4567 } 4568 } 4569 4570 @Override 4571 public boolean isProtectedBroadcast(String actionName) { 4572 synchronized (mPackages) { 4573 if (mProtectedBroadcasts.contains(actionName)) { 4574 return true; 4575 } else if (actionName != null) { 4576 // TODO: remove these terrible hacks 4577 if (actionName.startsWith("android.net.netmon.lingerExpired") 4578 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4579 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4580 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4581 return true; 4582 } 4583 } 4584 } 4585 return false; 4586 } 4587 4588 @Override 4589 public int checkSignatures(String pkg1, String pkg2) { 4590 synchronized (mPackages) { 4591 final PackageParser.Package p1 = mPackages.get(pkg1); 4592 final PackageParser.Package p2 = mPackages.get(pkg2); 4593 if (p1 == null || p1.mExtras == null 4594 || p2 == null || p2.mExtras == null) { 4595 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4596 } 4597 return compareSignatures(p1.mSignatures, p2.mSignatures); 4598 } 4599 } 4600 4601 @Override 4602 public int checkUidSignatures(int uid1, int uid2) { 4603 // Map to base uids. 4604 uid1 = UserHandle.getAppId(uid1); 4605 uid2 = UserHandle.getAppId(uid2); 4606 // reader 4607 synchronized (mPackages) { 4608 Signature[] s1; 4609 Signature[] s2; 4610 Object obj = mSettings.getUserIdLPr(uid1); 4611 if (obj != null) { 4612 if (obj instanceof SharedUserSetting) { 4613 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4614 } else if (obj instanceof PackageSetting) { 4615 s1 = ((PackageSetting)obj).signatures.mSignatures; 4616 } else { 4617 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4618 } 4619 } else { 4620 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4621 } 4622 obj = mSettings.getUserIdLPr(uid2); 4623 if (obj != null) { 4624 if (obj instanceof SharedUserSetting) { 4625 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4626 } else if (obj instanceof PackageSetting) { 4627 s2 = ((PackageSetting)obj).signatures.mSignatures; 4628 } else { 4629 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4630 } 4631 } else { 4632 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4633 } 4634 return compareSignatures(s1, s2); 4635 } 4636 } 4637 4638 /** 4639 * This method should typically only be used when granting or revoking 4640 * permissions, since the app may immediately restart after this call. 4641 * <p> 4642 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4643 * guard your work against the app being relaunched. 4644 */ 4645 private void killUid(int appId, int userId, String reason) { 4646 final long identity = Binder.clearCallingIdentity(); 4647 try { 4648 IActivityManager am = ActivityManagerNative.getDefault(); 4649 if (am != null) { 4650 try { 4651 am.killUid(appId, userId, reason); 4652 } catch (RemoteException e) { 4653 /* ignore - same process */ 4654 } 4655 } 4656 } finally { 4657 Binder.restoreCallingIdentity(identity); 4658 } 4659 } 4660 4661 /** 4662 * Compares two sets of signatures. Returns: 4663 * <br /> 4664 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4665 * <br /> 4666 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4667 * <br /> 4668 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4669 * <br /> 4670 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4671 * <br /> 4672 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4673 */ 4674 static int compareSignatures(Signature[] s1, Signature[] s2) { 4675 if (s1 == null) { 4676 return s2 == null 4677 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4678 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4679 } 4680 4681 if (s2 == null) { 4682 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4683 } 4684 4685 if (s1.length != s2.length) { 4686 return PackageManager.SIGNATURE_NO_MATCH; 4687 } 4688 4689 // Since both signature sets are of size 1, we can compare without HashSets. 4690 if (s1.length == 1) { 4691 return s1[0].equals(s2[0]) ? 4692 PackageManager.SIGNATURE_MATCH : 4693 PackageManager.SIGNATURE_NO_MATCH; 4694 } 4695 4696 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4697 for (Signature sig : s1) { 4698 set1.add(sig); 4699 } 4700 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4701 for (Signature sig : s2) { 4702 set2.add(sig); 4703 } 4704 // Make sure s2 contains all signatures in s1. 4705 if (set1.equals(set2)) { 4706 return PackageManager.SIGNATURE_MATCH; 4707 } 4708 return PackageManager.SIGNATURE_NO_MATCH; 4709 } 4710 4711 /** 4712 * If the database version for this type of package (internal storage or 4713 * external storage) is less than the version where package signatures 4714 * were updated, return true. 4715 */ 4716 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4717 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4718 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4719 } 4720 4721 /** 4722 * Used for backward compatibility to make sure any packages with 4723 * certificate chains get upgraded to the new style. {@code existingSigs} 4724 * will be in the old format (since they were stored on disk from before the 4725 * system upgrade) and {@code scannedSigs} will be in the newer format. 4726 */ 4727 private int compareSignaturesCompat(PackageSignatures existingSigs, 4728 PackageParser.Package scannedPkg) { 4729 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4730 return PackageManager.SIGNATURE_NO_MATCH; 4731 } 4732 4733 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4734 for (Signature sig : existingSigs.mSignatures) { 4735 existingSet.add(sig); 4736 } 4737 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4738 for (Signature sig : scannedPkg.mSignatures) { 4739 try { 4740 Signature[] chainSignatures = sig.getChainSignatures(); 4741 for (Signature chainSig : chainSignatures) { 4742 scannedCompatSet.add(chainSig); 4743 } 4744 } catch (CertificateEncodingException e) { 4745 scannedCompatSet.add(sig); 4746 } 4747 } 4748 /* 4749 * Make sure the expanded scanned set contains all signatures in the 4750 * existing one. 4751 */ 4752 if (scannedCompatSet.equals(existingSet)) { 4753 // Migrate the old signatures to the new scheme. 4754 existingSigs.assignSignatures(scannedPkg.mSignatures); 4755 // The new KeySets will be re-added later in the scanning process. 4756 synchronized (mPackages) { 4757 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4758 } 4759 return PackageManager.SIGNATURE_MATCH; 4760 } 4761 return PackageManager.SIGNATURE_NO_MATCH; 4762 } 4763 4764 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4765 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4766 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4767 } 4768 4769 private int compareSignaturesRecover(PackageSignatures existingSigs, 4770 PackageParser.Package scannedPkg) { 4771 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4772 return PackageManager.SIGNATURE_NO_MATCH; 4773 } 4774 4775 String msg = null; 4776 try { 4777 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4778 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4779 + scannedPkg.packageName); 4780 return PackageManager.SIGNATURE_MATCH; 4781 } 4782 } catch (CertificateException e) { 4783 msg = e.getMessage(); 4784 } 4785 4786 logCriticalInfo(Log.INFO, 4787 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4788 return PackageManager.SIGNATURE_NO_MATCH; 4789 } 4790 4791 @Override 4792 public List<String> getAllPackages() { 4793 synchronized (mPackages) { 4794 return new ArrayList<String>(mPackages.keySet()); 4795 } 4796 } 4797 4798 @Override 4799 public String[] getPackagesForUid(int uid) { 4800 uid = UserHandle.getAppId(uid); 4801 // reader 4802 synchronized (mPackages) { 4803 Object obj = mSettings.getUserIdLPr(uid); 4804 if (obj instanceof SharedUserSetting) { 4805 final SharedUserSetting sus = (SharedUserSetting) obj; 4806 final int N = sus.packages.size(); 4807 final String[] res = new String[N]; 4808 for (int i = 0; i < N; i++) { 4809 res[i] = sus.packages.valueAt(i).name; 4810 } 4811 return res; 4812 } else if (obj instanceof PackageSetting) { 4813 final PackageSetting ps = (PackageSetting) obj; 4814 return new String[] { ps.name }; 4815 } 4816 } 4817 return null; 4818 } 4819 4820 @Override 4821 public String getNameForUid(int uid) { 4822 // reader 4823 synchronized (mPackages) { 4824 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4825 if (obj instanceof SharedUserSetting) { 4826 final SharedUserSetting sus = (SharedUserSetting) obj; 4827 return sus.name + ":" + sus.userId; 4828 } else if (obj instanceof PackageSetting) { 4829 final PackageSetting ps = (PackageSetting) obj; 4830 return ps.name; 4831 } 4832 } 4833 return null; 4834 } 4835 4836 @Override 4837 public int getUidForSharedUser(String sharedUserName) { 4838 if(sharedUserName == null) { 4839 return -1; 4840 } 4841 // reader 4842 synchronized (mPackages) { 4843 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4844 if (suid == null) { 4845 return -1; 4846 } 4847 return suid.userId; 4848 } 4849 } 4850 4851 @Override 4852 public int getFlagsForUid(int uid) { 4853 synchronized (mPackages) { 4854 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4855 if (obj instanceof SharedUserSetting) { 4856 final SharedUserSetting sus = (SharedUserSetting) obj; 4857 return sus.pkgFlags; 4858 } else if (obj instanceof PackageSetting) { 4859 final PackageSetting ps = (PackageSetting) obj; 4860 return ps.pkgFlags; 4861 } 4862 } 4863 return 0; 4864 } 4865 4866 @Override 4867 public int getPrivateFlagsForUid(int uid) { 4868 synchronized (mPackages) { 4869 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4870 if (obj instanceof SharedUserSetting) { 4871 final SharedUserSetting sus = (SharedUserSetting) obj; 4872 return sus.pkgPrivateFlags; 4873 } else if (obj instanceof PackageSetting) { 4874 final PackageSetting ps = (PackageSetting) obj; 4875 return ps.pkgPrivateFlags; 4876 } 4877 } 4878 return 0; 4879 } 4880 4881 @Override 4882 public boolean isUidPrivileged(int uid) { 4883 uid = UserHandle.getAppId(uid); 4884 // reader 4885 synchronized (mPackages) { 4886 Object obj = mSettings.getUserIdLPr(uid); 4887 if (obj instanceof SharedUserSetting) { 4888 final SharedUserSetting sus = (SharedUserSetting) obj; 4889 final Iterator<PackageSetting> it = sus.packages.iterator(); 4890 while (it.hasNext()) { 4891 if (it.next().isPrivileged()) { 4892 return true; 4893 } 4894 } 4895 } else if (obj instanceof PackageSetting) { 4896 final PackageSetting ps = (PackageSetting) obj; 4897 return ps.isPrivileged(); 4898 } 4899 } 4900 return false; 4901 } 4902 4903 @Override 4904 public String[] getAppOpPermissionPackages(String permissionName) { 4905 synchronized (mPackages) { 4906 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4907 if (pkgs == null) { 4908 return null; 4909 } 4910 return pkgs.toArray(new String[pkgs.size()]); 4911 } 4912 } 4913 4914 @Override 4915 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4916 int flags, int userId) { 4917 try { 4918 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4919 4920 if (!sUserManager.exists(userId)) return null; 4921 flags = updateFlagsForResolve(flags, userId, intent); 4922 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4923 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4924 4925 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4926 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4927 flags, userId); 4928 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4929 4930 final ResolveInfo bestChoice = 4931 chooseBestActivity(intent, resolvedType, flags, query, userId); 4932 4933 if (isEphemeralAllowed(intent, query, userId)) { 4934 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4935 final EphemeralResolveInfo ai = 4936 getEphemeralResolveInfo(intent, resolvedType, userId); 4937 if (ai != null) { 4938 if (DEBUG_EPHEMERAL) { 4939 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4940 } 4941 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4942 bestChoice.ephemeralResolveInfo = ai; 4943 } 4944 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4945 } 4946 return bestChoice; 4947 } finally { 4948 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4949 } 4950 } 4951 4952 @Override 4953 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4954 IntentFilter filter, int match, ComponentName activity) { 4955 final int userId = UserHandle.getCallingUserId(); 4956 if (DEBUG_PREFERRED) { 4957 Log.v(TAG, "setLastChosenActivity intent=" + intent 4958 + " resolvedType=" + resolvedType 4959 + " flags=" + flags 4960 + " filter=" + filter 4961 + " match=" + match 4962 + " activity=" + activity); 4963 filter.dump(new PrintStreamPrinter(System.out), " "); 4964 } 4965 intent.setComponent(null); 4966 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4967 userId); 4968 // Find any earlier preferred or last chosen entries and nuke them 4969 findPreferredActivity(intent, resolvedType, 4970 flags, query, 0, false, true, false, userId); 4971 // Add the new activity as the last chosen for this filter 4972 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4973 "Setting last chosen"); 4974 } 4975 4976 @Override 4977 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4978 final int userId = UserHandle.getCallingUserId(); 4979 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4980 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4981 userId); 4982 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4983 false, false, false, userId); 4984 } 4985 4986 4987 private boolean isEphemeralAllowed( 4988 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4989 // Short circuit and return early if possible. 4990 if (DISABLE_EPHEMERAL_APPS) { 4991 return false; 4992 } 4993 final int callingUser = UserHandle.getCallingUserId(); 4994 if (callingUser != UserHandle.USER_SYSTEM) { 4995 return false; 4996 } 4997 if (mEphemeralResolverConnection == null) { 4998 return false; 4999 } 5000 if (intent.getComponent() != null) { 5001 return false; 5002 } 5003 if (intent.getPackage() != null) { 5004 return false; 5005 } 5006 final boolean isWebUri = hasWebURI(intent); 5007 if (!isWebUri) { 5008 return false; 5009 } 5010 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5011 synchronized (mPackages) { 5012 final int count = resolvedActivites.size(); 5013 for (int n = 0; n < count; n++) { 5014 ResolveInfo info = resolvedActivites.get(n); 5015 String packageName = info.activityInfo.packageName; 5016 PackageSetting ps = mSettings.mPackages.get(packageName); 5017 if (ps != null) { 5018 // Try to get the status from User settings first 5019 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5020 int status = (int) (packedStatus >> 32); 5021 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5022 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5023 if (DEBUG_EPHEMERAL) { 5024 Slog.v(TAG, "DENY ephemeral apps;" 5025 + " pkg: " + packageName + ", status: " + status); 5026 } 5027 return false; 5028 } 5029 } 5030 } 5031 } 5032 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5033 return true; 5034 } 5035 5036 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 5037 int userId) { 5038 final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(), 5039 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 5040 final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(), 5041 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 5042 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 5043 ephemeralPrefixCount); 5044 final int[] shaPrefix = digest.getDigestPrefix(); 5045 final byte[][] digestBytes = digest.getDigestBytes(); 5046 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 5047 mEphemeralResolverConnection.getEphemeralResolveInfoList( 5048 shaPrefix, ephemeralPrefixMask); 5049 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 5050 // No hash prefix match; there are no ephemeral apps for this domain. 5051 return null; 5052 } 5053 5054 // Go in reverse order so we match the narrowest scope first. 5055 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 5056 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 5057 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 5058 continue; 5059 } 5060 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 5061 // No filters; this should never happen. 5062 if (filters.isEmpty()) { 5063 continue; 5064 } 5065 // We have a domain match; resolve the filters to see if anything matches. 5066 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 5067 for (int j = filters.size() - 1; j >= 0; --j) { 5068 final EphemeralResolveIntentInfo intentInfo = 5069 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 5070 ephemeralResolver.addFilter(intentInfo); 5071 } 5072 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 5073 intent, resolvedType, false /*defaultOnly*/, userId); 5074 if (!matchedResolveInfoList.isEmpty()) { 5075 return matchedResolveInfoList.get(0); 5076 } 5077 } 5078 } 5079 // Hash or filter mis-match; no ephemeral apps for this domain. 5080 return null; 5081 } 5082 5083 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5084 int flags, List<ResolveInfo> query, int userId) { 5085 if (query != null) { 5086 final int N = query.size(); 5087 if (N == 1) { 5088 return query.get(0); 5089 } else if (N > 1) { 5090 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5091 // If there is more than one activity with the same priority, 5092 // then let the user decide between them. 5093 ResolveInfo r0 = query.get(0); 5094 ResolveInfo r1 = query.get(1); 5095 if (DEBUG_INTENT_MATCHING || debug) { 5096 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5097 + r1.activityInfo.name + "=" + r1.priority); 5098 } 5099 // If the first activity has a higher priority, or a different 5100 // default, then it is always desirable to pick it. 5101 if (r0.priority != r1.priority 5102 || r0.preferredOrder != r1.preferredOrder 5103 || r0.isDefault != r1.isDefault) { 5104 return query.get(0); 5105 } 5106 // If we have saved a preference for a preferred activity for 5107 // this Intent, use that. 5108 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5109 flags, query, r0.priority, true, false, debug, userId); 5110 if (ri != null) { 5111 return ri; 5112 } 5113 ri = new ResolveInfo(mResolveInfo); 5114 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5115 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5116 // If all of the options come from the same package, show the application's 5117 // label and icon instead of the generic resolver's. 5118 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5119 // and then throw away the ResolveInfo itself, meaning that the caller loses 5120 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5121 // a fallback for this case; we only set the target package's resources on 5122 // the ResolveInfo, not the ActivityInfo. 5123 final String intentPackage = intent.getPackage(); 5124 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5125 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5126 ri.resolvePackageName = intentPackage; 5127 if (userNeedsBadging(userId)) { 5128 ri.noResourceId = true; 5129 } else { 5130 ri.icon = appi.icon; 5131 } 5132 ri.iconResourceId = appi.icon; 5133 ri.labelRes = appi.labelRes; 5134 } 5135 ri.activityInfo.applicationInfo = new ApplicationInfo( 5136 ri.activityInfo.applicationInfo); 5137 if (userId != 0) { 5138 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5139 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5140 } 5141 // Make sure that the resolver is displayable in car mode 5142 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5143 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5144 return ri; 5145 } 5146 } 5147 return null; 5148 } 5149 5150 /** 5151 * Return true if the given list is not empty and all of its contents have 5152 * an activityInfo with the given package name. 5153 */ 5154 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5155 if (ArrayUtils.isEmpty(list)) { 5156 return false; 5157 } 5158 for (int i = 0, N = list.size(); i < N; i++) { 5159 final ResolveInfo ri = list.get(i); 5160 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5161 if (ai == null || !packageName.equals(ai.packageName)) { 5162 return false; 5163 } 5164 } 5165 return true; 5166 } 5167 5168 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5169 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5170 final int N = query.size(); 5171 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5172 .get(userId); 5173 // Get the list of persistent preferred activities that handle the intent 5174 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5175 List<PersistentPreferredActivity> pprefs = ppir != null 5176 ? ppir.queryIntent(intent, resolvedType, 5177 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5178 : null; 5179 if (pprefs != null && pprefs.size() > 0) { 5180 final int M = pprefs.size(); 5181 for (int i=0; i<M; i++) { 5182 final PersistentPreferredActivity ppa = pprefs.get(i); 5183 if (DEBUG_PREFERRED || debug) { 5184 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5185 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5186 + "\n component=" + ppa.mComponent); 5187 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5188 } 5189 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5190 flags | MATCH_DISABLED_COMPONENTS, userId); 5191 if (DEBUG_PREFERRED || debug) { 5192 Slog.v(TAG, "Found persistent preferred activity:"); 5193 if (ai != null) { 5194 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5195 } else { 5196 Slog.v(TAG, " null"); 5197 } 5198 } 5199 if (ai == null) { 5200 // This previously registered persistent preferred activity 5201 // component is no longer known. Ignore it and do NOT remove it. 5202 continue; 5203 } 5204 for (int j=0; j<N; j++) { 5205 final ResolveInfo ri = query.get(j); 5206 if (!ri.activityInfo.applicationInfo.packageName 5207 .equals(ai.applicationInfo.packageName)) { 5208 continue; 5209 } 5210 if (!ri.activityInfo.name.equals(ai.name)) { 5211 continue; 5212 } 5213 // Found a persistent preference that can handle the intent. 5214 if (DEBUG_PREFERRED || debug) { 5215 Slog.v(TAG, "Returning persistent preferred activity: " + 5216 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5217 } 5218 return ri; 5219 } 5220 } 5221 } 5222 return null; 5223 } 5224 5225 // TODO: handle preferred activities missing while user has amnesia 5226 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5227 List<ResolveInfo> query, int priority, boolean always, 5228 boolean removeMatches, boolean debug, int userId) { 5229 if (!sUserManager.exists(userId)) return null; 5230 flags = updateFlagsForResolve(flags, userId, intent); 5231 // writer 5232 synchronized (mPackages) { 5233 if (intent.getSelector() != null) { 5234 intent = intent.getSelector(); 5235 } 5236 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5237 5238 // Try to find a matching persistent preferred activity. 5239 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5240 debug, userId); 5241 5242 // If a persistent preferred activity matched, use it. 5243 if (pri != null) { 5244 return pri; 5245 } 5246 5247 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5248 // Get the list of preferred activities that handle the intent 5249 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5250 List<PreferredActivity> prefs = pir != null 5251 ? pir.queryIntent(intent, resolvedType, 5252 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5253 : null; 5254 if (prefs != null && prefs.size() > 0) { 5255 boolean changed = false; 5256 try { 5257 // First figure out how good the original match set is. 5258 // We will only allow preferred activities that came 5259 // from the same match quality. 5260 int match = 0; 5261 5262 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5263 5264 final int N = query.size(); 5265 for (int j=0; j<N; j++) { 5266 final ResolveInfo ri = query.get(j); 5267 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5268 + ": 0x" + Integer.toHexString(match)); 5269 if (ri.match > match) { 5270 match = ri.match; 5271 } 5272 } 5273 5274 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5275 + Integer.toHexString(match)); 5276 5277 match &= IntentFilter.MATCH_CATEGORY_MASK; 5278 final int M = prefs.size(); 5279 for (int i=0; i<M; i++) { 5280 final PreferredActivity pa = prefs.get(i); 5281 if (DEBUG_PREFERRED || debug) { 5282 Slog.v(TAG, "Checking PreferredActivity ds=" 5283 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5284 + "\n component=" + pa.mPref.mComponent); 5285 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5286 } 5287 if (pa.mPref.mMatch != match) { 5288 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5289 + Integer.toHexString(pa.mPref.mMatch)); 5290 continue; 5291 } 5292 // If it's not an "always" type preferred activity and that's what we're 5293 // looking for, skip it. 5294 if (always && !pa.mPref.mAlways) { 5295 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5296 continue; 5297 } 5298 final ActivityInfo ai = getActivityInfo( 5299 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5300 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5301 userId); 5302 if (DEBUG_PREFERRED || debug) { 5303 Slog.v(TAG, "Found preferred activity:"); 5304 if (ai != null) { 5305 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5306 } else { 5307 Slog.v(TAG, " null"); 5308 } 5309 } 5310 if (ai == null) { 5311 // This previously registered preferred activity 5312 // component is no longer known. Most likely an update 5313 // to the app was installed and in the new version this 5314 // component no longer exists. Clean it up by removing 5315 // it from the preferred activities list, and skip it. 5316 Slog.w(TAG, "Removing dangling preferred activity: " 5317 + pa.mPref.mComponent); 5318 pir.removeFilter(pa); 5319 changed = true; 5320 continue; 5321 } 5322 for (int j=0; j<N; j++) { 5323 final ResolveInfo ri = query.get(j); 5324 if (!ri.activityInfo.applicationInfo.packageName 5325 .equals(ai.applicationInfo.packageName)) { 5326 continue; 5327 } 5328 if (!ri.activityInfo.name.equals(ai.name)) { 5329 continue; 5330 } 5331 5332 if (removeMatches) { 5333 pir.removeFilter(pa); 5334 changed = true; 5335 if (DEBUG_PREFERRED) { 5336 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5337 } 5338 break; 5339 } 5340 5341 // Okay we found a previously set preferred or last chosen app. 5342 // If the result set is different from when this 5343 // was created, we need to clear it and re-ask the 5344 // user their preference, if we're looking for an "always" type entry. 5345 if (always && !pa.mPref.sameSet(query)) { 5346 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5347 + intent + " type " + resolvedType); 5348 if (DEBUG_PREFERRED) { 5349 Slog.v(TAG, "Removing preferred activity since set changed " 5350 + pa.mPref.mComponent); 5351 } 5352 pir.removeFilter(pa); 5353 // Re-add the filter as a "last chosen" entry (!always) 5354 PreferredActivity lastChosen = new PreferredActivity( 5355 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5356 pir.addFilter(lastChosen); 5357 changed = true; 5358 return null; 5359 } 5360 5361 // Yay! Either the set matched or we're looking for the last chosen 5362 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5363 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5364 return ri; 5365 } 5366 } 5367 } finally { 5368 if (changed) { 5369 if (DEBUG_PREFERRED) { 5370 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5371 } 5372 scheduleWritePackageRestrictionsLocked(userId); 5373 } 5374 } 5375 } 5376 } 5377 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5378 return null; 5379 } 5380 5381 /* 5382 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5383 */ 5384 @Override 5385 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5386 int targetUserId) { 5387 mContext.enforceCallingOrSelfPermission( 5388 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5389 List<CrossProfileIntentFilter> matches = 5390 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5391 if (matches != null) { 5392 int size = matches.size(); 5393 for (int i = 0; i < size; i++) { 5394 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5395 } 5396 } 5397 if (hasWebURI(intent)) { 5398 // cross-profile app linking works only towards the parent. 5399 final UserInfo parent = getProfileParent(sourceUserId); 5400 synchronized(mPackages) { 5401 int flags = updateFlagsForResolve(0, parent.id, intent); 5402 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5403 intent, resolvedType, flags, sourceUserId, parent.id); 5404 return xpDomainInfo != null; 5405 } 5406 } 5407 return false; 5408 } 5409 5410 private UserInfo getProfileParent(int userId) { 5411 final long identity = Binder.clearCallingIdentity(); 5412 try { 5413 return sUserManager.getProfileParent(userId); 5414 } finally { 5415 Binder.restoreCallingIdentity(identity); 5416 } 5417 } 5418 5419 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5420 String resolvedType, int userId) { 5421 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5422 if (resolver != null) { 5423 return resolver.queryIntent(intent, resolvedType, false, userId); 5424 } 5425 return null; 5426 } 5427 5428 @Override 5429 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5430 String resolvedType, int flags, int userId) { 5431 try { 5432 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5433 5434 return new ParceledListSlice<>( 5435 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5436 } finally { 5437 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5438 } 5439 } 5440 5441 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5442 String resolvedType, int flags, int userId) { 5443 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5444 flags = updateFlagsForResolve(flags, userId, intent); 5445 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5446 false /* requireFullPermission */, false /* checkShell */, 5447 "query intent activities"); 5448 ComponentName comp = intent.getComponent(); 5449 if (comp == null) { 5450 if (intent.getSelector() != null) { 5451 intent = intent.getSelector(); 5452 comp = intent.getComponent(); 5453 } 5454 } 5455 5456 if (comp != null) { 5457 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5458 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5459 if (ai != null) { 5460 final ResolveInfo ri = new ResolveInfo(); 5461 ri.activityInfo = ai; 5462 list.add(ri); 5463 } 5464 return list; 5465 } 5466 5467 // reader 5468 synchronized (mPackages) { 5469 final String pkgName = intent.getPackage(); 5470 if (pkgName == null) { 5471 List<CrossProfileIntentFilter> matchingFilters = 5472 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5473 // Check for results that need to skip the current profile. 5474 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5475 resolvedType, flags, userId); 5476 if (xpResolveInfo != null) { 5477 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5478 result.add(xpResolveInfo); 5479 return filterIfNotSystemUser(result, userId); 5480 } 5481 5482 // Check for results in the current profile. 5483 List<ResolveInfo> result = mActivities.queryIntent( 5484 intent, resolvedType, flags, userId); 5485 result = filterIfNotSystemUser(result, userId); 5486 5487 // Check for cross profile results. 5488 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5489 xpResolveInfo = queryCrossProfileIntents( 5490 matchingFilters, intent, resolvedType, flags, userId, 5491 hasNonNegativePriorityResult); 5492 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5493 boolean isVisibleToUser = filterIfNotSystemUser( 5494 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5495 if (isVisibleToUser) { 5496 result.add(xpResolveInfo); 5497 Collections.sort(result, mResolvePrioritySorter); 5498 } 5499 } 5500 if (hasWebURI(intent)) { 5501 CrossProfileDomainInfo xpDomainInfo = null; 5502 final UserInfo parent = getProfileParent(userId); 5503 if (parent != null) { 5504 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5505 flags, userId, parent.id); 5506 } 5507 if (xpDomainInfo != null) { 5508 if (xpResolveInfo != null) { 5509 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5510 // in the result. 5511 result.remove(xpResolveInfo); 5512 } 5513 if (result.size() == 0) { 5514 result.add(xpDomainInfo.resolveInfo); 5515 return result; 5516 } 5517 } else if (result.size() <= 1) { 5518 return result; 5519 } 5520 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5521 xpDomainInfo, userId); 5522 Collections.sort(result, mResolvePrioritySorter); 5523 } 5524 return result; 5525 } 5526 final PackageParser.Package pkg = mPackages.get(pkgName); 5527 if (pkg != null) { 5528 return filterIfNotSystemUser( 5529 mActivities.queryIntentForPackage( 5530 intent, resolvedType, flags, pkg.activities, userId), 5531 userId); 5532 } 5533 return new ArrayList<ResolveInfo>(); 5534 } 5535 } 5536 5537 private static class CrossProfileDomainInfo { 5538 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5539 ResolveInfo resolveInfo; 5540 /* Best domain verification status of the activities found in the other profile */ 5541 int bestDomainVerificationStatus; 5542 } 5543 5544 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5545 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5546 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5547 sourceUserId)) { 5548 return null; 5549 } 5550 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5551 resolvedType, flags, parentUserId); 5552 5553 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5554 return null; 5555 } 5556 CrossProfileDomainInfo result = null; 5557 int size = resultTargetUser.size(); 5558 for (int i = 0; i < size; i++) { 5559 ResolveInfo riTargetUser = resultTargetUser.get(i); 5560 // Intent filter verification is only for filters that specify a host. So don't return 5561 // those that handle all web uris. 5562 if (riTargetUser.handleAllWebDataURI) { 5563 continue; 5564 } 5565 String packageName = riTargetUser.activityInfo.packageName; 5566 PackageSetting ps = mSettings.mPackages.get(packageName); 5567 if (ps == null) { 5568 continue; 5569 } 5570 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5571 int status = (int)(verificationState >> 32); 5572 if (result == null) { 5573 result = new CrossProfileDomainInfo(); 5574 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5575 sourceUserId, parentUserId); 5576 result.bestDomainVerificationStatus = status; 5577 } else { 5578 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5579 result.bestDomainVerificationStatus); 5580 } 5581 } 5582 // Don't consider matches with status NEVER across profiles. 5583 if (result != null && result.bestDomainVerificationStatus 5584 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5585 return null; 5586 } 5587 return result; 5588 } 5589 5590 /** 5591 * Verification statuses are ordered from the worse to the best, except for 5592 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5593 */ 5594 private int bestDomainVerificationStatus(int status1, int status2) { 5595 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5596 return status2; 5597 } 5598 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5599 return status1; 5600 } 5601 return (int) MathUtils.max(status1, status2); 5602 } 5603 5604 private boolean isUserEnabled(int userId) { 5605 long callingId = Binder.clearCallingIdentity(); 5606 try { 5607 UserInfo userInfo = sUserManager.getUserInfo(userId); 5608 return userInfo != null && userInfo.isEnabled(); 5609 } finally { 5610 Binder.restoreCallingIdentity(callingId); 5611 } 5612 } 5613 5614 /** 5615 * Filter out activities with systemUserOnly flag set, when current user is not System. 5616 * 5617 * @return filtered list 5618 */ 5619 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5620 if (userId == UserHandle.USER_SYSTEM) { 5621 return resolveInfos; 5622 } 5623 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5624 ResolveInfo info = resolveInfos.get(i); 5625 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5626 resolveInfos.remove(i); 5627 } 5628 } 5629 return resolveInfos; 5630 } 5631 5632 /** 5633 * @param resolveInfos list of resolve infos in descending priority order 5634 * @return if the list contains a resolve info with non-negative priority 5635 */ 5636 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5637 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5638 } 5639 5640 private static boolean hasWebURI(Intent intent) { 5641 if (intent.getData() == null) { 5642 return false; 5643 } 5644 final String scheme = intent.getScheme(); 5645 if (TextUtils.isEmpty(scheme)) { 5646 return false; 5647 } 5648 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5649 } 5650 5651 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5652 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5653 int userId) { 5654 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5655 5656 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5657 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5658 candidates.size()); 5659 } 5660 5661 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5662 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5663 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5664 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5665 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5666 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5667 5668 synchronized (mPackages) { 5669 final int count = candidates.size(); 5670 // First, try to use linked apps. Partition the candidates into four lists: 5671 // one for the final results, one for the "do not use ever", one for "undefined status" 5672 // and finally one for "browser app type". 5673 for (int n=0; n<count; n++) { 5674 ResolveInfo info = candidates.get(n); 5675 String packageName = info.activityInfo.packageName; 5676 PackageSetting ps = mSettings.mPackages.get(packageName); 5677 if (ps != null) { 5678 // Add to the special match all list (Browser use case) 5679 if (info.handleAllWebDataURI) { 5680 matchAllList.add(info); 5681 continue; 5682 } 5683 // Try to get the status from User settings first 5684 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5685 int status = (int)(packedStatus >> 32); 5686 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5687 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5688 if (DEBUG_DOMAIN_VERIFICATION) { 5689 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5690 + " : linkgen=" + linkGeneration); 5691 } 5692 // Use link-enabled generation as preferredOrder, i.e. 5693 // prefer newly-enabled over earlier-enabled. 5694 info.preferredOrder = linkGeneration; 5695 alwaysList.add(info); 5696 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5697 if (DEBUG_DOMAIN_VERIFICATION) { 5698 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5699 } 5700 neverList.add(info); 5701 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5702 if (DEBUG_DOMAIN_VERIFICATION) { 5703 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5704 } 5705 alwaysAskList.add(info); 5706 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5707 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5708 if (DEBUG_DOMAIN_VERIFICATION) { 5709 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5710 } 5711 undefinedList.add(info); 5712 } 5713 } 5714 } 5715 5716 // We'll want to include browser possibilities in a few cases 5717 boolean includeBrowser = false; 5718 5719 // First try to add the "always" resolution(s) for the current user, if any 5720 if (alwaysList.size() > 0) { 5721 result.addAll(alwaysList); 5722 } else { 5723 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5724 result.addAll(undefinedList); 5725 // Maybe add one for the other profile. 5726 if (xpDomainInfo != null && ( 5727 xpDomainInfo.bestDomainVerificationStatus 5728 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5729 result.add(xpDomainInfo.resolveInfo); 5730 } 5731 includeBrowser = true; 5732 } 5733 5734 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5735 // If there were 'always' entries their preferred order has been set, so we also 5736 // back that off to make the alternatives equivalent 5737 if (alwaysAskList.size() > 0) { 5738 for (ResolveInfo i : result) { 5739 i.preferredOrder = 0; 5740 } 5741 result.addAll(alwaysAskList); 5742 includeBrowser = true; 5743 } 5744 5745 if (includeBrowser) { 5746 // Also add browsers (all of them or only the default one) 5747 if (DEBUG_DOMAIN_VERIFICATION) { 5748 Slog.v(TAG, " ...including browsers in candidate set"); 5749 } 5750 if ((matchFlags & MATCH_ALL) != 0) { 5751 result.addAll(matchAllList); 5752 } else { 5753 // Browser/generic handling case. If there's a default browser, go straight 5754 // to that (but only if there is no other higher-priority match). 5755 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5756 int maxMatchPrio = 0; 5757 ResolveInfo defaultBrowserMatch = null; 5758 final int numCandidates = matchAllList.size(); 5759 for (int n = 0; n < numCandidates; n++) { 5760 ResolveInfo info = matchAllList.get(n); 5761 // track the highest overall match priority... 5762 if (info.priority > maxMatchPrio) { 5763 maxMatchPrio = info.priority; 5764 } 5765 // ...and the highest-priority default browser match 5766 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5767 if (defaultBrowserMatch == null 5768 || (defaultBrowserMatch.priority < info.priority)) { 5769 if (debug) { 5770 Slog.v(TAG, "Considering default browser match " + info); 5771 } 5772 defaultBrowserMatch = info; 5773 } 5774 } 5775 } 5776 if (defaultBrowserMatch != null 5777 && defaultBrowserMatch.priority >= maxMatchPrio 5778 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5779 { 5780 if (debug) { 5781 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5782 } 5783 result.add(defaultBrowserMatch); 5784 } else { 5785 result.addAll(matchAllList); 5786 } 5787 } 5788 5789 // If there is nothing selected, add all candidates and remove the ones that the user 5790 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5791 if (result.size() == 0) { 5792 result.addAll(candidates); 5793 result.removeAll(neverList); 5794 } 5795 } 5796 } 5797 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5798 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5799 result.size()); 5800 for (ResolveInfo info : result) { 5801 Slog.v(TAG, " + " + info.activityInfo); 5802 } 5803 } 5804 return result; 5805 } 5806 5807 // Returns a packed value as a long: 5808 // 5809 // high 'int'-sized word: link status: undefined/ask/never/always. 5810 // low 'int'-sized word: relative priority among 'always' results. 5811 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5812 long result = ps.getDomainVerificationStatusForUser(userId); 5813 // if none available, get the master status 5814 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5815 if (ps.getIntentFilterVerificationInfo() != null) { 5816 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5817 } 5818 } 5819 return result; 5820 } 5821 5822 private ResolveInfo querySkipCurrentProfileIntents( 5823 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5824 int flags, int sourceUserId) { 5825 if (matchingFilters != null) { 5826 int size = matchingFilters.size(); 5827 for (int i = 0; i < size; i ++) { 5828 CrossProfileIntentFilter filter = matchingFilters.get(i); 5829 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5830 // Checking if there are activities in the target user that can handle the 5831 // intent. 5832 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5833 resolvedType, flags, sourceUserId); 5834 if (resolveInfo != null) { 5835 return resolveInfo; 5836 } 5837 } 5838 } 5839 } 5840 return null; 5841 } 5842 5843 // Return matching ResolveInfo in target user if any. 5844 private ResolveInfo queryCrossProfileIntents( 5845 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5846 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5847 if (matchingFilters != null) { 5848 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5849 // match the same intent. For performance reasons, it is better not to 5850 // run queryIntent twice for the same userId 5851 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5852 int size = matchingFilters.size(); 5853 for (int i = 0; i < size; i++) { 5854 CrossProfileIntentFilter filter = matchingFilters.get(i); 5855 int targetUserId = filter.getTargetUserId(); 5856 boolean skipCurrentProfile = 5857 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5858 boolean skipCurrentProfileIfNoMatchFound = 5859 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5860 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5861 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5862 // Checking if there are activities in the target user that can handle the 5863 // intent. 5864 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5865 resolvedType, flags, sourceUserId); 5866 if (resolveInfo != null) return resolveInfo; 5867 alreadyTriedUserIds.put(targetUserId, true); 5868 } 5869 } 5870 } 5871 return null; 5872 } 5873 5874 /** 5875 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5876 * will forward the intent to the filter's target user. 5877 * Otherwise, returns null. 5878 */ 5879 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5880 String resolvedType, int flags, int sourceUserId) { 5881 int targetUserId = filter.getTargetUserId(); 5882 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5883 resolvedType, flags, targetUserId); 5884 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5885 // If all the matches in the target profile are suspended, return null. 5886 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5887 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5888 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5889 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5890 targetUserId); 5891 } 5892 } 5893 } 5894 return null; 5895 } 5896 5897 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5898 int sourceUserId, int targetUserId) { 5899 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5900 long ident = Binder.clearCallingIdentity(); 5901 boolean targetIsProfile; 5902 try { 5903 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5904 } finally { 5905 Binder.restoreCallingIdentity(ident); 5906 } 5907 String className; 5908 if (targetIsProfile) { 5909 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5910 } else { 5911 className = FORWARD_INTENT_TO_PARENT; 5912 } 5913 ComponentName forwardingActivityComponentName = new ComponentName( 5914 mAndroidApplication.packageName, className); 5915 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5916 sourceUserId); 5917 if (!targetIsProfile) { 5918 forwardingActivityInfo.showUserIcon = targetUserId; 5919 forwardingResolveInfo.noResourceId = true; 5920 } 5921 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5922 forwardingResolveInfo.priority = 0; 5923 forwardingResolveInfo.preferredOrder = 0; 5924 forwardingResolveInfo.match = 0; 5925 forwardingResolveInfo.isDefault = true; 5926 forwardingResolveInfo.filter = filter; 5927 forwardingResolveInfo.targetUserId = targetUserId; 5928 return forwardingResolveInfo; 5929 } 5930 5931 @Override 5932 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5933 Intent[] specifics, String[] specificTypes, Intent intent, 5934 String resolvedType, int flags, int userId) { 5935 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5936 specificTypes, intent, resolvedType, flags, userId)); 5937 } 5938 5939 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5940 Intent[] specifics, String[] specificTypes, Intent intent, 5941 String resolvedType, int flags, int userId) { 5942 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5943 flags = updateFlagsForResolve(flags, userId, intent); 5944 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5945 false /* requireFullPermission */, false /* checkShell */, 5946 "query intent activity options"); 5947 final String resultsAction = intent.getAction(); 5948 5949 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5950 | PackageManager.GET_RESOLVED_FILTER, userId); 5951 5952 if (DEBUG_INTENT_MATCHING) { 5953 Log.v(TAG, "Query " + intent + ": " + results); 5954 } 5955 5956 int specificsPos = 0; 5957 int N; 5958 5959 // todo: note that the algorithm used here is O(N^2). This 5960 // isn't a problem in our current environment, but if we start running 5961 // into situations where we have more than 5 or 10 matches then this 5962 // should probably be changed to something smarter... 5963 5964 // First we go through and resolve each of the specific items 5965 // that were supplied, taking care of removing any corresponding 5966 // duplicate items in the generic resolve list. 5967 if (specifics != null) { 5968 for (int i=0; i<specifics.length; i++) { 5969 final Intent sintent = specifics[i]; 5970 if (sintent == null) { 5971 continue; 5972 } 5973 5974 if (DEBUG_INTENT_MATCHING) { 5975 Log.v(TAG, "Specific #" + i + ": " + sintent); 5976 } 5977 5978 String action = sintent.getAction(); 5979 if (resultsAction != null && resultsAction.equals(action)) { 5980 // If this action was explicitly requested, then don't 5981 // remove things that have it. 5982 action = null; 5983 } 5984 5985 ResolveInfo ri = null; 5986 ActivityInfo ai = null; 5987 5988 ComponentName comp = sintent.getComponent(); 5989 if (comp == null) { 5990 ri = resolveIntent( 5991 sintent, 5992 specificTypes != null ? specificTypes[i] : null, 5993 flags, userId); 5994 if (ri == null) { 5995 continue; 5996 } 5997 if (ri == mResolveInfo) { 5998 // ACK! Must do something better with this. 5999 } 6000 ai = ri.activityInfo; 6001 comp = new ComponentName(ai.applicationInfo.packageName, 6002 ai.name); 6003 } else { 6004 ai = getActivityInfo(comp, flags, userId); 6005 if (ai == null) { 6006 continue; 6007 } 6008 } 6009 6010 // Look for any generic query activities that are duplicates 6011 // of this specific one, and remove them from the results. 6012 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6013 N = results.size(); 6014 int j; 6015 for (j=specificsPos; j<N; j++) { 6016 ResolveInfo sri = results.get(j); 6017 if ((sri.activityInfo.name.equals(comp.getClassName()) 6018 && sri.activityInfo.applicationInfo.packageName.equals( 6019 comp.getPackageName())) 6020 || (action != null && sri.filter.matchAction(action))) { 6021 results.remove(j); 6022 if (DEBUG_INTENT_MATCHING) Log.v( 6023 TAG, "Removing duplicate item from " + j 6024 + " due to specific " + specificsPos); 6025 if (ri == null) { 6026 ri = sri; 6027 } 6028 j--; 6029 N--; 6030 } 6031 } 6032 6033 // Add this specific item to its proper place. 6034 if (ri == null) { 6035 ri = new ResolveInfo(); 6036 ri.activityInfo = ai; 6037 } 6038 results.add(specificsPos, ri); 6039 ri.specificIndex = i; 6040 specificsPos++; 6041 } 6042 } 6043 6044 // Now we go through the remaining generic results and remove any 6045 // duplicate actions that are found here. 6046 N = results.size(); 6047 for (int i=specificsPos; i<N-1; i++) { 6048 final ResolveInfo rii = results.get(i); 6049 if (rii.filter == null) { 6050 continue; 6051 } 6052 6053 // Iterate over all of the actions of this result's intent 6054 // filter... typically this should be just one. 6055 final Iterator<String> it = rii.filter.actionsIterator(); 6056 if (it == null) { 6057 continue; 6058 } 6059 while (it.hasNext()) { 6060 final String action = it.next(); 6061 if (resultsAction != null && resultsAction.equals(action)) { 6062 // If this action was explicitly requested, then don't 6063 // remove things that have it. 6064 continue; 6065 } 6066 for (int j=i+1; j<N; j++) { 6067 final ResolveInfo rij = results.get(j); 6068 if (rij.filter != null && rij.filter.hasAction(action)) { 6069 results.remove(j); 6070 if (DEBUG_INTENT_MATCHING) Log.v( 6071 TAG, "Removing duplicate item from " + j 6072 + " due to action " + action + " at " + i); 6073 j--; 6074 N--; 6075 } 6076 } 6077 } 6078 6079 // If the caller didn't request filter information, drop it now 6080 // so we don't have to marshall/unmarshall it. 6081 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6082 rii.filter = null; 6083 } 6084 } 6085 6086 // Filter out the caller activity if so requested. 6087 if (caller != null) { 6088 N = results.size(); 6089 for (int i=0; i<N; i++) { 6090 ActivityInfo ainfo = results.get(i).activityInfo; 6091 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6092 && caller.getClassName().equals(ainfo.name)) { 6093 results.remove(i); 6094 break; 6095 } 6096 } 6097 } 6098 6099 // If the caller didn't request filter information, 6100 // drop them now so we don't have to 6101 // marshall/unmarshall it. 6102 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6103 N = results.size(); 6104 for (int i=0; i<N; i++) { 6105 results.get(i).filter = null; 6106 } 6107 } 6108 6109 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6110 return results; 6111 } 6112 6113 @Override 6114 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6115 String resolvedType, int flags, int userId) { 6116 return new ParceledListSlice<>( 6117 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6118 } 6119 6120 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6121 String resolvedType, int flags, int userId) { 6122 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6123 flags = updateFlagsForResolve(flags, userId, intent); 6124 ComponentName comp = intent.getComponent(); 6125 if (comp == null) { 6126 if (intent.getSelector() != null) { 6127 intent = intent.getSelector(); 6128 comp = intent.getComponent(); 6129 } 6130 } 6131 if (comp != null) { 6132 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6133 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6134 if (ai != null) { 6135 ResolveInfo ri = new ResolveInfo(); 6136 ri.activityInfo = ai; 6137 list.add(ri); 6138 } 6139 return list; 6140 } 6141 6142 // reader 6143 synchronized (mPackages) { 6144 String pkgName = intent.getPackage(); 6145 if (pkgName == null) { 6146 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6147 } 6148 final PackageParser.Package pkg = mPackages.get(pkgName); 6149 if (pkg != null) { 6150 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6151 userId); 6152 } 6153 return Collections.emptyList(); 6154 } 6155 } 6156 6157 @Override 6158 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6159 if (!sUserManager.exists(userId)) return null; 6160 flags = updateFlagsForResolve(flags, userId, intent); 6161 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6162 if (query != null) { 6163 if (query.size() >= 1) { 6164 // If there is more than one service with the same priority, 6165 // just arbitrarily pick the first one. 6166 return query.get(0); 6167 } 6168 } 6169 return null; 6170 } 6171 6172 @Override 6173 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6174 String resolvedType, int flags, int userId) { 6175 return new ParceledListSlice<>( 6176 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6177 } 6178 6179 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6180 String resolvedType, int flags, int userId) { 6181 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6182 flags = updateFlagsForResolve(flags, userId, intent); 6183 ComponentName comp = intent.getComponent(); 6184 if (comp == null) { 6185 if (intent.getSelector() != null) { 6186 intent = intent.getSelector(); 6187 comp = intent.getComponent(); 6188 } 6189 } 6190 if (comp != null) { 6191 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6192 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6193 if (si != null) { 6194 final ResolveInfo ri = new ResolveInfo(); 6195 ri.serviceInfo = si; 6196 list.add(ri); 6197 } 6198 return list; 6199 } 6200 6201 // reader 6202 synchronized (mPackages) { 6203 String pkgName = intent.getPackage(); 6204 if (pkgName == null) { 6205 return mServices.queryIntent(intent, resolvedType, flags, userId); 6206 } 6207 final PackageParser.Package pkg = mPackages.get(pkgName); 6208 if (pkg != null) { 6209 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6210 userId); 6211 } 6212 return Collections.emptyList(); 6213 } 6214 } 6215 6216 @Override 6217 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6218 String resolvedType, int flags, int userId) { 6219 return new ParceledListSlice<>( 6220 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6221 } 6222 6223 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6224 Intent intent, String resolvedType, int flags, int userId) { 6225 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6226 flags = updateFlagsForResolve(flags, userId, intent); 6227 ComponentName comp = intent.getComponent(); 6228 if (comp == null) { 6229 if (intent.getSelector() != null) { 6230 intent = intent.getSelector(); 6231 comp = intent.getComponent(); 6232 } 6233 } 6234 if (comp != null) { 6235 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6236 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6237 if (pi != null) { 6238 final ResolveInfo ri = new ResolveInfo(); 6239 ri.providerInfo = pi; 6240 list.add(ri); 6241 } 6242 return list; 6243 } 6244 6245 // reader 6246 synchronized (mPackages) { 6247 String pkgName = intent.getPackage(); 6248 if (pkgName == null) { 6249 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6250 } 6251 final PackageParser.Package pkg = mPackages.get(pkgName); 6252 if (pkg != null) { 6253 return mProviders.queryIntentForPackage( 6254 intent, resolvedType, flags, pkg.providers, userId); 6255 } 6256 return Collections.emptyList(); 6257 } 6258 } 6259 6260 @Override 6261 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6262 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6263 flags = updateFlagsForPackage(flags, userId, null); 6264 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6265 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6266 true /* requireFullPermission */, false /* checkShell */, 6267 "get installed packages"); 6268 6269 // writer 6270 synchronized (mPackages) { 6271 ArrayList<PackageInfo> list; 6272 if (listUninstalled) { 6273 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6274 for (PackageSetting ps : mSettings.mPackages.values()) { 6275 final PackageInfo pi; 6276 if (ps.pkg != null) { 6277 pi = generatePackageInfo(ps, flags, userId); 6278 } else { 6279 pi = generatePackageInfo(ps, flags, userId); 6280 } 6281 if (pi != null) { 6282 list.add(pi); 6283 } 6284 } 6285 } else { 6286 list = new ArrayList<PackageInfo>(mPackages.size()); 6287 for (PackageParser.Package p : mPackages.values()) { 6288 final PackageInfo pi = 6289 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6290 if (pi != null) { 6291 list.add(pi); 6292 } 6293 } 6294 } 6295 6296 return new ParceledListSlice<PackageInfo>(list); 6297 } 6298 } 6299 6300 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6301 String[] permissions, boolean[] tmp, int flags, int userId) { 6302 int numMatch = 0; 6303 final PermissionsState permissionsState = ps.getPermissionsState(); 6304 for (int i=0; i<permissions.length; i++) { 6305 final String permission = permissions[i]; 6306 if (permissionsState.hasPermission(permission, userId)) { 6307 tmp[i] = true; 6308 numMatch++; 6309 } else { 6310 tmp[i] = false; 6311 } 6312 } 6313 if (numMatch == 0) { 6314 return; 6315 } 6316 final PackageInfo pi; 6317 if (ps.pkg != null) { 6318 pi = generatePackageInfo(ps, flags, userId); 6319 } else { 6320 pi = generatePackageInfo(ps, flags, userId); 6321 } 6322 // The above might return null in cases of uninstalled apps or install-state 6323 // skew across users/profiles. 6324 if (pi != null) { 6325 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6326 if (numMatch == permissions.length) { 6327 pi.requestedPermissions = permissions; 6328 } else { 6329 pi.requestedPermissions = new String[numMatch]; 6330 numMatch = 0; 6331 for (int i=0; i<permissions.length; i++) { 6332 if (tmp[i]) { 6333 pi.requestedPermissions[numMatch] = permissions[i]; 6334 numMatch++; 6335 } 6336 } 6337 } 6338 } 6339 list.add(pi); 6340 } 6341 } 6342 6343 @Override 6344 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6345 String[] permissions, int flags, int userId) { 6346 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6347 flags = updateFlagsForPackage(flags, userId, permissions); 6348 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6349 6350 // writer 6351 synchronized (mPackages) { 6352 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6353 boolean[] tmpBools = new boolean[permissions.length]; 6354 if (listUninstalled) { 6355 for (PackageSetting ps : mSettings.mPackages.values()) { 6356 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6357 } 6358 } else { 6359 for (PackageParser.Package pkg : mPackages.values()) { 6360 PackageSetting ps = (PackageSetting)pkg.mExtras; 6361 if (ps != null) { 6362 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6363 userId); 6364 } 6365 } 6366 } 6367 6368 return new ParceledListSlice<PackageInfo>(list); 6369 } 6370 } 6371 6372 @Override 6373 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6374 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6375 flags = updateFlagsForApplication(flags, userId, null); 6376 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6377 6378 // writer 6379 synchronized (mPackages) { 6380 ArrayList<ApplicationInfo> list; 6381 if (listUninstalled) { 6382 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6383 for (PackageSetting ps : mSettings.mPackages.values()) { 6384 ApplicationInfo ai; 6385 if (ps.pkg != null) { 6386 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6387 ps.readUserState(userId), userId); 6388 } else { 6389 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6390 } 6391 if (ai != null) { 6392 list.add(ai); 6393 } 6394 } 6395 } else { 6396 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6397 for (PackageParser.Package p : mPackages.values()) { 6398 if (p.mExtras != null) { 6399 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6400 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6401 if (ai != null) { 6402 list.add(ai); 6403 } 6404 } 6405 } 6406 } 6407 6408 return new ParceledListSlice<ApplicationInfo>(list); 6409 } 6410 } 6411 6412 @Override 6413 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6414 if (DISABLE_EPHEMERAL_APPS) { 6415 return null; 6416 } 6417 6418 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6419 "getEphemeralApplications"); 6420 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6421 true /* requireFullPermission */, false /* checkShell */, 6422 "getEphemeralApplications"); 6423 synchronized (mPackages) { 6424 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6425 .getEphemeralApplicationsLPw(userId); 6426 if (ephemeralApps != null) { 6427 return new ParceledListSlice<>(ephemeralApps); 6428 } 6429 } 6430 return null; 6431 } 6432 6433 @Override 6434 public boolean isEphemeralApplication(String packageName, int userId) { 6435 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6436 true /* requireFullPermission */, false /* checkShell */, 6437 "isEphemeral"); 6438 if (DISABLE_EPHEMERAL_APPS) { 6439 return false; 6440 } 6441 6442 if (!isCallerSameApp(packageName)) { 6443 return false; 6444 } 6445 synchronized (mPackages) { 6446 PackageParser.Package pkg = mPackages.get(packageName); 6447 if (pkg != null) { 6448 return pkg.applicationInfo.isEphemeralApp(); 6449 } 6450 } 6451 return false; 6452 } 6453 6454 @Override 6455 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6456 if (DISABLE_EPHEMERAL_APPS) { 6457 return null; 6458 } 6459 6460 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6461 true /* requireFullPermission */, false /* checkShell */, 6462 "getCookie"); 6463 if (!isCallerSameApp(packageName)) { 6464 return null; 6465 } 6466 synchronized (mPackages) { 6467 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6468 packageName, userId); 6469 } 6470 } 6471 6472 @Override 6473 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6474 if (DISABLE_EPHEMERAL_APPS) { 6475 return true; 6476 } 6477 6478 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6479 true /* requireFullPermission */, true /* checkShell */, 6480 "setCookie"); 6481 if (!isCallerSameApp(packageName)) { 6482 return false; 6483 } 6484 synchronized (mPackages) { 6485 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6486 packageName, cookie, userId); 6487 } 6488 } 6489 6490 @Override 6491 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6492 if (DISABLE_EPHEMERAL_APPS) { 6493 return null; 6494 } 6495 6496 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6497 "getEphemeralApplicationIcon"); 6498 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6499 true /* requireFullPermission */, false /* checkShell */, 6500 "getEphemeralApplicationIcon"); 6501 synchronized (mPackages) { 6502 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6503 packageName, userId); 6504 } 6505 } 6506 6507 private boolean isCallerSameApp(String packageName) { 6508 PackageParser.Package pkg = mPackages.get(packageName); 6509 return pkg != null 6510 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6511 } 6512 6513 @Override 6514 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6515 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6516 } 6517 6518 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6519 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6520 6521 // reader 6522 synchronized (mPackages) { 6523 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6524 final int userId = UserHandle.getCallingUserId(); 6525 while (i.hasNext()) { 6526 final PackageParser.Package p = i.next(); 6527 if (p.applicationInfo == null) continue; 6528 6529 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6530 && !p.applicationInfo.isDirectBootAware(); 6531 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6532 && p.applicationInfo.isDirectBootAware(); 6533 6534 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6535 && (!mSafeMode || isSystemApp(p)) 6536 && (matchesUnaware || matchesAware)) { 6537 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6538 if (ps != null) { 6539 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6540 ps.readUserState(userId), userId); 6541 if (ai != null) { 6542 finalList.add(ai); 6543 } 6544 } 6545 } 6546 } 6547 } 6548 6549 return finalList; 6550 } 6551 6552 @Override 6553 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6554 if (!sUserManager.exists(userId)) return null; 6555 flags = updateFlagsForComponent(flags, userId, name); 6556 // reader 6557 synchronized (mPackages) { 6558 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6559 PackageSetting ps = provider != null 6560 ? mSettings.mPackages.get(provider.owner.packageName) 6561 : null; 6562 return ps != null 6563 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6564 ? PackageParser.generateProviderInfo(provider, flags, 6565 ps.readUserState(userId), userId) 6566 : null; 6567 } 6568 } 6569 6570 /** 6571 * @deprecated 6572 */ 6573 @Deprecated 6574 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6575 // reader 6576 synchronized (mPackages) { 6577 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6578 .entrySet().iterator(); 6579 final int userId = UserHandle.getCallingUserId(); 6580 while (i.hasNext()) { 6581 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6582 PackageParser.Provider p = entry.getValue(); 6583 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6584 6585 if (ps != null && p.syncable 6586 && (!mSafeMode || (p.info.applicationInfo.flags 6587 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6588 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6589 ps.readUserState(userId), userId); 6590 if (info != null) { 6591 outNames.add(entry.getKey()); 6592 outInfo.add(info); 6593 } 6594 } 6595 } 6596 } 6597 } 6598 6599 @Override 6600 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6601 int uid, int flags) { 6602 final int userId = processName != null ? UserHandle.getUserId(uid) 6603 : UserHandle.getCallingUserId(); 6604 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6605 flags = updateFlagsForComponent(flags, userId, processName); 6606 6607 ArrayList<ProviderInfo> finalList = null; 6608 // reader 6609 synchronized (mPackages) { 6610 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6611 while (i.hasNext()) { 6612 final PackageParser.Provider p = i.next(); 6613 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6614 if (ps != null && p.info.authority != null 6615 && (processName == null 6616 || (p.info.processName.equals(processName) 6617 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6618 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6619 if (finalList == null) { 6620 finalList = new ArrayList<ProviderInfo>(3); 6621 } 6622 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6623 ps.readUserState(userId), userId); 6624 if (info != null) { 6625 finalList.add(info); 6626 } 6627 } 6628 } 6629 } 6630 6631 if (finalList != null) { 6632 Collections.sort(finalList, mProviderInitOrderSorter); 6633 return new ParceledListSlice<ProviderInfo>(finalList); 6634 } 6635 6636 return ParceledListSlice.emptyList(); 6637 } 6638 6639 @Override 6640 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6641 // reader 6642 synchronized (mPackages) { 6643 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6644 return PackageParser.generateInstrumentationInfo(i, flags); 6645 } 6646 } 6647 6648 @Override 6649 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6650 String targetPackage, int flags) { 6651 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6652 } 6653 6654 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6655 int flags) { 6656 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6657 6658 // reader 6659 synchronized (mPackages) { 6660 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6661 while (i.hasNext()) { 6662 final PackageParser.Instrumentation p = i.next(); 6663 if (targetPackage == null 6664 || targetPackage.equals(p.info.targetPackage)) { 6665 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6666 flags); 6667 if (ii != null) { 6668 finalList.add(ii); 6669 } 6670 } 6671 } 6672 } 6673 6674 return finalList; 6675 } 6676 6677 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6678 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6679 if (overlays == null) { 6680 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6681 return; 6682 } 6683 for (PackageParser.Package opkg : overlays.values()) { 6684 // Not much to do if idmap fails: we already logged the error 6685 // and we certainly don't want to abort installation of pkg simply 6686 // because an overlay didn't fit properly. For these reasons, 6687 // ignore the return value of createIdmapForPackagePairLI. 6688 createIdmapForPackagePairLI(pkg, opkg); 6689 } 6690 } 6691 6692 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6693 PackageParser.Package opkg) { 6694 if (!opkg.mTrustedOverlay) { 6695 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6696 opkg.baseCodePath + ": overlay not trusted"); 6697 return false; 6698 } 6699 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6700 if (overlaySet == null) { 6701 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6702 opkg.baseCodePath + " but target package has no known overlays"); 6703 return false; 6704 } 6705 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6706 // TODO: generate idmap for split APKs 6707 try { 6708 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6709 } catch (InstallerException e) { 6710 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6711 + opkg.baseCodePath); 6712 return false; 6713 } 6714 PackageParser.Package[] overlayArray = 6715 overlaySet.values().toArray(new PackageParser.Package[0]); 6716 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6717 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6718 return p1.mOverlayPriority - p2.mOverlayPriority; 6719 } 6720 }; 6721 Arrays.sort(overlayArray, cmp); 6722 6723 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6724 int i = 0; 6725 for (PackageParser.Package p : overlayArray) { 6726 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6727 } 6728 return true; 6729 } 6730 6731 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6732 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6733 try { 6734 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6735 } finally { 6736 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6737 } 6738 } 6739 6740 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6741 final File[] files = dir.listFiles(); 6742 if (ArrayUtils.isEmpty(files)) { 6743 Log.d(TAG, "No files in app dir " + dir); 6744 return; 6745 } 6746 6747 if (DEBUG_PACKAGE_SCANNING) { 6748 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6749 + " flags=0x" + Integer.toHexString(parseFlags)); 6750 } 6751 6752 for (File file : files) { 6753 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6754 && !PackageInstallerService.isStageName(file.getName()); 6755 if (!isPackage) { 6756 // Ignore entries which are not packages 6757 continue; 6758 } 6759 try { 6760 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6761 scanFlags, currentTime, null); 6762 } catch (PackageManagerException e) { 6763 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6764 6765 // Delete invalid userdata apps 6766 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6767 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6768 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6769 removeCodePathLI(file); 6770 } 6771 } 6772 } 6773 } 6774 6775 private static File getSettingsProblemFile() { 6776 File dataDir = Environment.getDataDirectory(); 6777 File systemDir = new File(dataDir, "system"); 6778 File fname = new File(systemDir, "uiderrors.txt"); 6779 return fname; 6780 } 6781 6782 static void reportSettingsProblem(int priority, String msg) { 6783 logCriticalInfo(priority, msg); 6784 } 6785 6786 static void logCriticalInfo(int priority, String msg) { 6787 Slog.println(priority, TAG, msg); 6788 EventLogTags.writePmCriticalInfo(msg); 6789 try { 6790 File fname = getSettingsProblemFile(); 6791 FileOutputStream out = new FileOutputStream(fname, true); 6792 PrintWriter pw = new FastPrintWriter(out); 6793 SimpleDateFormat formatter = new SimpleDateFormat(); 6794 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6795 pw.println(dateString + ": " + msg); 6796 pw.close(); 6797 FileUtils.setPermissions( 6798 fname.toString(), 6799 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6800 -1, -1); 6801 } catch (java.io.IOException e) { 6802 } 6803 } 6804 6805 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6806 if (srcFile.isDirectory()) { 6807 final File baseFile = new File(pkg.baseCodePath); 6808 long maxModifiedTime = baseFile.lastModified(); 6809 if (pkg.splitCodePaths != null) { 6810 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6811 final File splitFile = new File(pkg.splitCodePaths[i]); 6812 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6813 } 6814 } 6815 return maxModifiedTime; 6816 } 6817 return srcFile.lastModified(); 6818 } 6819 6820 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6821 final int policyFlags) throws PackageManagerException { 6822 if (ps != null 6823 && ps.codePath.equals(srcFile) 6824 && ps.timeStamp == getLastModifiedTime(pkg, srcFile) 6825 && !isCompatSignatureUpdateNeeded(pkg) 6826 && !isRecoverSignatureUpdateNeeded(pkg)) { 6827 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6828 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6829 ArraySet<PublicKey> signingKs; 6830 synchronized (mPackages) { 6831 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6832 } 6833 if (ps.signatures.mSignatures != null 6834 && ps.signatures.mSignatures.length != 0 6835 && signingKs != null) { 6836 // Optimization: reuse the existing cached certificates 6837 // if the package appears to be unchanged. 6838 pkg.mSignatures = ps.signatures.mSignatures; 6839 pkg.mSigningKeys = signingKs; 6840 return; 6841 } 6842 6843 Slog.w(TAG, "PackageSetting for " + ps.name 6844 + " is missing signatures. Collecting certs again to recover them."); 6845 } else { 6846 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6847 } 6848 6849 try { 6850 PackageParser.collectCertificates(pkg, policyFlags); 6851 } catch (PackageParserException e) { 6852 throw PackageManagerException.from(e); 6853 } 6854 } 6855 6856 /** 6857 * Traces a package scan. 6858 * @see #scanPackageLI(File, int, int, long, UserHandle) 6859 */ 6860 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6861 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6862 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6863 try { 6864 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6865 } finally { 6866 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6867 } 6868 } 6869 6870 /** 6871 * Scans a package and returns the newly parsed package. 6872 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6873 */ 6874 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6875 long currentTime, UserHandle user) throws PackageManagerException { 6876 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6877 PackageParser pp = new PackageParser(); 6878 pp.setSeparateProcesses(mSeparateProcesses); 6879 pp.setOnlyCoreApps(mOnlyCore); 6880 pp.setDisplayMetrics(mMetrics); 6881 6882 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6883 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6884 } 6885 6886 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6887 final PackageParser.Package pkg; 6888 try { 6889 pkg = pp.parsePackage(scanFile, parseFlags); 6890 } catch (PackageParserException e) { 6891 throw PackageManagerException.from(e); 6892 } finally { 6893 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6894 } 6895 6896 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6897 } 6898 6899 /** 6900 * Scans a package and returns the newly parsed package. 6901 * @throws PackageManagerException on a parse error. 6902 */ 6903 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6904 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6905 throws PackageManagerException { 6906 // If the package has children and this is the first dive in the function 6907 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6908 // packages (parent and children) would be successfully scanned before the 6909 // actual scan since scanning mutates internal state and we want to atomically 6910 // install the package and its children. 6911 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6912 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6913 scanFlags |= SCAN_CHECK_ONLY; 6914 } 6915 } else { 6916 scanFlags &= ~SCAN_CHECK_ONLY; 6917 } 6918 6919 // Scan the parent 6920 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6921 scanFlags, currentTime, user); 6922 6923 // Scan the children 6924 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6925 for (int i = 0; i < childCount; i++) { 6926 PackageParser.Package childPackage = pkg.childPackages.get(i); 6927 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6928 currentTime, user); 6929 } 6930 6931 6932 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6933 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6934 } 6935 6936 return scannedPkg; 6937 } 6938 6939 /** 6940 * Scans a package and returns the newly parsed package. 6941 * @throws PackageManagerException on a parse error. 6942 */ 6943 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6944 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6945 throws PackageManagerException { 6946 PackageSetting ps = null; 6947 PackageSetting updatedPkg; 6948 // reader 6949 synchronized (mPackages) { 6950 // Look to see if we already know about this package. 6951 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6952 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6953 // This package has been renamed to its original name. Let's 6954 // use that. 6955 ps = mSettings.peekPackageLPr(oldName); 6956 } 6957 // If there was no original package, see one for the real package name. 6958 if (ps == null) { 6959 ps = mSettings.peekPackageLPr(pkg.packageName); 6960 } 6961 // Check to see if this package could be hiding/updating a system 6962 // package. Must look for it either under the original or real 6963 // package name depending on our state. 6964 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6965 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6966 6967 // If this is a package we don't know about on the system partition, we 6968 // may need to remove disabled child packages on the system partition 6969 // or may need to not add child packages if the parent apk is updated 6970 // on the data partition and no longer defines this child package. 6971 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6972 // If this is a parent package for an updated system app and this system 6973 // app got an OTA update which no longer defines some of the child packages 6974 // we have to prune them from the disabled system packages. 6975 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6976 if (disabledPs != null) { 6977 final int scannedChildCount = (pkg.childPackages != null) 6978 ? pkg.childPackages.size() : 0; 6979 final int disabledChildCount = disabledPs.childPackageNames != null 6980 ? disabledPs.childPackageNames.size() : 0; 6981 for (int i = 0; i < disabledChildCount; i++) { 6982 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6983 boolean disabledPackageAvailable = false; 6984 for (int j = 0; j < scannedChildCount; j++) { 6985 PackageParser.Package childPkg = pkg.childPackages.get(j); 6986 if (childPkg.packageName.equals(disabledChildPackageName)) { 6987 disabledPackageAvailable = true; 6988 break; 6989 } 6990 } 6991 if (!disabledPackageAvailable) { 6992 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6993 } 6994 } 6995 } 6996 } 6997 } 6998 6999 boolean updatedPkgBetter = false; 7000 // First check if this is a system package that may involve an update 7001 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7002 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7003 // it needs to drop FLAG_PRIVILEGED. 7004 if (locationIsPrivileged(scanFile)) { 7005 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7006 } else { 7007 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7008 } 7009 7010 if (ps != null && !ps.codePath.equals(scanFile)) { 7011 // The path has changed from what was last scanned... check the 7012 // version of the new path against what we have stored to determine 7013 // what to do. 7014 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7015 if (pkg.mVersionCode <= ps.versionCode) { 7016 // The system package has been updated and the code path does not match 7017 // Ignore entry. Skip it. 7018 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7019 + " ignored: updated version " + ps.versionCode 7020 + " better than this " + pkg.mVersionCode); 7021 if (!updatedPkg.codePath.equals(scanFile)) { 7022 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7023 + ps.name + " changing from " + updatedPkg.codePathString 7024 + " to " + scanFile); 7025 updatedPkg.codePath = scanFile; 7026 updatedPkg.codePathString = scanFile.toString(); 7027 updatedPkg.resourcePath = scanFile; 7028 updatedPkg.resourcePathString = scanFile.toString(); 7029 } 7030 updatedPkg.pkg = pkg; 7031 updatedPkg.versionCode = pkg.mVersionCode; 7032 7033 // Update the disabled system child packages to point to the package too. 7034 final int childCount = updatedPkg.childPackageNames != null 7035 ? updatedPkg.childPackageNames.size() : 0; 7036 for (int i = 0; i < childCount; i++) { 7037 String childPackageName = updatedPkg.childPackageNames.get(i); 7038 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7039 childPackageName); 7040 if (updatedChildPkg != null) { 7041 updatedChildPkg.pkg = pkg; 7042 updatedChildPkg.versionCode = pkg.mVersionCode; 7043 } 7044 } 7045 7046 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7047 + scanFile + " ignored: updated version " + ps.versionCode 7048 + " better than this " + pkg.mVersionCode); 7049 } else { 7050 // The current app on the system partition is better than 7051 // what we have updated to on the data partition; switch 7052 // back to the system partition version. 7053 // At this point, its safely assumed that package installation for 7054 // apps in system partition will go through. If not there won't be a working 7055 // version of the app 7056 // writer 7057 synchronized (mPackages) { 7058 // Just remove the loaded entries from package lists. 7059 mPackages.remove(ps.name); 7060 } 7061 7062 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7063 + " reverting from " + ps.codePathString 7064 + ": new version " + pkg.mVersionCode 7065 + " better than installed " + ps.versionCode); 7066 7067 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7068 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7069 synchronized (mInstallLock) { 7070 args.cleanUpResourcesLI(); 7071 } 7072 synchronized (mPackages) { 7073 mSettings.enableSystemPackageLPw(ps.name); 7074 } 7075 updatedPkgBetter = true; 7076 } 7077 } 7078 } 7079 7080 if (updatedPkg != null) { 7081 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7082 // initially 7083 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7084 7085 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7086 // flag set initially 7087 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7088 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7089 } 7090 } 7091 7092 // Verify certificates against what was last scanned 7093 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7094 7095 /* 7096 * A new system app appeared, but we already had a non-system one of the 7097 * same name installed earlier. 7098 */ 7099 boolean shouldHideSystemApp = false; 7100 if (updatedPkg == null && ps != null 7101 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7102 /* 7103 * Check to make sure the signatures match first. If they don't, 7104 * wipe the installed application and its data. 7105 */ 7106 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7107 != PackageManager.SIGNATURE_MATCH) { 7108 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7109 + " signatures don't match existing userdata copy; removing"); 7110 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7111 "scanPackageInternalLI")) { 7112 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7113 } 7114 ps = null; 7115 } else { 7116 /* 7117 * If the newly-added system app is an older version than the 7118 * already installed version, hide it. It will be scanned later 7119 * and re-added like an update. 7120 */ 7121 if (pkg.mVersionCode <= ps.versionCode) { 7122 shouldHideSystemApp = true; 7123 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7124 + " but new version " + pkg.mVersionCode + " better than installed " 7125 + ps.versionCode + "; hiding system"); 7126 } else { 7127 /* 7128 * The newly found system app is a newer version that the 7129 * one previously installed. Simply remove the 7130 * already-installed application and replace it with our own 7131 * while keeping the application data. 7132 */ 7133 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7134 + " reverting from " + ps.codePathString + ": new version " 7135 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7136 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7137 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7138 synchronized (mInstallLock) { 7139 args.cleanUpResourcesLI(); 7140 } 7141 } 7142 } 7143 } 7144 7145 // The apk is forward locked (not public) if its code and resources 7146 // are kept in different files. (except for app in either system or 7147 // vendor path). 7148 // TODO grab this value from PackageSettings 7149 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7150 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7151 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7152 } 7153 } 7154 7155 // TODO: extend to support forward-locked splits 7156 String resourcePath = null; 7157 String baseResourcePath = null; 7158 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7159 if (ps != null && ps.resourcePathString != null) { 7160 resourcePath = ps.resourcePathString; 7161 baseResourcePath = ps.resourcePathString; 7162 } else { 7163 // Should not happen at all. Just log an error. 7164 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7165 } 7166 } else { 7167 resourcePath = pkg.codePath; 7168 baseResourcePath = pkg.baseCodePath; 7169 } 7170 7171 // Set application objects path explicitly. 7172 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7173 pkg.setApplicationInfoCodePath(pkg.codePath); 7174 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7175 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7176 pkg.setApplicationInfoResourcePath(resourcePath); 7177 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7178 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7179 7180 // Note that we invoke the following method only if we are about to unpack an application 7181 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7182 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7183 7184 /* 7185 * If the system app should be overridden by a previously installed 7186 * data, hide the system app now and let the /data/app scan pick it up 7187 * again. 7188 */ 7189 if (shouldHideSystemApp) { 7190 synchronized (mPackages) { 7191 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7192 } 7193 } 7194 7195 return scannedPkg; 7196 } 7197 7198 private static String fixProcessName(String defProcessName, 7199 String processName, int uid) { 7200 if (processName == null) { 7201 return defProcessName; 7202 } 7203 return processName; 7204 } 7205 7206 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7207 throws PackageManagerException { 7208 if (pkgSetting.signatures.mSignatures != null) { 7209 // Already existing package. Make sure signatures match 7210 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7211 == PackageManager.SIGNATURE_MATCH; 7212 if (!match) { 7213 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7214 == PackageManager.SIGNATURE_MATCH; 7215 } 7216 if (!match) { 7217 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7218 == PackageManager.SIGNATURE_MATCH; 7219 } 7220 if (!match) { 7221 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7222 + pkg.packageName + " signatures do not match the " 7223 + "previously installed version; ignoring!"); 7224 } 7225 } 7226 7227 // Check for shared user signatures 7228 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7229 // Already existing package. Make sure signatures match 7230 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7231 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7232 if (!match) { 7233 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7234 == PackageManager.SIGNATURE_MATCH; 7235 } 7236 if (!match) { 7237 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7238 == PackageManager.SIGNATURE_MATCH; 7239 } 7240 if (!match) { 7241 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7242 "Package " + pkg.packageName 7243 + " has no signatures that match those in shared user " 7244 + pkgSetting.sharedUser.name + "; ignoring!"); 7245 } 7246 } 7247 } 7248 7249 /** 7250 * Enforces that only the system UID or root's UID can call a method exposed 7251 * via Binder. 7252 * 7253 * @param message used as message if SecurityException is thrown 7254 * @throws SecurityException if the caller is not system or root 7255 */ 7256 private static final void enforceSystemOrRoot(String message) { 7257 final int uid = Binder.getCallingUid(); 7258 if (uid != Process.SYSTEM_UID && uid != 0) { 7259 throw new SecurityException(message); 7260 } 7261 } 7262 7263 @Override 7264 public void performFstrimIfNeeded() { 7265 enforceSystemOrRoot("Only the system can request fstrim"); 7266 7267 // Before everything else, see whether we need to fstrim. 7268 try { 7269 IMountService ms = PackageHelper.getMountService(); 7270 if (ms != null) { 7271 boolean doTrim = false; 7272 final long interval = android.provider.Settings.Global.getLong( 7273 mContext.getContentResolver(), 7274 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7275 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7276 if (interval > 0) { 7277 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7278 if (timeSinceLast > interval) { 7279 doTrim = true; 7280 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7281 + "; running immediately"); 7282 } 7283 } 7284 if (doTrim) { 7285 if (!isFirstBoot()) { 7286 try { 7287 ActivityManagerNative.getDefault().showBootMessage( 7288 mContext.getResources().getString( 7289 R.string.android_upgrading_fstrim), true); 7290 } catch (RemoteException e) { 7291 } 7292 } 7293 ms.runMaintenance(); 7294 } 7295 } else { 7296 Slog.e(TAG, "Mount service unavailable!"); 7297 } 7298 } catch (RemoteException e) { 7299 // Can't happen; MountService is local 7300 } 7301 } 7302 7303 @Override 7304 public void updatePackagesIfNeeded() { 7305 enforceSystemOrRoot("Only the system can request package update"); 7306 7307 // We need to re-extract after an OTA. 7308 boolean causeUpgrade = isUpgrade(); 7309 7310 // First boot or factory reset. 7311 // Note: we also handle devices that are upgrading to N right now as if it is their 7312 // first boot, as they do not have profile data. 7313 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7314 7315 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7316 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7317 7318 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7319 return; 7320 } 7321 7322 List<PackageParser.Package> pkgs; 7323 synchronized (mPackages) { 7324 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7325 } 7326 7327 final long startTime = System.nanoTime(); 7328 final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */, 7329 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7330 7331 final int elapsedTimeSeconds = 7332 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7333 7334 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7335 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7336 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7337 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7338 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7339 } 7340 7341 /** 7342 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7343 * containing statistics about the invocation. The array consists of three elements, 7344 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7345 * and {@code numberOfPackagesFailed}. 7346 */ 7347 private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog, 7348 String compilerFilter) { 7349 7350 int numberOfPackagesVisited = 0; 7351 int numberOfPackagesOptimized = 0; 7352 int numberOfPackagesSkipped = 0; 7353 int numberOfPackagesFailed = 0; 7354 final int numberOfPackagesToDexopt = pkgs.size(); 7355 7356 for (PackageParser.Package pkg : pkgs) { 7357 numberOfPackagesVisited++; 7358 7359 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7360 if (DEBUG_DEXOPT) { 7361 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7362 } 7363 numberOfPackagesSkipped++; 7364 continue; 7365 } 7366 7367 if (DEBUG_DEXOPT) { 7368 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7369 numberOfPackagesToDexopt + ": " + pkg.packageName); 7370 } 7371 7372 if (showDialog) { 7373 try { 7374 ActivityManagerNative.getDefault().showBootMessage( 7375 mContext.getResources().getString(R.string.android_upgrading_apk, 7376 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7377 } catch (RemoteException e) { 7378 } 7379 } 7380 7381 // checkProfiles is false to avoid merging profiles during boot which 7382 // might interfere with background compilation (b/28612421). 7383 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7384 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7385 // trade-off worth doing to save boot time work. 7386 int dexOptStatus = performDexOptTraced(pkg.packageName, 7387 false /* checkProfiles */, 7388 compilerFilter, 7389 false /* force */); 7390 switch (dexOptStatus) { 7391 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7392 numberOfPackagesOptimized++; 7393 break; 7394 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7395 numberOfPackagesSkipped++; 7396 break; 7397 case PackageDexOptimizer.DEX_OPT_FAILED: 7398 numberOfPackagesFailed++; 7399 break; 7400 default: 7401 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7402 break; 7403 } 7404 } 7405 7406 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7407 numberOfPackagesFailed }; 7408 } 7409 7410 @Override 7411 public void notifyPackageUse(String packageName, int reason) { 7412 synchronized (mPackages) { 7413 PackageParser.Package p = mPackages.get(packageName); 7414 if (p == null) { 7415 return; 7416 } 7417 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7418 } 7419 } 7420 7421 // TODO: this is not used nor needed. Delete it. 7422 @Override 7423 public boolean performDexOptIfNeeded(String packageName) { 7424 int dexOptStatus = performDexOptTraced(packageName, 7425 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7426 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7427 } 7428 7429 @Override 7430 public boolean performDexOpt(String packageName, 7431 boolean checkProfiles, int compileReason, boolean force) { 7432 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7433 getCompilerFilterForReason(compileReason), force); 7434 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7435 } 7436 7437 @Override 7438 public boolean performDexOptMode(String packageName, 7439 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7440 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7441 targetCompilerFilter, force); 7442 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7443 } 7444 7445 private int performDexOptTraced(String packageName, 7446 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7447 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7448 try { 7449 return performDexOptInternal(packageName, checkProfiles, 7450 targetCompilerFilter, force); 7451 } finally { 7452 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7453 } 7454 } 7455 7456 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7457 // if the package can now be considered up to date for the given filter. 7458 private int performDexOptInternal(String packageName, 7459 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7460 PackageParser.Package p; 7461 synchronized (mPackages) { 7462 p = mPackages.get(packageName); 7463 if (p == null) { 7464 // Package could not be found. Report failure. 7465 return PackageDexOptimizer.DEX_OPT_FAILED; 7466 } 7467 mPackageUsage.write(false); 7468 } 7469 long callingId = Binder.clearCallingIdentity(); 7470 try { 7471 synchronized (mInstallLock) { 7472 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7473 targetCompilerFilter, force); 7474 } 7475 } finally { 7476 Binder.restoreCallingIdentity(callingId); 7477 } 7478 } 7479 7480 public ArraySet<String> getOptimizablePackages() { 7481 ArraySet<String> pkgs = new ArraySet<String>(); 7482 synchronized (mPackages) { 7483 for (PackageParser.Package p : mPackages.values()) { 7484 if (PackageDexOptimizer.canOptimizePackage(p)) { 7485 pkgs.add(p.packageName); 7486 } 7487 } 7488 } 7489 return pkgs; 7490 } 7491 7492 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7493 boolean checkProfiles, String targetCompilerFilter, 7494 boolean force) { 7495 // Select the dex optimizer based on the force parameter. 7496 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7497 // allocate an object here. 7498 PackageDexOptimizer pdo = force 7499 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7500 : mPackageDexOptimizer; 7501 7502 // Optimize all dependencies first. Note: we ignore the return value and march on 7503 // on errors. 7504 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7505 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7506 if (!deps.isEmpty()) { 7507 for (PackageParser.Package depPackage : deps) { 7508 // TODO: Analyze and investigate if we (should) profile libraries. 7509 // Currently this will do a full compilation of the library by default. 7510 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7511 false /* checkProfiles */, 7512 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7513 } 7514 } 7515 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7516 targetCompilerFilter); 7517 } 7518 7519 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7520 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7521 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7522 Set<String> collectedNames = new HashSet<>(); 7523 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7524 7525 retValue.remove(p); 7526 7527 return retValue; 7528 } else { 7529 return Collections.emptyList(); 7530 } 7531 } 7532 7533 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7534 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7535 if (!collectedNames.contains(p.packageName)) { 7536 collectedNames.add(p.packageName); 7537 collected.add(p); 7538 7539 if (p.usesLibraries != null) { 7540 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7541 } 7542 if (p.usesOptionalLibraries != null) { 7543 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7544 collectedNames); 7545 } 7546 } 7547 } 7548 7549 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7550 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7551 for (String libName : libs) { 7552 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7553 if (libPkg != null) { 7554 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7555 } 7556 } 7557 } 7558 7559 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7560 synchronized (mPackages) { 7561 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7562 if (lib != null && lib.apk != null) { 7563 return mPackages.get(lib.apk); 7564 } 7565 } 7566 return null; 7567 } 7568 7569 public void shutdown() { 7570 mPackageUsage.write(true); 7571 } 7572 7573 @Override 7574 public void dumpProfiles(String packageName) { 7575 PackageParser.Package pkg; 7576 synchronized (mPackages) { 7577 pkg = mPackages.get(packageName); 7578 if (pkg == null) { 7579 throw new IllegalArgumentException("Unknown package: " + packageName); 7580 } 7581 } 7582 /* Only the shell, root, or the app user should be able to dump profiles. */ 7583 int callingUid = Binder.getCallingUid(); 7584 if (callingUid != Process.SHELL_UID && 7585 callingUid != Process.ROOT_UID && 7586 callingUid != pkg.applicationInfo.uid) { 7587 throw new SecurityException("dumpProfiles"); 7588 } 7589 7590 synchronized (mInstallLock) { 7591 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7592 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7593 try { 7594 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7595 String gid = Integer.toString(sharedGid); 7596 String codePaths = TextUtils.join(";", allCodePaths); 7597 mInstaller.dumpProfiles(gid, packageName, codePaths); 7598 } catch (InstallerException e) { 7599 Slog.w(TAG, "Failed to dump profiles", e); 7600 } 7601 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7602 } 7603 } 7604 7605 @Override 7606 public void forceDexOpt(String packageName) { 7607 enforceSystemOrRoot("forceDexOpt"); 7608 7609 PackageParser.Package pkg; 7610 synchronized (mPackages) { 7611 pkg = mPackages.get(packageName); 7612 if (pkg == null) { 7613 throw new IllegalArgumentException("Unknown package: " + packageName); 7614 } 7615 } 7616 7617 synchronized (mInstallLock) { 7618 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7619 7620 // Whoever is calling forceDexOpt wants a fully compiled package. 7621 // Don't use profiles since that may cause compilation to be skipped. 7622 final int res = performDexOptInternalWithDependenciesLI(pkg, 7623 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7624 true /* force */); 7625 7626 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7627 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7628 throw new IllegalStateException("Failed to dexopt: " + res); 7629 } 7630 } 7631 } 7632 7633 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7634 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7635 Slog.w(TAG, "Unable to update from " + oldPkg.name 7636 + " to " + newPkg.packageName 7637 + ": old package not in system partition"); 7638 return false; 7639 } else if (mPackages.get(oldPkg.name) != null) { 7640 Slog.w(TAG, "Unable to update from " + oldPkg.name 7641 + " to " + newPkg.packageName 7642 + ": old package still exists"); 7643 return false; 7644 } 7645 return true; 7646 } 7647 7648 void removeCodePathLI(File codePath) { 7649 if (codePath.isDirectory()) { 7650 try { 7651 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7652 } catch (InstallerException e) { 7653 Slog.w(TAG, "Failed to remove code path", e); 7654 } 7655 } else { 7656 codePath.delete(); 7657 } 7658 } 7659 7660 private int[] resolveUserIds(int userId) { 7661 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7662 } 7663 7664 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7665 if (pkg == null) { 7666 Slog.wtf(TAG, "Package was null!", new Throwable()); 7667 return; 7668 } 7669 clearAppDataLeafLIF(pkg, userId, flags); 7670 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7671 for (int i = 0; i < childCount; i++) { 7672 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7673 } 7674 } 7675 7676 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7677 final PackageSetting ps; 7678 synchronized (mPackages) { 7679 ps = mSettings.mPackages.get(pkg.packageName); 7680 } 7681 for (int realUserId : resolveUserIds(userId)) { 7682 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7683 try { 7684 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7685 ceDataInode); 7686 } catch (InstallerException e) { 7687 Slog.w(TAG, String.valueOf(e)); 7688 } 7689 } 7690 } 7691 7692 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7693 if (pkg == null) { 7694 Slog.wtf(TAG, "Package was null!", new Throwable()); 7695 return; 7696 } 7697 destroyAppDataLeafLIF(pkg, userId, flags); 7698 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7699 for (int i = 0; i < childCount; i++) { 7700 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7701 } 7702 } 7703 7704 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7705 final PackageSetting ps; 7706 synchronized (mPackages) { 7707 ps = mSettings.mPackages.get(pkg.packageName); 7708 } 7709 for (int realUserId : resolveUserIds(userId)) { 7710 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7711 try { 7712 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7713 ceDataInode); 7714 } catch (InstallerException e) { 7715 Slog.w(TAG, String.valueOf(e)); 7716 } 7717 } 7718 } 7719 7720 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7721 if (pkg == null) { 7722 Slog.wtf(TAG, "Package was null!", new Throwable()); 7723 return; 7724 } 7725 destroyAppProfilesLeafLIF(pkg); 7726 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7727 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7728 for (int i = 0; i < childCount; i++) { 7729 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7730 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7731 true /* removeBaseMarker */); 7732 } 7733 } 7734 7735 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7736 boolean removeBaseMarker) { 7737 if (pkg.isForwardLocked()) { 7738 return; 7739 } 7740 7741 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7742 try { 7743 path = PackageManagerServiceUtils.realpath(new File(path)); 7744 } catch (IOException e) { 7745 // TODO: Should we return early here ? 7746 Slog.w(TAG, "Failed to get canonical path", e); 7747 continue; 7748 } 7749 7750 final String useMarker = path.replace('/', '@'); 7751 for (int realUserId : resolveUserIds(userId)) { 7752 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7753 if (removeBaseMarker) { 7754 File foreignUseMark = new File(profileDir, useMarker); 7755 if (foreignUseMark.exists()) { 7756 if (!foreignUseMark.delete()) { 7757 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7758 + pkg.packageName); 7759 } 7760 } 7761 } 7762 7763 File[] markers = profileDir.listFiles(); 7764 if (markers != null) { 7765 final String searchString = "@" + pkg.packageName + "@"; 7766 // We also delete all markers that contain the package name we're 7767 // uninstalling. These are associated with secondary dex-files belonging 7768 // to the package. Reconstructing the path of these dex files is messy 7769 // in general. 7770 for (File marker : markers) { 7771 if (marker.getName().indexOf(searchString) > 0) { 7772 if (!marker.delete()) { 7773 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7774 + pkg.packageName); 7775 } 7776 } 7777 } 7778 } 7779 } 7780 } 7781 } 7782 7783 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7784 try { 7785 mInstaller.destroyAppProfiles(pkg.packageName); 7786 } catch (InstallerException e) { 7787 Slog.w(TAG, String.valueOf(e)); 7788 } 7789 } 7790 7791 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7792 if (pkg == null) { 7793 Slog.wtf(TAG, "Package was null!", new Throwable()); 7794 return; 7795 } 7796 clearAppProfilesLeafLIF(pkg); 7797 // We don't remove the base foreign use marker when clearing profiles because 7798 // we will rename it when the app is updated. Unlike the actual profile contents, 7799 // the foreign use marker is good across installs. 7800 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7801 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7802 for (int i = 0; i < childCount; i++) { 7803 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7804 } 7805 } 7806 7807 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7808 try { 7809 mInstaller.clearAppProfiles(pkg.packageName); 7810 } catch (InstallerException e) { 7811 Slog.w(TAG, String.valueOf(e)); 7812 } 7813 } 7814 7815 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7816 long lastUpdateTime) { 7817 // Set parent install/update time 7818 PackageSetting ps = (PackageSetting) pkg.mExtras; 7819 if (ps != null) { 7820 ps.firstInstallTime = firstInstallTime; 7821 ps.lastUpdateTime = lastUpdateTime; 7822 } 7823 // Set children install/update time 7824 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7825 for (int i = 0; i < childCount; i++) { 7826 PackageParser.Package childPkg = pkg.childPackages.get(i); 7827 ps = (PackageSetting) childPkg.mExtras; 7828 if (ps != null) { 7829 ps.firstInstallTime = firstInstallTime; 7830 ps.lastUpdateTime = lastUpdateTime; 7831 } 7832 } 7833 } 7834 7835 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7836 PackageParser.Package changingLib) { 7837 if (file.path != null) { 7838 usesLibraryFiles.add(file.path); 7839 return; 7840 } 7841 PackageParser.Package p = mPackages.get(file.apk); 7842 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7843 // If we are doing this while in the middle of updating a library apk, 7844 // then we need to make sure to use that new apk for determining the 7845 // dependencies here. (We haven't yet finished committing the new apk 7846 // to the package manager state.) 7847 if (p == null || p.packageName.equals(changingLib.packageName)) { 7848 p = changingLib; 7849 } 7850 } 7851 if (p != null) { 7852 usesLibraryFiles.addAll(p.getAllCodePaths()); 7853 } 7854 } 7855 7856 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7857 PackageParser.Package changingLib) throws PackageManagerException { 7858 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7859 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7860 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7861 for (int i=0; i<N; i++) { 7862 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7863 if (file == null) { 7864 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7865 "Package " + pkg.packageName + " requires unavailable shared library " 7866 + pkg.usesLibraries.get(i) + "; failing!"); 7867 } 7868 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7869 } 7870 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7871 for (int i=0; i<N; i++) { 7872 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7873 if (file == null) { 7874 Slog.w(TAG, "Package " + pkg.packageName 7875 + " desires unavailable shared library " 7876 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7877 } else { 7878 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7879 } 7880 } 7881 N = usesLibraryFiles.size(); 7882 if (N > 0) { 7883 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7884 } else { 7885 pkg.usesLibraryFiles = null; 7886 } 7887 } 7888 } 7889 7890 private static boolean hasString(List<String> list, List<String> which) { 7891 if (list == null) { 7892 return false; 7893 } 7894 for (int i=list.size()-1; i>=0; i--) { 7895 for (int j=which.size()-1; j>=0; j--) { 7896 if (which.get(j).equals(list.get(i))) { 7897 return true; 7898 } 7899 } 7900 } 7901 return false; 7902 } 7903 7904 private void updateAllSharedLibrariesLPw() { 7905 for (PackageParser.Package pkg : mPackages.values()) { 7906 try { 7907 updateSharedLibrariesLPw(pkg, null); 7908 } catch (PackageManagerException e) { 7909 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7910 } 7911 } 7912 } 7913 7914 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7915 PackageParser.Package changingPkg) { 7916 ArrayList<PackageParser.Package> res = null; 7917 for (PackageParser.Package pkg : mPackages.values()) { 7918 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7919 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7920 if (res == null) { 7921 res = new ArrayList<PackageParser.Package>(); 7922 } 7923 res.add(pkg); 7924 try { 7925 updateSharedLibrariesLPw(pkg, changingPkg); 7926 } catch (PackageManagerException e) { 7927 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7928 } 7929 } 7930 } 7931 return res; 7932 } 7933 7934 /** 7935 * Derive the value of the {@code cpuAbiOverride} based on the provided 7936 * value and an optional stored value from the package settings. 7937 */ 7938 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7939 String cpuAbiOverride = null; 7940 7941 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7942 cpuAbiOverride = null; 7943 } else if (abiOverride != null) { 7944 cpuAbiOverride = abiOverride; 7945 } else if (settings != null) { 7946 cpuAbiOverride = settings.cpuAbiOverrideString; 7947 } 7948 7949 return cpuAbiOverride; 7950 } 7951 7952 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7953 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7954 throws PackageManagerException { 7955 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7956 // If the package has children and this is the first dive in the function 7957 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7958 // whether all packages (parent and children) would be successfully scanned 7959 // before the actual scan since scanning mutates internal state and we want 7960 // to atomically install the package and its children. 7961 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7962 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7963 scanFlags |= SCAN_CHECK_ONLY; 7964 } 7965 } else { 7966 scanFlags &= ~SCAN_CHECK_ONLY; 7967 } 7968 7969 final PackageParser.Package scannedPkg; 7970 try { 7971 // Scan the parent 7972 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7973 // Scan the children 7974 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7975 for (int i = 0; i < childCount; i++) { 7976 PackageParser.Package childPkg = pkg.childPackages.get(i); 7977 scanPackageLI(childPkg, policyFlags, 7978 scanFlags, currentTime, user); 7979 } 7980 } finally { 7981 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7982 } 7983 7984 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7985 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7986 } 7987 7988 return scannedPkg; 7989 } 7990 7991 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7992 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7993 boolean success = false; 7994 try { 7995 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7996 currentTime, user); 7997 success = true; 7998 return res; 7999 } finally { 8000 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8001 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8002 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8003 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8004 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8005 } 8006 } 8007 } 8008 8009 /** 8010 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8011 */ 8012 private static boolean apkHasCode(String fileName) { 8013 StrictJarFile jarFile = null; 8014 try { 8015 jarFile = new StrictJarFile(fileName, 8016 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8017 return jarFile.findEntry("classes.dex") != null; 8018 } catch (IOException ignore) { 8019 } finally { 8020 try { 8021 if (jarFile != null) { 8022 jarFile.close(); 8023 } 8024 } catch (IOException ignore) {} 8025 } 8026 return false; 8027 } 8028 8029 /** 8030 * Enforces code policy for the package. This ensures that if an APK has 8031 * declared hasCode="true" in its manifest that the APK actually contains 8032 * code. 8033 * 8034 * @throws PackageManagerException If bytecode could not be found when it should exist 8035 */ 8036 private static void enforceCodePolicy(PackageParser.Package pkg) 8037 throws PackageManagerException { 8038 final boolean shouldHaveCode = 8039 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8040 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8041 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8042 "Package " + pkg.baseCodePath + " code is missing"); 8043 } 8044 8045 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8046 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8047 final boolean splitShouldHaveCode = 8048 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8049 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8050 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8051 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8052 } 8053 } 8054 } 8055 } 8056 8057 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8058 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8059 throws PackageManagerException { 8060 final File scanFile = new File(pkg.codePath); 8061 if (pkg.applicationInfo.getCodePath() == null || 8062 pkg.applicationInfo.getResourcePath() == null) { 8063 // Bail out. The resource and code paths haven't been set. 8064 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8065 "Code and resource paths haven't been set correctly"); 8066 } 8067 8068 // Apply policy 8069 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8070 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8071 if (pkg.applicationInfo.isDirectBootAware()) { 8072 // we're direct boot aware; set for all components 8073 for (PackageParser.Service s : pkg.services) { 8074 s.info.encryptionAware = s.info.directBootAware = true; 8075 } 8076 for (PackageParser.Provider p : pkg.providers) { 8077 p.info.encryptionAware = p.info.directBootAware = true; 8078 } 8079 for (PackageParser.Activity a : pkg.activities) { 8080 a.info.encryptionAware = a.info.directBootAware = true; 8081 } 8082 for (PackageParser.Activity r : pkg.receivers) { 8083 r.info.encryptionAware = r.info.directBootAware = true; 8084 } 8085 } 8086 } else { 8087 // Only allow system apps to be flagged as core apps. 8088 pkg.coreApp = false; 8089 // clear flags not applicable to regular apps 8090 pkg.applicationInfo.privateFlags &= 8091 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8092 pkg.applicationInfo.privateFlags &= 8093 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8094 } 8095 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8096 8097 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8098 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8099 } 8100 8101 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8102 enforceCodePolicy(pkg); 8103 } 8104 8105 if (mCustomResolverComponentName != null && 8106 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8107 setUpCustomResolverActivity(pkg); 8108 } 8109 8110 if (pkg.packageName.equals("android")) { 8111 synchronized (mPackages) { 8112 if (mAndroidApplication != null) { 8113 Slog.w(TAG, "*************************************************"); 8114 Slog.w(TAG, "Core android package being redefined. Skipping."); 8115 Slog.w(TAG, " file=" + scanFile); 8116 Slog.w(TAG, "*************************************************"); 8117 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8118 "Core android package being redefined. Skipping."); 8119 } 8120 8121 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8122 // Set up information for our fall-back user intent resolution activity. 8123 mPlatformPackage = pkg; 8124 pkg.mVersionCode = mSdkVersion; 8125 mAndroidApplication = pkg.applicationInfo; 8126 8127 if (!mResolverReplaced) { 8128 mResolveActivity.applicationInfo = mAndroidApplication; 8129 mResolveActivity.name = ResolverActivity.class.getName(); 8130 mResolveActivity.packageName = mAndroidApplication.packageName; 8131 mResolveActivity.processName = "system:ui"; 8132 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8133 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8134 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8135 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8136 mResolveActivity.exported = true; 8137 mResolveActivity.enabled = true; 8138 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8139 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8140 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8141 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8142 | ActivityInfo.CONFIG_ORIENTATION 8143 | ActivityInfo.CONFIG_KEYBOARD 8144 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8145 mResolveInfo.activityInfo = mResolveActivity; 8146 mResolveInfo.priority = 0; 8147 mResolveInfo.preferredOrder = 0; 8148 mResolveInfo.match = 0; 8149 mResolveComponentName = new ComponentName( 8150 mAndroidApplication.packageName, mResolveActivity.name); 8151 } 8152 } 8153 } 8154 } 8155 8156 if (DEBUG_PACKAGE_SCANNING) { 8157 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8158 Log.d(TAG, "Scanning package " + pkg.packageName); 8159 } 8160 8161 synchronized (mPackages) { 8162 if (mPackages.containsKey(pkg.packageName) 8163 || mSharedLibraries.containsKey(pkg.packageName)) { 8164 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8165 "Application package " + pkg.packageName 8166 + " already installed. Skipping duplicate."); 8167 } 8168 8169 // If we're only installing presumed-existing packages, require that the 8170 // scanned APK is both already known and at the path previously established 8171 // for it. Previously unknown packages we pick up normally, but if we have an 8172 // a priori expectation about this package's install presence, enforce it. 8173 // With a singular exception for new system packages. When an OTA contains 8174 // a new system package, we allow the codepath to change from a system location 8175 // to the user-installed location. If we don't allow this change, any newer, 8176 // user-installed version of the application will be ignored. 8177 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8178 if (mExpectingBetter.containsKey(pkg.packageName)) { 8179 logCriticalInfo(Log.WARN, 8180 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8181 } else { 8182 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8183 if (known != null) { 8184 if (DEBUG_PACKAGE_SCANNING) { 8185 Log.d(TAG, "Examining " + pkg.codePath 8186 + " and requiring known paths " + known.codePathString 8187 + " & " + known.resourcePathString); 8188 } 8189 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8190 || !pkg.applicationInfo.getResourcePath().equals( 8191 known.resourcePathString)) { 8192 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8193 "Application package " + pkg.packageName 8194 + " found at " + pkg.applicationInfo.getCodePath() 8195 + " but expected at " + known.codePathString 8196 + "; ignoring."); 8197 } 8198 } 8199 } 8200 } 8201 } 8202 8203 // Initialize package source and resource directories 8204 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8205 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8206 8207 SharedUserSetting suid = null; 8208 PackageSetting pkgSetting = null; 8209 8210 if (!isSystemApp(pkg)) { 8211 // Only system apps can use these features. 8212 pkg.mOriginalPackages = null; 8213 pkg.mRealPackage = null; 8214 pkg.mAdoptPermissions = null; 8215 } 8216 8217 // Getting the package setting may have a side-effect, so if we 8218 // are only checking if scan would succeed, stash a copy of the 8219 // old setting to restore at the end. 8220 PackageSetting nonMutatedPs = null; 8221 8222 // writer 8223 synchronized (mPackages) { 8224 if (pkg.mSharedUserId != null) { 8225 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8226 if (suid == null) { 8227 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8228 "Creating application package " + pkg.packageName 8229 + " for shared user failed"); 8230 } 8231 if (DEBUG_PACKAGE_SCANNING) { 8232 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8233 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8234 + "): packages=" + suid.packages); 8235 } 8236 } 8237 8238 // Check if we are renaming from an original package name. 8239 PackageSetting origPackage = null; 8240 String realName = null; 8241 if (pkg.mOriginalPackages != null) { 8242 // This package may need to be renamed to a previously 8243 // installed name. Let's check on that... 8244 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8245 if (pkg.mOriginalPackages.contains(renamed)) { 8246 // This package had originally been installed as the 8247 // original name, and we have already taken care of 8248 // transitioning to the new one. Just update the new 8249 // one to continue using the old name. 8250 realName = pkg.mRealPackage; 8251 if (!pkg.packageName.equals(renamed)) { 8252 // Callers into this function may have already taken 8253 // care of renaming the package; only do it here if 8254 // it is not already done. 8255 pkg.setPackageName(renamed); 8256 } 8257 8258 } else { 8259 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8260 if ((origPackage = mSettings.peekPackageLPr( 8261 pkg.mOriginalPackages.get(i))) != null) { 8262 // We do have the package already installed under its 8263 // original name... should we use it? 8264 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8265 // New package is not compatible with original. 8266 origPackage = null; 8267 continue; 8268 } else if (origPackage.sharedUser != null) { 8269 // Make sure uid is compatible between packages. 8270 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8271 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8272 + " to " + pkg.packageName + ": old uid " 8273 + origPackage.sharedUser.name 8274 + " differs from " + pkg.mSharedUserId); 8275 origPackage = null; 8276 continue; 8277 } 8278 // TODO: Add case when shared user id is added [b/28144775] 8279 } else { 8280 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8281 + pkg.packageName + " to old name " + origPackage.name); 8282 } 8283 break; 8284 } 8285 } 8286 } 8287 } 8288 8289 if (mTransferedPackages.contains(pkg.packageName)) { 8290 Slog.w(TAG, "Package " + pkg.packageName 8291 + " was transferred to another, but its .apk remains"); 8292 } 8293 8294 // See comments in nonMutatedPs declaration 8295 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8296 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8297 if (foundPs != null) { 8298 nonMutatedPs = new PackageSetting(foundPs); 8299 } 8300 } 8301 8302 // Just create the setting, don't add it yet. For already existing packages 8303 // the PkgSetting exists already and doesn't have to be created. 8304 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8305 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8306 pkg.applicationInfo.primaryCpuAbi, 8307 pkg.applicationInfo.secondaryCpuAbi, 8308 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8309 user, false); 8310 if (pkgSetting == null) { 8311 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8312 "Creating application package " + pkg.packageName + " failed"); 8313 } 8314 8315 if (pkgSetting.origPackage != null) { 8316 // If we are first transitioning from an original package, 8317 // fix up the new package's name now. We need to do this after 8318 // looking up the package under its new name, so getPackageLP 8319 // can take care of fiddling things correctly. 8320 pkg.setPackageName(origPackage.name); 8321 8322 // File a report about this. 8323 String msg = "New package " + pkgSetting.realName 8324 + " renamed to replace old package " + pkgSetting.name; 8325 reportSettingsProblem(Log.WARN, msg); 8326 8327 // Make a note of it. 8328 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8329 mTransferedPackages.add(origPackage.name); 8330 } 8331 8332 // No longer need to retain this. 8333 pkgSetting.origPackage = null; 8334 } 8335 8336 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8337 // Make a note of it. 8338 mTransferedPackages.add(pkg.packageName); 8339 } 8340 8341 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8342 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8343 } 8344 8345 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8346 // Check all shared libraries and map to their actual file path. 8347 // We only do this here for apps not on a system dir, because those 8348 // are the only ones that can fail an install due to this. We 8349 // will take care of the system apps by updating all of their 8350 // library paths after the scan is done. 8351 updateSharedLibrariesLPw(pkg, null); 8352 } 8353 8354 if (mFoundPolicyFile) { 8355 SELinuxMMAC.assignSeinfoValue(pkg); 8356 } 8357 8358 pkg.applicationInfo.uid = pkgSetting.appId; 8359 pkg.mExtras = pkgSetting; 8360 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8361 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8362 // We just determined the app is signed correctly, so bring 8363 // over the latest parsed certs. 8364 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8365 } else { 8366 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8367 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8368 "Package " + pkg.packageName + " upgrade keys do not match the " 8369 + "previously installed version"); 8370 } else { 8371 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8372 String msg = "System package " + pkg.packageName 8373 + " signature changed; retaining data."; 8374 reportSettingsProblem(Log.WARN, msg); 8375 } 8376 } 8377 } else { 8378 try { 8379 verifySignaturesLP(pkgSetting, pkg); 8380 // We just determined the app is signed correctly, so bring 8381 // over the latest parsed certs. 8382 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8383 } catch (PackageManagerException e) { 8384 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8385 throw e; 8386 } 8387 // The signature has changed, but this package is in the system 8388 // image... let's recover! 8389 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8390 // However... if this package is part of a shared user, but it 8391 // doesn't match the signature of the shared user, let's fail. 8392 // What this means is that you can't change the signatures 8393 // associated with an overall shared user, which doesn't seem all 8394 // that unreasonable. 8395 if (pkgSetting.sharedUser != null) { 8396 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8397 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8398 throw new PackageManagerException( 8399 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8400 "Signature mismatch for shared user: " 8401 + pkgSetting.sharedUser); 8402 } 8403 } 8404 // File a report about this. 8405 String msg = "System package " + pkg.packageName 8406 + " signature changed; retaining data."; 8407 reportSettingsProblem(Log.WARN, msg); 8408 } 8409 } 8410 // Verify that this new package doesn't have any content providers 8411 // that conflict with existing packages. Only do this if the 8412 // package isn't already installed, since we don't want to break 8413 // things that are installed. 8414 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8415 final int N = pkg.providers.size(); 8416 int i; 8417 for (i=0; i<N; i++) { 8418 PackageParser.Provider p = pkg.providers.get(i); 8419 if (p.info.authority != null) { 8420 String names[] = p.info.authority.split(";"); 8421 for (int j = 0; j < names.length; j++) { 8422 if (mProvidersByAuthority.containsKey(names[j])) { 8423 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8424 final String otherPackageName = 8425 ((other != null && other.getComponentName() != null) ? 8426 other.getComponentName().getPackageName() : "?"); 8427 throw new PackageManagerException( 8428 INSTALL_FAILED_CONFLICTING_PROVIDER, 8429 "Can't install because provider name " + names[j] 8430 + " (in package " + pkg.applicationInfo.packageName 8431 + ") is already used by " + otherPackageName); 8432 } 8433 } 8434 } 8435 } 8436 } 8437 8438 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8439 // This package wants to adopt ownership of permissions from 8440 // another package. 8441 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8442 final String origName = pkg.mAdoptPermissions.get(i); 8443 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8444 if (orig != null) { 8445 if (verifyPackageUpdateLPr(orig, pkg)) { 8446 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8447 + pkg.packageName); 8448 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8449 } 8450 } 8451 } 8452 } 8453 } 8454 8455 final String pkgName = pkg.packageName; 8456 8457 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8458 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8459 pkg.applicationInfo.processName = fixProcessName( 8460 pkg.applicationInfo.packageName, 8461 pkg.applicationInfo.processName, 8462 pkg.applicationInfo.uid); 8463 8464 if (pkg != mPlatformPackage) { 8465 // Get all of our default paths setup 8466 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8467 } 8468 8469 final String path = scanFile.getPath(); 8470 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8471 8472 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8473 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8474 8475 // Some system apps still use directory structure for native libraries 8476 // in which case we might end up not detecting abi solely based on apk 8477 // structure. Try to detect abi based on directory structure. 8478 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8479 pkg.applicationInfo.primaryCpuAbi == null) { 8480 setBundledAppAbisAndRoots(pkg, pkgSetting); 8481 setNativeLibraryPaths(pkg); 8482 } 8483 8484 } else { 8485 if ((scanFlags & SCAN_MOVE) != 0) { 8486 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8487 // but we already have this packages package info in the PackageSetting. We just 8488 // use that and derive the native library path based on the new codepath. 8489 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8490 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8491 } 8492 8493 // Set native library paths again. For moves, the path will be updated based on the 8494 // ABIs we've determined above. For non-moves, the path will be updated based on the 8495 // ABIs we determined during compilation, but the path will depend on the final 8496 // package path (after the rename away from the stage path). 8497 setNativeLibraryPaths(pkg); 8498 } 8499 8500 // This is a special case for the "system" package, where the ABI is 8501 // dictated by the zygote configuration (and init.rc). We should keep track 8502 // of this ABI so that we can deal with "normal" applications that run under 8503 // the same UID correctly. 8504 if (mPlatformPackage == pkg) { 8505 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8506 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8507 } 8508 8509 // If there's a mismatch between the abi-override in the package setting 8510 // and the abiOverride specified for the install. Warn about this because we 8511 // would've already compiled the app without taking the package setting into 8512 // account. 8513 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8514 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8515 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8516 " for package " + pkg.packageName); 8517 } 8518 } 8519 8520 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8521 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8522 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8523 8524 // Copy the derived override back to the parsed package, so that we can 8525 // update the package settings accordingly. 8526 pkg.cpuAbiOverride = cpuAbiOverride; 8527 8528 if (DEBUG_ABI_SELECTION) { 8529 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8530 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8531 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8532 } 8533 8534 // Push the derived path down into PackageSettings so we know what to 8535 // clean up at uninstall time. 8536 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8537 8538 if (DEBUG_ABI_SELECTION) { 8539 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8540 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8541 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8542 } 8543 8544 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8545 // We don't do this here during boot because we can do it all 8546 // at once after scanning all existing packages. 8547 // 8548 // We also do this *before* we perform dexopt on this package, so that 8549 // we can avoid redundant dexopts, and also to make sure we've got the 8550 // code and package path correct. 8551 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8552 pkg, true /* boot complete */); 8553 } 8554 8555 if (mFactoryTest && pkg.requestedPermissions.contains( 8556 android.Manifest.permission.FACTORY_TEST)) { 8557 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8558 } 8559 8560 ArrayList<PackageParser.Package> clientLibPkgs = null; 8561 8562 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8563 if (nonMutatedPs != null) { 8564 synchronized (mPackages) { 8565 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8566 } 8567 } 8568 return pkg; 8569 } 8570 8571 // Only privileged apps and updated privileged apps can add child packages. 8572 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8573 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8574 throw new PackageManagerException("Only privileged apps and updated " 8575 + "privileged apps can add child packages. Ignoring package " 8576 + pkg.packageName); 8577 } 8578 final int childCount = pkg.childPackages.size(); 8579 for (int i = 0; i < childCount; i++) { 8580 PackageParser.Package childPkg = pkg.childPackages.get(i); 8581 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8582 childPkg.packageName)) { 8583 throw new PackageManagerException("Cannot override a child package of " 8584 + "another disabled system app. Ignoring package " + pkg.packageName); 8585 } 8586 } 8587 } 8588 8589 // writer 8590 synchronized (mPackages) { 8591 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8592 // Only system apps can add new shared libraries. 8593 if (pkg.libraryNames != null) { 8594 for (int i=0; i<pkg.libraryNames.size(); i++) { 8595 String name = pkg.libraryNames.get(i); 8596 boolean allowed = false; 8597 if (pkg.isUpdatedSystemApp()) { 8598 // New library entries can only be added through the 8599 // system image. This is important to get rid of a lot 8600 // of nasty edge cases: for example if we allowed a non- 8601 // system update of the app to add a library, then uninstalling 8602 // the update would make the library go away, and assumptions 8603 // we made such as through app install filtering would now 8604 // have allowed apps on the device which aren't compatible 8605 // with it. Better to just have the restriction here, be 8606 // conservative, and create many fewer cases that can negatively 8607 // impact the user experience. 8608 final PackageSetting sysPs = mSettings 8609 .getDisabledSystemPkgLPr(pkg.packageName); 8610 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8611 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8612 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8613 allowed = true; 8614 break; 8615 } 8616 } 8617 } 8618 } else { 8619 allowed = true; 8620 } 8621 if (allowed) { 8622 if (!mSharedLibraries.containsKey(name)) { 8623 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8624 } else if (!name.equals(pkg.packageName)) { 8625 Slog.w(TAG, "Package " + pkg.packageName + " library " 8626 + name + " already exists; skipping"); 8627 } 8628 } else { 8629 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8630 + name + " that is not declared on system image; skipping"); 8631 } 8632 } 8633 if ((scanFlags & SCAN_BOOTING) == 0) { 8634 // If we are not booting, we need to update any applications 8635 // that are clients of our shared library. If we are booting, 8636 // this will all be done once the scan is complete. 8637 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8638 } 8639 } 8640 } 8641 } 8642 8643 if ((scanFlags & SCAN_BOOTING) != 0) { 8644 // No apps can run during boot scan, so they don't need to be frozen 8645 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8646 // Caller asked to not kill app, so it's probably not frozen 8647 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8648 // Caller asked us to ignore frozen check for some reason; they 8649 // probably didn't know the package name 8650 } else { 8651 // We're doing major surgery on this package, so it better be frozen 8652 // right now to keep it from launching 8653 checkPackageFrozen(pkgName); 8654 } 8655 8656 // Also need to kill any apps that are dependent on the library. 8657 if (clientLibPkgs != null) { 8658 for (int i=0; i<clientLibPkgs.size(); i++) { 8659 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8660 killApplication(clientPkg.applicationInfo.packageName, 8661 clientPkg.applicationInfo.uid, "update lib"); 8662 } 8663 } 8664 8665 // Make sure we're not adding any bogus keyset info 8666 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8667 ksms.assertScannedPackageValid(pkg); 8668 8669 // writer 8670 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8671 8672 boolean createIdmapFailed = false; 8673 synchronized (mPackages) { 8674 // We don't expect installation to fail beyond this point 8675 8676 if (pkgSetting.pkg != null) { 8677 // Note that |user| might be null during the initial boot scan. If a codePath 8678 // for an app has changed during a boot scan, it's due to an app update that's 8679 // part of the system partition and marker changes must be applied to all users. 8680 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8681 (user != null) ? user : UserHandle.ALL); 8682 } 8683 8684 // Add the new setting to mSettings 8685 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8686 // Add the new setting to mPackages 8687 mPackages.put(pkg.applicationInfo.packageName, pkg); 8688 // Make sure we don't accidentally delete its data. 8689 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8690 while (iter.hasNext()) { 8691 PackageCleanItem item = iter.next(); 8692 if (pkgName.equals(item.packageName)) { 8693 iter.remove(); 8694 } 8695 } 8696 8697 // Take care of first install / last update times. 8698 if (currentTime != 0) { 8699 if (pkgSetting.firstInstallTime == 0) { 8700 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8701 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8702 pkgSetting.lastUpdateTime = currentTime; 8703 } 8704 } else if (pkgSetting.firstInstallTime == 0) { 8705 // We need *something*. Take time time stamp of the file. 8706 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8707 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8708 if (scanFileTime != pkgSetting.timeStamp) { 8709 // A package on the system image has changed; consider this 8710 // to be an update. 8711 pkgSetting.lastUpdateTime = scanFileTime; 8712 } 8713 } 8714 8715 // Add the package's KeySets to the global KeySetManagerService 8716 ksms.addScannedPackageLPw(pkg); 8717 8718 int N = pkg.providers.size(); 8719 StringBuilder r = null; 8720 int i; 8721 for (i=0; i<N; i++) { 8722 PackageParser.Provider p = pkg.providers.get(i); 8723 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8724 p.info.processName, pkg.applicationInfo.uid); 8725 mProviders.addProvider(p); 8726 p.syncable = p.info.isSyncable; 8727 if (p.info.authority != null) { 8728 String names[] = p.info.authority.split(";"); 8729 p.info.authority = null; 8730 for (int j = 0; j < names.length; j++) { 8731 if (j == 1 && p.syncable) { 8732 // We only want the first authority for a provider to possibly be 8733 // syncable, so if we already added this provider using a different 8734 // authority clear the syncable flag. We copy the provider before 8735 // changing it because the mProviders object contains a reference 8736 // to a provider that we don't want to change. 8737 // Only do this for the second authority since the resulting provider 8738 // object can be the same for all future authorities for this provider. 8739 p = new PackageParser.Provider(p); 8740 p.syncable = false; 8741 } 8742 if (!mProvidersByAuthority.containsKey(names[j])) { 8743 mProvidersByAuthority.put(names[j], p); 8744 if (p.info.authority == null) { 8745 p.info.authority = names[j]; 8746 } else { 8747 p.info.authority = p.info.authority + ";" + names[j]; 8748 } 8749 if (DEBUG_PACKAGE_SCANNING) { 8750 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8751 Log.d(TAG, "Registered content provider: " + names[j] 8752 + ", className = " + p.info.name + ", isSyncable = " 8753 + p.info.isSyncable); 8754 } 8755 } else { 8756 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8757 Slog.w(TAG, "Skipping provider name " + names[j] + 8758 " (in package " + pkg.applicationInfo.packageName + 8759 "): name already used by " 8760 + ((other != null && other.getComponentName() != null) 8761 ? other.getComponentName().getPackageName() : "?")); 8762 } 8763 } 8764 } 8765 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8766 if (r == null) { 8767 r = new StringBuilder(256); 8768 } else { 8769 r.append(' '); 8770 } 8771 r.append(p.info.name); 8772 } 8773 } 8774 if (r != null) { 8775 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8776 } 8777 8778 N = pkg.services.size(); 8779 r = null; 8780 for (i=0; i<N; i++) { 8781 PackageParser.Service s = pkg.services.get(i); 8782 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8783 s.info.processName, pkg.applicationInfo.uid); 8784 mServices.addService(s); 8785 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8786 if (r == null) { 8787 r = new StringBuilder(256); 8788 } else { 8789 r.append(' '); 8790 } 8791 r.append(s.info.name); 8792 } 8793 } 8794 if (r != null) { 8795 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8796 } 8797 8798 N = pkg.receivers.size(); 8799 r = null; 8800 for (i=0; i<N; i++) { 8801 PackageParser.Activity a = pkg.receivers.get(i); 8802 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8803 a.info.processName, pkg.applicationInfo.uid); 8804 mReceivers.addActivity(a, "receiver"); 8805 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8806 if (r == null) { 8807 r = new StringBuilder(256); 8808 } else { 8809 r.append(' '); 8810 } 8811 r.append(a.info.name); 8812 } 8813 } 8814 if (r != null) { 8815 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8816 } 8817 8818 N = pkg.activities.size(); 8819 r = null; 8820 for (i=0; i<N; i++) { 8821 PackageParser.Activity a = pkg.activities.get(i); 8822 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8823 a.info.processName, pkg.applicationInfo.uid); 8824 mActivities.addActivity(a, "activity"); 8825 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8826 if (r == null) { 8827 r = new StringBuilder(256); 8828 } else { 8829 r.append(' '); 8830 } 8831 r.append(a.info.name); 8832 } 8833 } 8834 if (r != null) { 8835 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8836 } 8837 8838 N = pkg.permissionGroups.size(); 8839 r = null; 8840 for (i=0; i<N; i++) { 8841 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8842 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8843 if (cur == null) { 8844 mPermissionGroups.put(pg.info.name, pg); 8845 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8846 if (r == null) { 8847 r = new StringBuilder(256); 8848 } else { 8849 r.append(' '); 8850 } 8851 r.append(pg.info.name); 8852 } 8853 } else { 8854 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8855 + pg.info.packageName + " ignored: original from " 8856 + cur.info.packageName); 8857 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8858 if (r == null) { 8859 r = new StringBuilder(256); 8860 } else { 8861 r.append(' '); 8862 } 8863 r.append("DUP:"); 8864 r.append(pg.info.name); 8865 } 8866 } 8867 } 8868 if (r != null) { 8869 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8870 } 8871 8872 N = pkg.permissions.size(); 8873 r = null; 8874 for (i=0; i<N; i++) { 8875 PackageParser.Permission p = pkg.permissions.get(i); 8876 8877 // Assume by default that we did not install this permission into the system. 8878 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8879 8880 // Now that permission groups have a special meaning, we ignore permission 8881 // groups for legacy apps to prevent unexpected behavior. In particular, 8882 // permissions for one app being granted to someone just becase they happen 8883 // to be in a group defined by another app (before this had no implications). 8884 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8885 p.group = mPermissionGroups.get(p.info.group); 8886 // Warn for a permission in an unknown group. 8887 if (p.info.group != null && p.group == null) { 8888 Slog.w(TAG, "Permission " + p.info.name + " from package " 8889 + p.info.packageName + " in an unknown group " + p.info.group); 8890 } 8891 } 8892 8893 ArrayMap<String, BasePermission> permissionMap = 8894 p.tree ? mSettings.mPermissionTrees 8895 : mSettings.mPermissions; 8896 BasePermission bp = permissionMap.get(p.info.name); 8897 8898 // Allow system apps to redefine non-system permissions 8899 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8900 final boolean currentOwnerIsSystem = (bp.perm != null 8901 && isSystemApp(bp.perm.owner)); 8902 if (isSystemApp(p.owner)) { 8903 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8904 // It's a built-in permission and no owner, take ownership now 8905 bp.packageSetting = pkgSetting; 8906 bp.perm = p; 8907 bp.uid = pkg.applicationInfo.uid; 8908 bp.sourcePackage = p.info.packageName; 8909 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8910 } else if (!currentOwnerIsSystem) { 8911 String msg = "New decl " + p.owner + " of permission " 8912 + p.info.name + " is system; overriding " + bp.sourcePackage; 8913 reportSettingsProblem(Log.WARN, msg); 8914 bp = null; 8915 } 8916 } 8917 } 8918 8919 if (bp == null) { 8920 bp = new BasePermission(p.info.name, p.info.packageName, 8921 BasePermission.TYPE_NORMAL); 8922 permissionMap.put(p.info.name, bp); 8923 } 8924 8925 if (bp.perm == null) { 8926 if (bp.sourcePackage == null 8927 || bp.sourcePackage.equals(p.info.packageName)) { 8928 BasePermission tree = findPermissionTreeLP(p.info.name); 8929 if (tree == null 8930 || tree.sourcePackage.equals(p.info.packageName)) { 8931 bp.packageSetting = pkgSetting; 8932 bp.perm = p; 8933 bp.uid = pkg.applicationInfo.uid; 8934 bp.sourcePackage = p.info.packageName; 8935 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8936 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8937 if (r == null) { 8938 r = new StringBuilder(256); 8939 } else { 8940 r.append(' '); 8941 } 8942 r.append(p.info.name); 8943 } 8944 } else { 8945 Slog.w(TAG, "Permission " + p.info.name + " from package " 8946 + p.info.packageName + " ignored: base tree " 8947 + tree.name + " is from package " 8948 + tree.sourcePackage); 8949 } 8950 } else { 8951 Slog.w(TAG, "Permission " + p.info.name + " from package " 8952 + p.info.packageName + " ignored: original from " 8953 + bp.sourcePackage); 8954 } 8955 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8956 if (r == null) { 8957 r = new StringBuilder(256); 8958 } else { 8959 r.append(' '); 8960 } 8961 r.append("DUP:"); 8962 r.append(p.info.name); 8963 } 8964 if (bp.perm == p) { 8965 bp.protectionLevel = p.info.protectionLevel; 8966 } 8967 } 8968 8969 if (r != null) { 8970 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8971 } 8972 8973 N = pkg.instrumentation.size(); 8974 r = null; 8975 for (i=0; i<N; i++) { 8976 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8977 a.info.packageName = pkg.applicationInfo.packageName; 8978 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8979 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8980 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8981 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8982 a.info.dataDir = pkg.applicationInfo.dataDir; 8983 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8984 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8985 8986 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8987 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8988 mInstrumentation.put(a.getComponentName(), a); 8989 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8990 if (r == null) { 8991 r = new StringBuilder(256); 8992 } else { 8993 r.append(' '); 8994 } 8995 r.append(a.info.name); 8996 } 8997 } 8998 if (r != null) { 8999 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9000 } 9001 9002 if (pkg.protectedBroadcasts != null) { 9003 N = pkg.protectedBroadcasts.size(); 9004 for (i=0; i<N; i++) { 9005 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9006 } 9007 } 9008 9009 pkgSetting.setTimeStamp(scanFileTime); 9010 9011 // Create idmap files for pairs of (packages, overlay packages). 9012 // Note: "android", ie framework-res.apk, is handled by native layers. 9013 if (pkg.mOverlayTarget != null) { 9014 // This is an overlay package. 9015 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9016 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9017 mOverlays.put(pkg.mOverlayTarget, 9018 new ArrayMap<String, PackageParser.Package>()); 9019 } 9020 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9021 map.put(pkg.packageName, pkg); 9022 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9023 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9024 createIdmapFailed = true; 9025 } 9026 } 9027 } else if (mOverlays.containsKey(pkg.packageName) && 9028 !pkg.packageName.equals("android")) { 9029 // This is a regular package, with one or more known overlay packages. 9030 createIdmapsForPackageLI(pkg); 9031 } 9032 } 9033 9034 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9035 9036 if (createIdmapFailed) { 9037 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9038 "scanPackageLI failed to createIdmap"); 9039 } 9040 return pkg; 9041 } 9042 9043 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9044 PackageParser.Package update, UserHandle user) { 9045 if (existing.applicationInfo == null || update.applicationInfo == null) { 9046 // This isn't due to an app installation. 9047 return; 9048 } 9049 9050 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9051 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9052 9053 // The codePath hasn't changed, so there's nothing for us to do. 9054 if (Objects.equals(oldCodePath, newCodePath)) { 9055 return; 9056 } 9057 9058 File canonicalNewCodePath; 9059 try { 9060 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9061 } catch (IOException e) { 9062 Slog.w(TAG, "Failed to get canonical path.", e); 9063 return; 9064 } 9065 9066 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9067 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9068 // that the last component of the path (i.e, the name) doesn't need canonicalization 9069 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9070 // but may change in the future. Hopefully this function won't exist at that point. 9071 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9072 oldCodePath.getName()); 9073 9074 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9075 // with "@". 9076 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9077 if (!oldMarkerPrefix.endsWith("@")) { 9078 oldMarkerPrefix += "@"; 9079 } 9080 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9081 if (!newMarkerPrefix.endsWith("@")) { 9082 newMarkerPrefix += "@"; 9083 } 9084 9085 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9086 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9087 for (String updatedPath : updatedPaths) { 9088 String updatedPathName = new File(updatedPath).getName(); 9089 markerSuffixes.add(updatedPathName.replace('/', '@')); 9090 } 9091 9092 for (int userId : resolveUserIds(user.getIdentifier())) { 9093 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9094 9095 for (String markerSuffix : markerSuffixes) { 9096 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9097 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9098 if (oldForeignUseMark.exists()) { 9099 try { 9100 Os.rename(oldForeignUseMark.getAbsolutePath(), 9101 newForeignUseMark.getAbsolutePath()); 9102 } catch (ErrnoException e) { 9103 Slog.w(TAG, "Failed to rename foreign use marker", e); 9104 oldForeignUseMark.delete(); 9105 } 9106 } 9107 } 9108 } 9109 } 9110 9111 /** 9112 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9113 * is derived purely on the basis of the contents of {@code scanFile} and 9114 * {@code cpuAbiOverride}. 9115 * 9116 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9117 */ 9118 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9119 String cpuAbiOverride, boolean extractLibs) 9120 throws PackageManagerException { 9121 // TODO: We can probably be smarter about this stuff. For installed apps, 9122 // we can calculate this information at install time once and for all. For 9123 // system apps, we can probably assume that this information doesn't change 9124 // after the first boot scan. As things stand, we do lots of unnecessary work. 9125 9126 // Give ourselves some initial paths; we'll come back for another 9127 // pass once we've determined ABI below. 9128 setNativeLibraryPaths(pkg); 9129 9130 // We would never need to extract libs for forward-locked and external packages, 9131 // since the container service will do it for us. We shouldn't attempt to 9132 // extract libs from system app when it was not updated. 9133 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9134 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9135 extractLibs = false; 9136 } 9137 9138 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9139 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9140 9141 NativeLibraryHelper.Handle handle = null; 9142 try { 9143 handle = NativeLibraryHelper.Handle.create(pkg); 9144 // TODO(multiArch): This can be null for apps that didn't go through the 9145 // usual installation process. We can calculate it again, like we 9146 // do during install time. 9147 // 9148 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9149 // unnecessary. 9150 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9151 9152 // Null out the abis so that they can be recalculated. 9153 pkg.applicationInfo.primaryCpuAbi = null; 9154 pkg.applicationInfo.secondaryCpuAbi = null; 9155 if (isMultiArch(pkg.applicationInfo)) { 9156 // Warn if we've set an abiOverride for multi-lib packages.. 9157 // By definition, we need to copy both 32 and 64 bit libraries for 9158 // such packages. 9159 if (pkg.cpuAbiOverride != null 9160 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9161 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9162 } 9163 9164 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9165 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9166 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9167 if (extractLibs) { 9168 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9169 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9170 useIsaSpecificSubdirs); 9171 } else { 9172 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9173 } 9174 } 9175 9176 maybeThrowExceptionForMultiArchCopy( 9177 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9178 9179 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9180 if (extractLibs) { 9181 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9182 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9183 useIsaSpecificSubdirs); 9184 } else { 9185 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9186 } 9187 } 9188 9189 maybeThrowExceptionForMultiArchCopy( 9190 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9191 9192 if (abi64 >= 0) { 9193 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9194 } 9195 9196 if (abi32 >= 0) { 9197 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9198 if (abi64 >= 0) { 9199 if (pkg.use32bitAbi) { 9200 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9201 pkg.applicationInfo.primaryCpuAbi = abi; 9202 } else { 9203 pkg.applicationInfo.secondaryCpuAbi = abi; 9204 } 9205 } else { 9206 pkg.applicationInfo.primaryCpuAbi = abi; 9207 } 9208 } 9209 9210 } else { 9211 String[] abiList = (cpuAbiOverride != null) ? 9212 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9213 9214 // Enable gross and lame hacks for apps that are built with old 9215 // SDK tools. We must scan their APKs for renderscript bitcode and 9216 // not launch them if it's present. Don't bother checking on devices 9217 // that don't have 64 bit support. 9218 boolean needsRenderScriptOverride = false; 9219 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9220 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9221 abiList = Build.SUPPORTED_32_BIT_ABIS; 9222 needsRenderScriptOverride = true; 9223 } 9224 9225 final int copyRet; 9226 if (extractLibs) { 9227 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9228 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9229 } else { 9230 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9231 } 9232 9233 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9234 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9235 "Error unpackaging native libs for app, errorCode=" + copyRet); 9236 } 9237 9238 if (copyRet >= 0) { 9239 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9240 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9241 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9242 } else if (needsRenderScriptOverride) { 9243 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9244 } 9245 } 9246 } catch (IOException ioe) { 9247 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9248 } finally { 9249 IoUtils.closeQuietly(handle); 9250 } 9251 9252 // Now that we've calculated the ABIs and determined if it's an internal app, 9253 // we will go ahead and populate the nativeLibraryPath. 9254 setNativeLibraryPaths(pkg); 9255 } 9256 9257 /** 9258 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9259 * i.e, so that all packages can be run inside a single process if required. 9260 * 9261 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9262 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9263 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9264 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9265 * updating a package that belongs to a shared user. 9266 * 9267 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9268 * adds unnecessary complexity. 9269 */ 9270 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9271 PackageParser.Package scannedPackage, boolean bootComplete) { 9272 String requiredInstructionSet = null; 9273 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9274 requiredInstructionSet = VMRuntime.getInstructionSet( 9275 scannedPackage.applicationInfo.primaryCpuAbi); 9276 } 9277 9278 PackageSetting requirer = null; 9279 for (PackageSetting ps : packagesForUser) { 9280 // If packagesForUser contains scannedPackage, we skip it. This will happen 9281 // when scannedPackage is an update of an existing package. Without this check, 9282 // we will never be able to change the ABI of any package belonging to a shared 9283 // user, even if it's compatible with other packages. 9284 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9285 if (ps.primaryCpuAbiString == null) { 9286 continue; 9287 } 9288 9289 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9290 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9291 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9292 // this but there's not much we can do. 9293 String errorMessage = "Instruction set mismatch, " 9294 + ((requirer == null) ? "[caller]" : requirer) 9295 + " requires " + requiredInstructionSet + " whereas " + ps 9296 + " requires " + instructionSet; 9297 Slog.w(TAG, errorMessage); 9298 } 9299 9300 if (requiredInstructionSet == null) { 9301 requiredInstructionSet = instructionSet; 9302 requirer = ps; 9303 } 9304 } 9305 } 9306 9307 if (requiredInstructionSet != null) { 9308 String adjustedAbi; 9309 if (requirer != null) { 9310 // requirer != null implies that either scannedPackage was null or that scannedPackage 9311 // did not require an ABI, in which case we have to adjust scannedPackage to match 9312 // the ABI of the set (which is the same as requirer's ABI) 9313 adjustedAbi = requirer.primaryCpuAbiString; 9314 if (scannedPackage != null) { 9315 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9316 } 9317 } else { 9318 // requirer == null implies that we're updating all ABIs in the set to 9319 // match scannedPackage. 9320 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9321 } 9322 9323 for (PackageSetting ps : packagesForUser) { 9324 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9325 if (ps.primaryCpuAbiString != null) { 9326 continue; 9327 } 9328 9329 ps.primaryCpuAbiString = adjustedAbi; 9330 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9331 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9332 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9333 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9334 + " (requirer=" 9335 + (requirer == null ? "null" : requirer.pkg.packageName) 9336 + ", scannedPackage=" 9337 + (scannedPackage != null ? scannedPackage.packageName : "null") 9338 + ")"); 9339 try { 9340 mInstaller.rmdex(ps.codePathString, 9341 getDexCodeInstructionSet(getPreferredInstructionSet())); 9342 } catch (InstallerException ignored) { 9343 } 9344 } 9345 } 9346 } 9347 } 9348 } 9349 9350 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9351 synchronized (mPackages) { 9352 mResolverReplaced = true; 9353 // Set up information for custom user intent resolution activity. 9354 mResolveActivity.applicationInfo = pkg.applicationInfo; 9355 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9356 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9357 mResolveActivity.processName = pkg.applicationInfo.packageName; 9358 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9359 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9360 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9361 mResolveActivity.theme = 0; 9362 mResolveActivity.exported = true; 9363 mResolveActivity.enabled = true; 9364 mResolveInfo.activityInfo = mResolveActivity; 9365 mResolveInfo.priority = 0; 9366 mResolveInfo.preferredOrder = 0; 9367 mResolveInfo.match = 0; 9368 mResolveComponentName = mCustomResolverComponentName; 9369 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9370 mResolveComponentName); 9371 } 9372 } 9373 9374 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9375 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9376 9377 // Set up information for ephemeral installer activity 9378 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9379 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9380 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9381 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9382 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9383 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9384 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9385 mEphemeralInstallerActivity.theme = 0; 9386 mEphemeralInstallerActivity.exported = true; 9387 mEphemeralInstallerActivity.enabled = true; 9388 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9389 mEphemeralInstallerInfo.priority = 0; 9390 mEphemeralInstallerInfo.preferredOrder = 0; 9391 mEphemeralInstallerInfo.match = 0; 9392 9393 if (DEBUG_EPHEMERAL) { 9394 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9395 } 9396 } 9397 9398 private static String calculateBundledApkRoot(final String codePathString) { 9399 final File codePath = new File(codePathString); 9400 final File codeRoot; 9401 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9402 codeRoot = Environment.getRootDirectory(); 9403 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9404 codeRoot = Environment.getOemDirectory(); 9405 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9406 codeRoot = Environment.getVendorDirectory(); 9407 } else { 9408 // Unrecognized code path; take its top real segment as the apk root: 9409 // e.g. /something/app/blah.apk => /something 9410 try { 9411 File f = codePath.getCanonicalFile(); 9412 File parent = f.getParentFile(); // non-null because codePath is a file 9413 File tmp; 9414 while ((tmp = parent.getParentFile()) != null) { 9415 f = parent; 9416 parent = tmp; 9417 } 9418 codeRoot = f; 9419 Slog.w(TAG, "Unrecognized code path " 9420 + codePath + " - using " + codeRoot); 9421 } catch (IOException e) { 9422 // Can't canonicalize the code path -- shenanigans? 9423 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9424 return Environment.getRootDirectory().getPath(); 9425 } 9426 } 9427 return codeRoot.getPath(); 9428 } 9429 9430 /** 9431 * Derive and set the location of native libraries for the given package, 9432 * which varies depending on where and how the package was installed. 9433 */ 9434 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9435 final ApplicationInfo info = pkg.applicationInfo; 9436 final String codePath = pkg.codePath; 9437 final File codeFile = new File(codePath); 9438 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9439 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9440 9441 info.nativeLibraryRootDir = null; 9442 info.nativeLibraryRootRequiresIsa = false; 9443 info.nativeLibraryDir = null; 9444 info.secondaryNativeLibraryDir = null; 9445 9446 if (isApkFile(codeFile)) { 9447 // Monolithic install 9448 if (bundledApp) { 9449 // If "/system/lib64/apkname" exists, assume that is the per-package 9450 // native library directory to use; otherwise use "/system/lib/apkname". 9451 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9452 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9453 getPrimaryInstructionSet(info)); 9454 9455 // This is a bundled system app so choose the path based on the ABI. 9456 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9457 // is just the default path. 9458 final String apkName = deriveCodePathName(codePath); 9459 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9460 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9461 apkName).getAbsolutePath(); 9462 9463 if (info.secondaryCpuAbi != null) { 9464 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9465 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9466 secondaryLibDir, apkName).getAbsolutePath(); 9467 } 9468 } else if (asecApp) { 9469 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9470 .getAbsolutePath(); 9471 } else { 9472 final String apkName = deriveCodePathName(codePath); 9473 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9474 .getAbsolutePath(); 9475 } 9476 9477 info.nativeLibraryRootRequiresIsa = false; 9478 info.nativeLibraryDir = info.nativeLibraryRootDir; 9479 } else { 9480 // Cluster install 9481 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9482 info.nativeLibraryRootRequiresIsa = true; 9483 9484 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9485 getPrimaryInstructionSet(info)).getAbsolutePath(); 9486 9487 if (info.secondaryCpuAbi != null) { 9488 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9489 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9490 } 9491 } 9492 } 9493 9494 /** 9495 * Calculate the abis and roots for a bundled app. These can uniquely 9496 * be determined from the contents of the system partition, i.e whether 9497 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9498 * of this information, and instead assume that the system was built 9499 * sensibly. 9500 */ 9501 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9502 PackageSetting pkgSetting) { 9503 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9504 9505 // If "/system/lib64/apkname" exists, assume that is the per-package 9506 // native library directory to use; otherwise use "/system/lib/apkname". 9507 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9508 setBundledAppAbi(pkg, apkRoot, apkName); 9509 // pkgSetting might be null during rescan following uninstall of updates 9510 // to a bundled app, so accommodate that possibility. The settings in 9511 // that case will be established later from the parsed package. 9512 // 9513 // If the settings aren't null, sync them up with what we've just derived. 9514 // note that apkRoot isn't stored in the package settings. 9515 if (pkgSetting != null) { 9516 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9517 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9518 } 9519 } 9520 9521 /** 9522 * Deduces the ABI of a bundled app and sets the relevant fields on the 9523 * parsed pkg object. 9524 * 9525 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9526 * under which system libraries are installed. 9527 * @param apkName the name of the installed package. 9528 */ 9529 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9530 final File codeFile = new File(pkg.codePath); 9531 9532 final boolean has64BitLibs; 9533 final boolean has32BitLibs; 9534 if (isApkFile(codeFile)) { 9535 // Monolithic install 9536 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9537 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9538 } else { 9539 // Cluster install 9540 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9541 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9542 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9543 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9544 has64BitLibs = (new File(rootDir, isa)).exists(); 9545 } else { 9546 has64BitLibs = false; 9547 } 9548 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9549 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9550 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9551 has32BitLibs = (new File(rootDir, isa)).exists(); 9552 } else { 9553 has32BitLibs = false; 9554 } 9555 } 9556 9557 if (has64BitLibs && !has32BitLibs) { 9558 // The package has 64 bit libs, but not 32 bit libs. Its primary 9559 // ABI should be 64 bit. We can safely assume here that the bundled 9560 // native libraries correspond to the most preferred ABI in the list. 9561 9562 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9563 pkg.applicationInfo.secondaryCpuAbi = null; 9564 } else if (has32BitLibs && !has64BitLibs) { 9565 // The package has 32 bit libs but not 64 bit libs. Its primary 9566 // ABI should be 32 bit. 9567 9568 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9569 pkg.applicationInfo.secondaryCpuAbi = null; 9570 } else if (has32BitLibs && has64BitLibs) { 9571 // The application has both 64 and 32 bit bundled libraries. We check 9572 // here that the app declares multiArch support, and warn if it doesn't. 9573 // 9574 // We will be lenient here and record both ABIs. The primary will be the 9575 // ABI that's higher on the list, i.e, a device that's configured to prefer 9576 // 64 bit apps will see a 64 bit primary ABI, 9577 9578 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9579 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9580 } 9581 9582 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9583 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9584 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9585 } else { 9586 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9587 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9588 } 9589 } else { 9590 pkg.applicationInfo.primaryCpuAbi = null; 9591 pkg.applicationInfo.secondaryCpuAbi = null; 9592 } 9593 } 9594 9595 private void killApplication(String pkgName, int appId, String reason) { 9596 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9597 } 9598 9599 private void killApplication(String pkgName, int appId, int userId, String reason) { 9600 // Request the ActivityManager to kill the process(only for existing packages) 9601 // so that we do not end up in a confused state while the user is still using the older 9602 // version of the application while the new one gets installed. 9603 final long token = Binder.clearCallingIdentity(); 9604 try { 9605 IActivityManager am = ActivityManagerNative.getDefault(); 9606 if (am != null) { 9607 try { 9608 am.killApplication(pkgName, appId, userId, reason); 9609 } catch (RemoteException e) { 9610 } 9611 } 9612 } finally { 9613 Binder.restoreCallingIdentity(token); 9614 } 9615 } 9616 9617 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9618 // Remove the parent package setting 9619 PackageSetting ps = (PackageSetting) pkg.mExtras; 9620 if (ps != null) { 9621 removePackageLI(ps, chatty); 9622 } 9623 // Remove the child package setting 9624 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9625 for (int i = 0; i < childCount; i++) { 9626 PackageParser.Package childPkg = pkg.childPackages.get(i); 9627 ps = (PackageSetting) childPkg.mExtras; 9628 if (ps != null) { 9629 removePackageLI(ps, chatty); 9630 } 9631 } 9632 } 9633 9634 void removePackageLI(PackageSetting ps, boolean chatty) { 9635 if (DEBUG_INSTALL) { 9636 if (chatty) 9637 Log.d(TAG, "Removing package " + ps.name); 9638 } 9639 9640 // writer 9641 synchronized (mPackages) { 9642 mPackages.remove(ps.name); 9643 final PackageParser.Package pkg = ps.pkg; 9644 if (pkg != null) { 9645 cleanPackageDataStructuresLILPw(pkg, chatty); 9646 } 9647 } 9648 } 9649 9650 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9651 if (DEBUG_INSTALL) { 9652 if (chatty) 9653 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9654 } 9655 9656 // writer 9657 synchronized (mPackages) { 9658 // Remove the parent package 9659 mPackages.remove(pkg.applicationInfo.packageName); 9660 cleanPackageDataStructuresLILPw(pkg, chatty); 9661 9662 // Remove the child packages 9663 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9664 for (int i = 0; i < childCount; i++) { 9665 PackageParser.Package childPkg = pkg.childPackages.get(i); 9666 mPackages.remove(childPkg.applicationInfo.packageName); 9667 cleanPackageDataStructuresLILPw(childPkg, chatty); 9668 } 9669 } 9670 } 9671 9672 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9673 int N = pkg.providers.size(); 9674 StringBuilder r = null; 9675 int i; 9676 for (i=0; i<N; i++) { 9677 PackageParser.Provider p = pkg.providers.get(i); 9678 mProviders.removeProvider(p); 9679 if (p.info.authority == null) { 9680 9681 /* There was another ContentProvider with this authority when 9682 * this app was installed so this authority is null, 9683 * Ignore it as we don't have to unregister the provider. 9684 */ 9685 continue; 9686 } 9687 String names[] = p.info.authority.split(";"); 9688 for (int j = 0; j < names.length; j++) { 9689 if (mProvidersByAuthority.get(names[j]) == p) { 9690 mProvidersByAuthority.remove(names[j]); 9691 if (DEBUG_REMOVE) { 9692 if (chatty) 9693 Log.d(TAG, "Unregistered content provider: " + names[j] 9694 + ", className = " + p.info.name + ", isSyncable = " 9695 + p.info.isSyncable); 9696 } 9697 } 9698 } 9699 if (DEBUG_REMOVE && chatty) { 9700 if (r == null) { 9701 r = new StringBuilder(256); 9702 } else { 9703 r.append(' '); 9704 } 9705 r.append(p.info.name); 9706 } 9707 } 9708 if (r != null) { 9709 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9710 } 9711 9712 N = pkg.services.size(); 9713 r = null; 9714 for (i=0; i<N; i++) { 9715 PackageParser.Service s = pkg.services.get(i); 9716 mServices.removeService(s); 9717 if (chatty) { 9718 if (r == null) { 9719 r = new StringBuilder(256); 9720 } else { 9721 r.append(' '); 9722 } 9723 r.append(s.info.name); 9724 } 9725 } 9726 if (r != null) { 9727 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9728 } 9729 9730 N = pkg.receivers.size(); 9731 r = null; 9732 for (i=0; i<N; i++) { 9733 PackageParser.Activity a = pkg.receivers.get(i); 9734 mReceivers.removeActivity(a, "receiver"); 9735 if (DEBUG_REMOVE && chatty) { 9736 if (r == null) { 9737 r = new StringBuilder(256); 9738 } else { 9739 r.append(' '); 9740 } 9741 r.append(a.info.name); 9742 } 9743 } 9744 if (r != null) { 9745 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9746 } 9747 9748 N = pkg.activities.size(); 9749 r = null; 9750 for (i=0; i<N; i++) { 9751 PackageParser.Activity a = pkg.activities.get(i); 9752 mActivities.removeActivity(a, "activity"); 9753 if (DEBUG_REMOVE && chatty) { 9754 if (r == null) { 9755 r = new StringBuilder(256); 9756 } else { 9757 r.append(' '); 9758 } 9759 r.append(a.info.name); 9760 } 9761 } 9762 if (r != null) { 9763 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9764 } 9765 9766 N = pkg.permissions.size(); 9767 r = null; 9768 for (i=0; i<N; i++) { 9769 PackageParser.Permission p = pkg.permissions.get(i); 9770 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9771 if (bp == null) { 9772 bp = mSettings.mPermissionTrees.get(p.info.name); 9773 } 9774 if (bp != null && bp.perm == p) { 9775 bp.perm = null; 9776 if (DEBUG_REMOVE && chatty) { 9777 if (r == null) { 9778 r = new StringBuilder(256); 9779 } else { 9780 r.append(' '); 9781 } 9782 r.append(p.info.name); 9783 } 9784 } 9785 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9786 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9787 if (appOpPkgs != null) { 9788 appOpPkgs.remove(pkg.packageName); 9789 } 9790 } 9791 } 9792 if (r != null) { 9793 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9794 } 9795 9796 N = pkg.requestedPermissions.size(); 9797 r = null; 9798 for (i=0; i<N; i++) { 9799 String perm = pkg.requestedPermissions.get(i); 9800 BasePermission bp = mSettings.mPermissions.get(perm); 9801 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9802 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9803 if (appOpPkgs != null) { 9804 appOpPkgs.remove(pkg.packageName); 9805 if (appOpPkgs.isEmpty()) { 9806 mAppOpPermissionPackages.remove(perm); 9807 } 9808 } 9809 } 9810 } 9811 if (r != null) { 9812 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9813 } 9814 9815 N = pkg.instrumentation.size(); 9816 r = null; 9817 for (i=0; i<N; i++) { 9818 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9819 mInstrumentation.remove(a.getComponentName()); 9820 if (DEBUG_REMOVE && chatty) { 9821 if (r == null) { 9822 r = new StringBuilder(256); 9823 } else { 9824 r.append(' '); 9825 } 9826 r.append(a.info.name); 9827 } 9828 } 9829 if (r != null) { 9830 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9831 } 9832 9833 r = null; 9834 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9835 // Only system apps can hold shared libraries. 9836 if (pkg.libraryNames != null) { 9837 for (i=0; i<pkg.libraryNames.size(); i++) { 9838 String name = pkg.libraryNames.get(i); 9839 SharedLibraryEntry cur = mSharedLibraries.get(name); 9840 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9841 mSharedLibraries.remove(name); 9842 if (DEBUG_REMOVE && chatty) { 9843 if (r == null) { 9844 r = new StringBuilder(256); 9845 } else { 9846 r.append(' '); 9847 } 9848 r.append(name); 9849 } 9850 } 9851 } 9852 } 9853 } 9854 if (r != null) { 9855 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9856 } 9857 } 9858 9859 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9860 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9861 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9862 return true; 9863 } 9864 } 9865 return false; 9866 } 9867 9868 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9869 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9870 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9871 9872 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9873 // Update the parent permissions 9874 updatePermissionsLPw(pkg.packageName, pkg, flags); 9875 // Update the child permissions 9876 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9877 for (int i = 0; i < childCount; i++) { 9878 PackageParser.Package childPkg = pkg.childPackages.get(i); 9879 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9880 } 9881 } 9882 9883 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9884 int flags) { 9885 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9886 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9887 } 9888 9889 private void updatePermissionsLPw(String changingPkg, 9890 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9891 // Make sure there are no dangling permission trees. 9892 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9893 while (it.hasNext()) { 9894 final BasePermission bp = it.next(); 9895 if (bp.packageSetting == null) { 9896 // We may not yet have parsed the package, so just see if 9897 // we still know about its settings. 9898 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9899 } 9900 if (bp.packageSetting == null) { 9901 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9902 + " from package " + bp.sourcePackage); 9903 it.remove(); 9904 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9905 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9906 Slog.i(TAG, "Removing old permission tree: " + bp.name 9907 + " from package " + bp.sourcePackage); 9908 flags |= UPDATE_PERMISSIONS_ALL; 9909 it.remove(); 9910 } 9911 } 9912 } 9913 9914 // Make sure all dynamic permissions have been assigned to a package, 9915 // and make sure there are no dangling permissions. 9916 it = mSettings.mPermissions.values().iterator(); 9917 while (it.hasNext()) { 9918 final BasePermission bp = it.next(); 9919 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9920 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9921 + bp.name + " pkg=" + bp.sourcePackage 9922 + " info=" + bp.pendingInfo); 9923 if (bp.packageSetting == null && bp.pendingInfo != null) { 9924 final BasePermission tree = findPermissionTreeLP(bp.name); 9925 if (tree != null && tree.perm != null) { 9926 bp.packageSetting = tree.packageSetting; 9927 bp.perm = new PackageParser.Permission(tree.perm.owner, 9928 new PermissionInfo(bp.pendingInfo)); 9929 bp.perm.info.packageName = tree.perm.info.packageName; 9930 bp.perm.info.name = bp.name; 9931 bp.uid = tree.uid; 9932 } 9933 } 9934 } 9935 if (bp.packageSetting == null) { 9936 // We may not yet have parsed the package, so just see if 9937 // we still know about its settings. 9938 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9939 } 9940 if (bp.packageSetting == null) { 9941 Slog.w(TAG, "Removing dangling permission: " + bp.name 9942 + " from package " + bp.sourcePackage); 9943 it.remove(); 9944 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9945 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9946 Slog.i(TAG, "Removing old permission: " + bp.name 9947 + " from package " + bp.sourcePackage); 9948 flags |= UPDATE_PERMISSIONS_ALL; 9949 it.remove(); 9950 } 9951 } 9952 } 9953 9954 // Now update the permissions for all packages, in particular 9955 // replace the granted permissions of the system packages. 9956 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9957 for (PackageParser.Package pkg : mPackages.values()) { 9958 if (pkg != pkgInfo) { 9959 // Only replace for packages on requested volume 9960 final String volumeUuid = getVolumeUuidForPackage(pkg); 9961 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9962 && Objects.equals(replaceVolumeUuid, volumeUuid); 9963 grantPermissionsLPw(pkg, replace, changingPkg); 9964 } 9965 } 9966 } 9967 9968 if (pkgInfo != null) { 9969 // Only replace for packages on requested volume 9970 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9971 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9972 && Objects.equals(replaceVolumeUuid, volumeUuid); 9973 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9974 } 9975 } 9976 9977 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9978 String packageOfInterest) { 9979 // IMPORTANT: There are two types of permissions: install and runtime. 9980 // Install time permissions are granted when the app is installed to 9981 // all device users and users added in the future. Runtime permissions 9982 // are granted at runtime explicitly to specific users. Normal and signature 9983 // protected permissions are install time permissions. Dangerous permissions 9984 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9985 // otherwise they are runtime permissions. This function does not manage 9986 // runtime permissions except for the case an app targeting Lollipop MR1 9987 // being upgraded to target a newer SDK, in which case dangerous permissions 9988 // are transformed from install time to runtime ones. 9989 9990 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9991 if (ps == null) { 9992 return; 9993 } 9994 9995 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9996 9997 PermissionsState permissionsState = ps.getPermissionsState(); 9998 PermissionsState origPermissions = permissionsState; 9999 10000 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10001 10002 boolean runtimePermissionsRevoked = false; 10003 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10004 10005 boolean changedInstallPermission = false; 10006 10007 if (replace) { 10008 ps.installPermissionsFixed = false; 10009 if (!ps.isSharedUser()) { 10010 origPermissions = new PermissionsState(permissionsState); 10011 permissionsState.reset(); 10012 } else { 10013 // We need to know only about runtime permission changes since the 10014 // calling code always writes the install permissions state but 10015 // the runtime ones are written only if changed. The only cases of 10016 // changed runtime permissions here are promotion of an install to 10017 // runtime and revocation of a runtime from a shared user. 10018 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10019 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10020 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10021 runtimePermissionsRevoked = true; 10022 } 10023 } 10024 } 10025 10026 permissionsState.setGlobalGids(mGlobalGids); 10027 10028 final int N = pkg.requestedPermissions.size(); 10029 for (int i=0; i<N; i++) { 10030 final String name = pkg.requestedPermissions.get(i); 10031 final BasePermission bp = mSettings.mPermissions.get(name); 10032 10033 if (DEBUG_INSTALL) { 10034 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10035 } 10036 10037 if (bp == null || bp.packageSetting == null) { 10038 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10039 Slog.w(TAG, "Unknown permission " + name 10040 + " in package " + pkg.packageName); 10041 } 10042 continue; 10043 } 10044 10045 final String perm = bp.name; 10046 boolean allowedSig = false; 10047 int grant = GRANT_DENIED; 10048 10049 // Keep track of app op permissions. 10050 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10051 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10052 if (pkgs == null) { 10053 pkgs = new ArraySet<>(); 10054 mAppOpPermissionPackages.put(bp.name, pkgs); 10055 } 10056 pkgs.add(pkg.packageName); 10057 } 10058 10059 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10060 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10061 >= Build.VERSION_CODES.M; 10062 switch (level) { 10063 case PermissionInfo.PROTECTION_NORMAL: { 10064 // For all apps normal permissions are install time ones. 10065 grant = GRANT_INSTALL; 10066 } break; 10067 10068 case PermissionInfo.PROTECTION_DANGEROUS: { 10069 // If a permission review is required for legacy apps we represent 10070 // their permissions as always granted runtime ones since we need 10071 // to keep the review required permission flag per user while an 10072 // install permission's state is shared across all users. 10073 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10074 // For legacy apps dangerous permissions are install time ones. 10075 grant = GRANT_INSTALL; 10076 } else if (origPermissions.hasInstallPermission(bp.name)) { 10077 // For legacy apps that became modern, install becomes runtime. 10078 grant = GRANT_UPGRADE; 10079 } else if (mPromoteSystemApps 10080 && isSystemApp(ps) 10081 && mExistingSystemPackages.contains(ps.name)) { 10082 // For legacy system apps, install becomes runtime. 10083 // We cannot check hasInstallPermission() for system apps since those 10084 // permissions were granted implicitly and not persisted pre-M. 10085 grant = GRANT_UPGRADE; 10086 } else { 10087 // For modern apps keep runtime permissions unchanged. 10088 grant = GRANT_RUNTIME; 10089 } 10090 } break; 10091 10092 case PermissionInfo.PROTECTION_SIGNATURE: { 10093 // For all apps signature permissions are install time ones. 10094 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10095 if (allowedSig) { 10096 grant = GRANT_INSTALL; 10097 } 10098 } break; 10099 } 10100 10101 if (DEBUG_INSTALL) { 10102 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10103 } 10104 10105 if (grant != GRANT_DENIED) { 10106 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10107 // If this is an existing, non-system package, then 10108 // we can't add any new permissions to it. 10109 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10110 // Except... if this is a permission that was added 10111 // to the platform (note: need to only do this when 10112 // updating the platform). 10113 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10114 grant = GRANT_DENIED; 10115 } 10116 } 10117 } 10118 10119 switch (grant) { 10120 case GRANT_INSTALL: { 10121 // Revoke this as runtime permission to handle the case of 10122 // a runtime permission being downgraded to an install one. 10123 // Also in permission review mode we keep dangerous permissions 10124 // for legacy apps 10125 for (int userId : UserManagerService.getInstance().getUserIds()) { 10126 if (origPermissions.getRuntimePermissionState( 10127 bp.name, userId) != null) { 10128 // Revoke the runtime permission and clear the flags. 10129 origPermissions.revokeRuntimePermission(bp, userId); 10130 origPermissions.updatePermissionFlags(bp, userId, 10131 PackageManager.MASK_PERMISSION_FLAGS, 0); 10132 // If we revoked a permission permission, we have to write. 10133 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10134 changedRuntimePermissionUserIds, userId); 10135 } 10136 } 10137 // Grant an install permission. 10138 if (permissionsState.grantInstallPermission(bp) != 10139 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10140 changedInstallPermission = true; 10141 } 10142 } break; 10143 10144 case GRANT_RUNTIME: { 10145 // Grant previously granted runtime permissions. 10146 for (int userId : UserManagerService.getInstance().getUserIds()) { 10147 PermissionState permissionState = origPermissions 10148 .getRuntimePermissionState(bp.name, userId); 10149 int flags = permissionState != null 10150 ? permissionState.getFlags() : 0; 10151 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10152 if (permissionsState.grantRuntimePermission(bp, userId) == 10153 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10154 // If we cannot put the permission as it was, we have to write. 10155 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10156 changedRuntimePermissionUserIds, userId); 10157 } 10158 // If the app supports runtime permissions no need for a review. 10159 if (Build.PERMISSIONS_REVIEW_REQUIRED 10160 && appSupportsRuntimePermissions 10161 && (flags & PackageManager 10162 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10163 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10164 // Since we changed the flags, we have to write. 10165 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10166 changedRuntimePermissionUserIds, userId); 10167 } 10168 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10169 && !appSupportsRuntimePermissions) { 10170 // For legacy apps that need a permission review, every new 10171 // runtime permission is granted but it is pending a review. 10172 // We also need to review only platform defined runtime 10173 // permissions as these are the only ones the platform knows 10174 // how to disable the API to simulate revocation as legacy 10175 // apps don't expect to run with revoked permissions. 10176 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10177 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10178 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10179 // We changed the flags, hence have to write. 10180 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10181 changedRuntimePermissionUserIds, userId); 10182 } 10183 } 10184 if (permissionsState.grantRuntimePermission(bp, userId) 10185 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10186 // We changed the permission, hence have to write. 10187 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10188 changedRuntimePermissionUserIds, userId); 10189 } 10190 } 10191 // Propagate the permission flags. 10192 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10193 } 10194 } break; 10195 10196 case GRANT_UPGRADE: { 10197 // Grant runtime permissions for a previously held install permission. 10198 PermissionState permissionState = origPermissions 10199 .getInstallPermissionState(bp.name); 10200 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10201 10202 if (origPermissions.revokeInstallPermission(bp) 10203 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10204 // We will be transferring the permission flags, so clear them. 10205 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10206 PackageManager.MASK_PERMISSION_FLAGS, 0); 10207 changedInstallPermission = true; 10208 } 10209 10210 // If the permission is not to be promoted to runtime we ignore it and 10211 // also its other flags as they are not applicable to install permissions. 10212 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10213 for (int userId : currentUserIds) { 10214 if (permissionsState.grantRuntimePermission(bp, userId) != 10215 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10216 // Transfer the permission flags. 10217 permissionsState.updatePermissionFlags(bp, userId, 10218 flags, flags); 10219 // If we granted the permission, we have to write. 10220 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10221 changedRuntimePermissionUserIds, userId); 10222 } 10223 } 10224 } 10225 } break; 10226 10227 default: { 10228 if (packageOfInterest == null 10229 || packageOfInterest.equals(pkg.packageName)) { 10230 Slog.w(TAG, "Not granting permission " + perm 10231 + " to package " + pkg.packageName 10232 + " because it was previously installed without"); 10233 } 10234 } break; 10235 } 10236 } else { 10237 if (permissionsState.revokeInstallPermission(bp) != 10238 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10239 // Also drop the permission flags. 10240 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10241 PackageManager.MASK_PERMISSION_FLAGS, 0); 10242 changedInstallPermission = true; 10243 Slog.i(TAG, "Un-granting permission " + perm 10244 + " from package " + pkg.packageName 10245 + " (protectionLevel=" + bp.protectionLevel 10246 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10247 + ")"); 10248 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10249 // Don't print warning for app op permissions, since it is fine for them 10250 // not to be granted, there is a UI for the user to decide. 10251 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10252 Slog.w(TAG, "Not granting permission " + perm 10253 + " to package " + pkg.packageName 10254 + " (protectionLevel=" + bp.protectionLevel 10255 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10256 + ")"); 10257 } 10258 } 10259 } 10260 } 10261 10262 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10263 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10264 // This is the first that we have heard about this package, so the 10265 // permissions we have now selected are fixed until explicitly 10266 // changed. 10267 ps.installPermissionsFixed = true; 10268 } 10269 10270 // Persist the runtime permissions state for users with changes. If permissions 10271 // were revoked because no app in the shared user declares them we have to 10272 // write synchronously to avoid losing runtime permissions state. 10273 for (int userId : changedRuntimePermissionUserIds) { 10274 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10275 } 10276 10277 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10278 } 10279 10280 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10281 boolean allowed = false; 10282 final int NP = PackageParser.NEW_PERMISSIONS.length; 10283 for (int ip=0; ip<NP; ip++) { 10284 final PackageParser.NewPermissionInfo npi 10285 = PackageParser.NEW_PERMISSIONS[ip]; 10286 if (npi.name.equals(perm) 10287 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10288 allowed = true; 10289 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10290 + pkg.packageName); 10291 break; 10292 } 10293 } 10294 return allowed; 10295 } 10296 10297 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10298 BasePermission bp, PermissionsState origPermissions) { 10299 boolean allowed; 10300 allowed = (compareSignatures( 10301 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10302 == PackageManager.SIGNATURE_MATCH) 10303 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10304 == PackageManager.SIGNATURE_MATCH); 10305 if (!allowed && (bp.protectionLevel 10306 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10307 if (isSystemApp(pkg)) { 10308 // For updated system applications, a system permission 10309 // is granted only if it had been defined by the original application. 10310 if (pkg.isUpdatedSystemApp()) { 10311 final PackageSetting sysPs = mSettings 10312 .getDisabledSystemPkgLPr(pkg.packageName); 10313 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10314 // If the original was granted this permission, we take 10315 // that grant decision as read and propagate it to the 10316 // update. 10317 if (sysPs.isPrivileged()) { 10318 allowed = true; 10319 } 10320 } else { 10321 // The system apk may have been updated with an older 10322 // version of the one on the data partition, but which 10323 // granted a new system permission that it didn't have 10324 // before. In this case we do want to allow the app to 10325 // now get the new permission if the ancestral apk is 10326 // privileged to get it. 10327 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10328 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10329 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10330 allowed = true; 10331 break; 10332 } 10333 } 10334 } 10335 // Also if a privileged parent package on the system image or any of 10336 // its children requested a privileged permission, the updated child 10337 // packages can also get the permission. 10338 if (pkg.parentPackage != null) { 10339 final PackageSetting disabledSysParentPs = mSettings 10340 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10341 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10342 && disabledSysParentPs.isPrivileged()) { 10343 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10344 allowed = true; 10345 } else if (disabledSysParentPs.pkg.childPackages != null) { 10346 final int count = disabledSysParentPs.pkg.childPackages.size(); 10347 for (int i = 0; i < count; i++) { 10348 PackageParser.Package disabledSysChildPkg = 10349 disabledSysParentPs.pkg.childPackages.get(i); 10350 if (isPackageRequestingPermission(disabledSysChildPkg, 10351 perm)) { 10352 allowed = true; 10353 break; 10354 } 10355 } 10356 } 10357 } 10358 } 10359 } 10360 } else { 10361 allowed = isPrivilegedApp(pkg); 10362 } 10363 } 10364 } 10365 if (!allowed) { 10366 if (!allowed && (bp.protectionLevel 10367 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10368 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10369 // If this was a previously normal/dangerous permission that got moved 10370 // to a system permission as part of the runtime permission redesign, then 10371 // we still want to blindly grant it to old apps. 10372 allowed = true; 10373 } 10374 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10375 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10376 // If this permission is to be granted to the system installer and 10377 // this app is an installer, then it gets the permission. 10378 allowed = true; 10379 } 10380 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10381 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10382 // If this permission is to be granted to the system verifier and 10383 // this app is a verifier, then it gets the permission. 10384 allowed = true; 10385 } 10386 if (!allowed && (bp.protectionLevel 10387 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10388 && isSystemApp(pkg)) { 10389 // Any pre-installed system app is allowed to get this permission. 10390 allowed = true; 10391 } 10392 if (!allowed && (bp.protectionLevel 10393 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10394 // For development permissions, a development permission 10395 // is granted only if it was already granted. 10396 allowed = origPermissions.hasInstallPermission(perm); 10397 } 10398 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10399 && pkg.packageName.equals(mSetupWizardPackage)) { 10400 // If this permission is to be granted to the system setup wizard and 10401 // this app is a setup wizard, then it gets the permission. 10402 allowed = true; 10403 } 10404 } 10405 return allowed; 10406 } 10407 10408 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10409 final int permCount = pkg.requestedPermissions.size(); 10410 for (int j = 0; j < permCount; j++) { 10411 String requestedPermission = pkg.requestedPermissions.get(j); 10412 if (permission.equals(requestedPermission)) { 10413 return true; 10414 } 10415 } 10416 return false; 10417 } 10418 10419 final class ActivityIntentResolver 10420 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10421 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10422 boolean defaultOnly, int userId) { 10423 if (!sUserManager.exists(userId)) return null; 10424 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10425 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10426 } 10427 10428 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10429 int userId) { 10430 if (!sUserManager.exists(userId)) return null; 10431 mFlags = flags; 10432 return super.queryIntent(intent, resolvedType, 10433 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10434 } 10435 10436 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10437 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10438 if (!sUserManager.exists(userId)) return null; 10439 if (packageActivities == null) { 10440 return null; 10441 } 10442 mFlags = flags; 10443 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10444 final int N = packageActivities.size(); 10445 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10446 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10447 10448 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10449 for (int i = 0; i < N; ++i) { 10450 intentFilters = packageActivities.get(i).intents; 10451 if (intentFilters != null && intentFilters.size() > 0) { 10452 PackageParser.ActivityIntentInfo[] array = 10453 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10454 intentFilters.toArray(array); 10455 listCut.add(array); 10456 } 10457 } 10458 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10459 } 10460 10461 /** 10462 * Finds a privileged activity that matches the specified activity names. 10463 */ 10464 private PackageParser.Activity findMatchingActivity( 10465 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10466 for (PackageParser.Activity sysActivity : activityList) { 10467 if (sysActivity.info.name.equals(activityInfo.name)) { 10468 return sysActivity; 10469 } 10470 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10471 return sysActivity; 10472 } 10473 if (sysActivity.info.targetActivity != null) { 10474 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10475 return sysActivity; 10476 } 10477 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10478 return sysActivity; 10479 } 10480 } 10481 } 10482 return null; 10483 } 10484 10485 public class IterGenerator<E> { 10486 public Iterator<E> generate(ActivityIntentInfo info) { 10487 return null; 10488 } 10489 } 10490 10491 public class ActionIterGenerator extends IterGenerator<String> { 10492 @Override 10493 public Iterator<String> generate(ActivityIntentInfo info) { 10494 return info.actionsIterator(); 10495 } 10496 } 10497 10498 public class CategoriesIterGenerator extends IterGenerator<String> { 10499 @Override 10500 public Iterator<String> generate(ActivityIntentInfo info) { 10501 return info.categoriesIterator(); 10502 } 10503 } 10504 10505 public class SchemesIterGenerator extends IterGenerator<String> { 10506 @Override 10507 public Iterator<String> generate(ActivityIntentInfo info) { 10508 return info.schemesIterator(); 10509 } 10510 } 10511 10512 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10513 @Override 10514 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10515 return info.authoritiesIterator(); 10516 } 10517 } 10518 10519 /** 10520 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10521 * MODIFIED. Do not pass in a list that should not be changed. 10522 */ 10523 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10524 IterGenerator<T> generator, Iterator<T> searchIterator) { 10525 // loop through the set of actions; every one must be found in the intent filter 10526 while (searchIterator.hasNext()) { 10527 // we must have at least one filter in the list to consider a match 10528 if (intentList.size() == 0) { 10529 break; 10530 } 10531 10532 final T searchAction = searchIterator.next(); 10533 10534 // loop through the set of intent filters 10535 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10536 while (intentIter.hasNext()) { 10537 final ActivityIntentInfo intentInfo = intentIter.next(); 10538 boolean selectionFound = false; 10539 10540 // loop through the intent filter's selection criteria; at least one 10541 // of them must match the searched criteria 10542 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10543 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10544 final T intentSelection = intentSelectionIter.next(); 10545 if (intentSelection != null && intentSelection.equals(searchAction)) { 10546 selectionFound = true; 10547 break; 10548 } 10549 } 10550 10551 // the selection criteria wasn't found in this filter's set; this filter 10552 // is not a potential match 10553 if (!selectionFound) { 10554 intentIter.remove(); 10555 } 10556 } 10557 } 10558 } 10559 10560 private boolean isProtectedAction(ActivityIntentInfo filter) { 10561 final Iterator<String> actionsIter = filter.actionsIterator(); 10562 while (actionsIter != null && actionsIter.hasNext()) { 10563 final String filterAction = actionsIter.next(); 10564 if (PROTECTED_ACTIONS.contains(filterAction)) { 10565 return true; 10566 } 10567 } 10568 return false; 10569 } 10570 10571 /** 10572 * Adjusts the priority of the given intent filter according to policy. 10573 * <p> 10574 * <ul> 10575 * <li>The priority for non privileged applications is capped to '0'</li> 10576 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10577 * <li>The priority for unbundled updates to privileged applications is capped to the 10578 * priority defined on the system partition</li> 10579 * </ul> 10580 * <p> 10581 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10582 * allowed to obtain any priority on any action. 10583 */ 10584 private void adjustPriority( 10585 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10586 // nothing to do; priority is fine as-is 10587 if (intent.getPriority() <= 0) { 10588 return; 10589 } 10590 10591 final ActivityInfo activityInfo = intent.activity.info; 10592 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10593 10594 final boolean privilegedApp = 10595 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10596 if (!privilegedApp) { 10597 // non-privileged applications can never define a priority >0 10598 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10599 + " package: " + applicationInfo.packageName 10600 + " activity: " + intent.activity.className 10601 + " origPrio: " + intent.getPriority()); 10602 intent.setPriority(0); 10603 return; 10604 } 10605 10606 if (systemActivities == null) { 10607 // the system package is not disabled; we're parsing the system partition 10608 if (isProtectedAction(intent)) { 10609 if (mDeferProtectedFilters) { 10610 // We can't deal with these just yet. No component should ever obtain a 10611 // >0 priority for a protected actions, with ONE exception -- the setup 10612 // wizard. The setup wizard, however, cannot be known until we're able to 10613 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10614 // until all intent filters have been processed. Chicken, meet egg. 10615 // Let the filter temporarily have a high priority and rectify the 10616 // priorities after all system packages have been scanned. 10617 mProtectedFilters.add(intent); 10618 if (DEBUG_FILTERS) { 10619 Slog.i(TAG, "Protected action; save for later;" 10620 + " package: " + applicationInfo.packageName 10621 + " activity: " + intent.activity.className 10622 + " origPrio: " + intent.getPriority()); 10623 } 10624 return; 10625 } else { 10626 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10627 Slog.i(TAG, "No setup wizard;" 10628 + " All protected intents capped to priority 0"); 10629 } 10630 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10631 if (DEBUG_FILTERS) { 10632 Slog.i(TAG, "Found setup wizard;" 10633 + " allow priority " + intent.getPriority() + ";" 10634 + " package: " + intent.activity.info.packageName 10635 + " activity: " + intent.activity.className 10636 + " priority: " + intent.getPriority()); 10637 } 10638 // setup wizard gets whatever it wants 10639 return; 10640 } 10641 Slog.w(TAG, "Protected action; cap priority to 0;" 10642 + " package: " + intent.activity.info.packageName 10643 + " activity: " + intent.activity.className 10644 + " origPrio: " + intent.getPriority()); 10645 intent.setPriority(0); 10646 return; 10647 } 10648 } 10649 // privileged apps on the system image get whatever priority they request 10650 return; 10651 } 10652 10653 // privileged app unbundled update ... try to find the same activity 10654 final PackageParser.Activity foundActivity = 10655 findMatchingActivity(systemActivities, activityInfo); 10656 if (foundActivity == null) { 10657 // this is a new activity; it cannot obtain >0 priority 10658 if (DEBUG_FILTERS) { 10659 Slog.i(TAG, "New activity; cap priority to 0;" 10660 + " package: " + applicationInfo.packageName 10661 + " activity: " + intent.activity.className 10662 + " origPrio: " + intent.getPriority()); 10663 } 10664 intent.setPriority(0); 10665 return; 10666 } 10667 10668 // found activity, now check for filter equivalence 10669 10670 // a shallow copy is enough; we modify the list, not its contents 10671 final List<ActivityIntentInfo> intentListCopy = 10672 new ArrayList<>(foundActivity.intents); 10673 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10674 10675 // find matching action subsets 10676 final Iterator<String> actionsIterator = intent.actionsIterator(); 10677 if (actionsIterator != null) { 10678 getIntentListSubset( 10679 intentListCopy, new ActionIterGenerator(), actionsIterator); 10680 if (intentListCopy.size() == 0) { 10681 // no more intents to match; we're not equivalent 10682 if (DEBUG_FILTERS) { 10683 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10684 + " package: " + applicationInfo.packageName 10685 + " activity: " + intent.activity.className 10686 + " origPrio: " + intent.getPriority()); 10687 } 10688 intent.setPriority(0); 10689 return; 10690 } 10691 } 10692 10693 // find matching category subsets 10694 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10695 if (categoriesIterator != null) { 10696 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10697 categoriesIterator); 10698 if (intentListCopy.size() == 0) { 10699 // no more intents to match; we're not equivalent 10700 if (DEBUG_FILTERS) { 10701 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10702 + " package: " + applicationInfo.packageName 10703 + " activity: " + intent.activity.className 10704 + " origPrio: " + intent.getPriority()); 10705 } 10706 intent.setPriority(0); 10707 return; 10708 } 10709 } 10710 10711 // find matching schemes subsets 10712 final Iterator<String> schemesIterator = intent.schemesIterator(); 10713 if (schemesIterator != null) { 10714 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10715 schemesIterator); 10716 if (intentListCopy.size() == 0) { 10717 // no more intents to match; we're not equivalent 10718 if (DEBUG_FILTERS) { 10719 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10720 + " package: " + applicationInfo.packageName 10721 + " activity: " + intent.activity.className 10722 + " origPrio: " + intent.getPriority()); 10723 } 10724 intent.setPriority(0); 10725 return; 10726 } 10727 } 10728 10729 // find matching authorities subsets 10730 final Iterator<IntentFilter.AuthorityEntry> 10731 authoritiesIterator = intent.authoritiesIterator(); 10732 if (authoritiesIterator != null) { 10733 getIntentListSubset(intentListCopy, 10734 new AuthoritiesIterGenerator(), 10735 authoritiesIterator); 10736 if (intentListCopy.size() == 0) { 10737 // no more intents to match; we're not equivalent 10738 if (DEBUG_FILTERS) { 10739 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10740 + " package: " + applicationInfo.packageName 10741 + " activity: " + intent.activity.className 10742 + " origPrio: " + intent.getPriority()); 10743 } 10744 intent.setPriority(0); 10745 return; 10746 } 10747 } 10748 10749 // we found matching filter(s); app gets the max priority of all intents 10750 int cappedPriority = 0; 10751 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10752 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10753 } 10754 if (intent.getPriority() > cappedPriority) { 10755 if (DEBUG_FILTERS) { 10756 Slog.i(TAG, "Found matching filter(s);" 10757 + " cap priority to " + cappedPriority + ";" 10758 + " package: " + applicationInfo.packageName 10759 + " activity: " + intent.activity.className 10760 + " origPrio: " + intent.getPriority()); 10761 } 10762 intent.setPriority(cappedPriority); 10763 return; 10764 } 10765 // all this for nothing; the requested priority was <= what was on the system 10766 } 10767 10768 public final void addActivity(PackageParser.Activity a, String type) { 10769 mActivities.put(a.getComponentName(), a); 10770 if (DEBUG_SHOW_INFO) 10771 Log.v( 10772 TAG, " " + type + " " + 10773 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10774 if (DEBUG_SHOW_INFO) 10775 Log.v(TAG, " Class=" + a.info.name); 10776 final int NI = a.intents.size(); 10777 for (int j=0; j<NI; j++) { 10778 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10779 if ("activity".equals(type)) { 10780 final PackageSetting ps = 10781 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10782 final List<PackageParser.Activity> systemActivities = 10783 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10784 adjustPriority(systemActivities, intent); 10785 } 10786 if (DEBUG_SHOW_INFO) { 10787 Log.v(TAG, " IntentFilter:"); 10788 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10789 } 10790 if (!intent.debugCheck()) { 10791 Log.w(TAG, "==> For Activity " + a.info.name); 10792 } 10793 addFilter(intent); 10794 } 10795 } 10796 10797 public final void removeActivity(PackageParser.Activity a, String type) { 10798 mActivities.remove(a.getComponentName()); 10799 if (DEBUG_SHOW_INFO) { 10800 Log.v(TAG, " " + type + " " 10801 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10802 : a.info.name) + ":"); 10803 Log.v(TAG, " Class=" + a.info.name); 10804 } 10805 final int NI = a.intents.size(); 10806 for (int j=0; j<NI; j++) { 10807 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10808 if (DEBUG_SHOW_INFO) { 10809 Log.v(TAG, " IntentFilter:"); 10810 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10811 } 10812 removeFilter(intent); 10813 } 10814 } 10815 10816 @Override 10817 protected boolean allowFilterResult( 10818 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10819 ActivityInfo filterAi = filter.activity.info; 10820 for (int i=dest.size()-1; i>=0; i--) { 10821 ActivityInfo destAi = dest.get(i).activityInfo; 10822 if (destAi.name == filterAi.name 10823 && destAi.packageName == filterAi.packageName) { 10824 return false; 10825 } 10826 } 10827 return true; 10828 } 10829 10830 @Override 10831 protected ActivityIntentInfo[] newArray(int size) { 10832 return new ActivityIntentInfo[size]; 10833 } 10834 10835 @Override 10836 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10837 if (!sUserManager.exists(userId)) return true; 10838 PackageParser.Package p = filter.activity.owner; 10839 if (p != null) { 10840 PackageSetting ps = (PackageSetting)p.mExtras; 10841 if (ps != null) { 10842 // System apps are never considered stopped for purposes of 10843 // filtering, because there may be no way for the user to 10844 // actually re-launch them. 10845 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10846 && ps.getStopped(userId); 10847 } 10848 } 10849 return false; 10850 } 10851 10852 @Override 10853 protected boolean isPackageForFilter(String packageName, 10854 PackageParser.ActivityIntentInfo info) { 10855 return packageName.equals(info.activity.owner.packageName); 10856 } 10857 10858 @Override 10859 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10860 int match, int userId) { 10861 if (!sUserManager.exists(userId)) return null; 10862 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10863 return null; 10864 } 10865 final PackageParser.Activity activity = info.activity; 10866 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10867 if (ps == null) { 10868 return null; 10869 } 10870 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10871 ps.readUserState(userId), userId); 10872 if (ai == null) { 10873 return null; 10874 } 10875 final ResolveInfo res = new ResolveInfo(); 10876 res.activityInfo = ai; 10877 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10878 res.filter = info; 10879 } 10880 if (info != null) { 10881 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10882 } 10883 res.priority = info.getPriority(); 10884 res.preferredOrder = activity.owner.mPreferredOrder; 10885 //System.out.println("Result: " + res.activityInfo.className + 10886 // " = " + res.priority); 10887 res.match = match; 10888 res.isDefault = info.hasDefault; 10889 res.labelRes = info.labelRes; 10890 res.nonLocalizedLabel = info.nonLocalizedLabel; 10891 if (userNeedsBadging(userId)) { 10892 res.noResourceId = true; 10893 } else { 10894 res.icon = info.icon; 10895 } 10896 res.iconResourceId = info.icon; 10897 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10898 return res; 10899 } 10900 10901 @Override 10902 protected void sortResults(List<ResolveInfo> results) { 10903 Collections.sort(results, mResolvePrioritySorter); 10904 } 10905 10906 @Override 10907 protected void dumpFilter(PrintWriter out, String prefix, 10908 PackageParser.ActivityIntentInfo filter) { 10909 out.print(prefix); out.print( 10910 Integer.toHexString(System.identityHashCode(filter.activity))); 10911 out.print(' '); 10912 filter.activity.printComponentShortName(out); 10913 out.print(" filter "); 10914 out.println(Integer.toHexString(System.identityHashCode(filter))); 10915 } 10916 10917 @Override 10918 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10919 return filter.activity; 10920 } 10921 10922 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10923 PackageParser.Activity activity = (PackageParser.Activity)label; 10924 out.print(prefix); out.print( 10925 Integer.toHexString(System.identityHashCode(activity))); 10926 out.print(' '); 10927 activity.printComponentShortName(out); 10928 if (count > 1) { 10929 out.print(" ("); out.print(count); out.print(" filters)"); 10930 } 10931 out.println(); 10932 } 10933 10934 // Keys are String (activity class name), values are Activity. 10935 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10936 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10937 private int mFlags; 10938 } 10939 10940 private final class ServiceIntentResolver 10941 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10942 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10943 boolean defaultOnly, int userId) { 10944 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10945 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10946 } 10947 10948 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10949 int userId) { 10950 if (!sUserManager.exists(userId)) return null; 10951 mFlags = flags; 10952 return super.queryIntent(intent, resolvedType, 10953 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10954 } 10955 10956 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10957 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10958 if (!sUserManager.exists(userId)) return null; 10959 if (packageServices == null) { 10960 return null; 10961 } 10962 mFlags = flags; 10963 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10964 final int N = packageServices.size(); 10965 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10966 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10967 10968 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10969 for (int i = 0; i < N; ++i) { 10970 intentFilters = packageServices.get(i).intents; 10971 if (intentFilters != null && intentFilters.size() > 0) { 10972 PackageParser.ServiceIntentInfo[] array = 10973 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10974 intentFilters.toArray(array); 10975 listCut.add(array); 10976 } 10977 } 10978 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10979 } 10980 10981 public final void addService(PackageParser.Service s) { 10982 mServices.put(s.getComponentName(), s); 10983 if (DEBUG_SHOW_INFO) { 10984 Log.v(TAG, " " 10985 + (s.info.nonLocalizedLabel != null 10986 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10987 Log.v(TAG, " Class=" + s.info.name); 10988 } 10989 final int NI = s.intents.size(); 10990 int j; 10991 for (j=0; j<NI; j++) { 10992 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10993 if (DEBUG_SHOW_INFO) { 10994 Log.v(TAG, " IntentFilter:"); 10995 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10996 } 10997 if (!intent.debugCheck()) { 10998 Log.w(TAG, "==> For Service " + s.info.name); 10999 } 11000 addFilter(intent); 11001 } 11002 } 11003 11004 public final void removeService(PackageParser.Service s) { 11005 mServices.remove(s.getComponentName()); 11006 if (DEBUG_SHOW_INFO) { 11007 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11008 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11009 Log.v(TAG, " Class=" + s.info.name); 11010 } 11011 final int NI = s.intents.size(); 11012 int j; 11013 for (j=0; j<NI; j++) { 11014 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11015 if (DEBUG_SHOW_INFO) { 11016 Log.v(TAG, " IntentFilter:"); 11017 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11018 } 11019 removeFilter(intent); 11020 } 11021 } 11022 11023 @Override 11024 protected boolean allowFilterResult( 11025 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11026 ServiceInfo filterSi = filter.service.info; 11027 for (int i=dest.size()-1; i>=0; i--) { 11028 ServiceInfo destAi = dest.get(i).serviceInfo; 11029 if (destAi.name == filterSi.name 11030 && destAi.packageName == filterSi.packageName) { 11031 return false; 11032 } 11033 } 11034 return true; 11035 } 11036 11037 @Override 11038 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11039 return new PackageParser.ServiceIntentInfo[size]; 11040 } 11041 11042 @Override 11043 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11044 if (!sUserManager.exists(userId)) return true; 11045 PackageParser.Package p = filter.service.owner; 11046 if (p != null) { 11047 PackageSetting ps = (PackageSetting)p.mExtras; 11048 if (ps != null) { 11049 // System apps are never considered stopped for purposes of 11050 // filtering, because there may be no way for the user to 11051 // actually re-launch them. 11052 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11053 && ps.getStopped(userId); 11054 } 11055 } 11056 return false; 11057 } 11058 11059 @Override 11060 protected boolean isPackageForFilter(String packageName, 11061 PackageParser.ServiceIntentInfo info) { 11062 return packageName.equals(info.service.owner.packageName); 11063 } 11064 11065 @Override 11066 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11067 int match, int userId) { 11068 if (!sUserManager.exists(userId)) return null; 11069 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11070 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11071 return null; 11072 } 11073 final PackageParser.Service service = info.service; 11074 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11075 if (ps == null) { 11076 return null; 11077 } 11078 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11079 ps.readUserState(userId), userId); 11080 if (si == null) { 11081 return null; 11082 } 11083 final ResolveInfo res = new ResolveInfo(); 11084 res.serviceInfo = si; 11085 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11086 res.filter = filter; 11087 } 11088 res.priority = info.getPriority(); 11089 res.preferredOrder = service.owner.mPreferredOrder; 11090 res.match = match; 11091 res.isDefault = info.hasDefault; 11092 res.labelRes = info.labelRes; 11093 res.nonLocalizedLabel = info.nonLocalizedLabel; 11094 res.icon = info.icon; 11095 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11096 return res; 11097 } 11098 11099 @Override 11100 protected void sortResults(List<ResolveInfo> results) { 11101 Collections.sort(results, mResolvePrioritySorter); 11102 } 11103 11104 @Override 11105 protected void dumpFilter(PrintWriter out, String prefix, 11106 PackageParser.ServiceIntentInfo filter) { 11107 out.print(prefix); out.print( 11108 Integer.toHexString(System.identityHashCode(filter.service))); 11109 out.print(' '); 11110 filter.service.printComponentShortName(out); 11111 out.print(" filter "); 11112 out.println(Integer.toHexString(System.identityHashCode(filter))); 11113 } 11114 11115 @Override 11116 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11117 return filter.service; 11118 } 11119 11120 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11121 PackageParser.Service service = (PackageParser.Service)label; 11122 out.print(prefix); out.print( 11123 Integer.toHexString(System.identityHashCode(service))); 11124 out.print(' '); 11125 service.printComponentShortName(out); 11126 if (count > 1) { 11127 out.print(" ("); out.print(count); out.print(" filters)"); 11128 } 11129 out.println(); 11130 } 11131 11132// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11133// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11134// final List<ResolveInfo> retList = Lists.newArrayList(); 11135// while (i.hasNext()) { 11136// final ResolveInfo resolveInfo = (ResolveInfo) i; 11137// if (isEnabledLP(resolveInfo.serviceInfo)) { 11138// retList.add(resolveInfo); 11139// } 11140// } 11141// return retList; 11142// } 11143 11144 // Keys are String (activity class name), values are Activity. 11145 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11146 = new ArrayMap<ComponentName, PackageParser.Service>(); 11147 private int mFlags; 11148 }; 11149 11150 private final class ProviderIntentResolver 11151 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11152 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11153 boolean defaultOnly, int userId) { 11154 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11155 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11156 } 11157 11158 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11159 int userId) { 11160 if (!sUserManager.exists(userId)) 11161 return null; 11162 mFlags = flags; 11163 return super.queryIntent(intent, resolvedType, 11164 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11165 } 11166 11167 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11168 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11169 if (!sUserManager.exists(userId)) 11170 return null; 11171 if (packageProviders == null) { 11172 return null; 11173 } 11174 mFlags = flags; 11175 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11176 final int N = packageProviders.size(); 11177 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11178 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11179 11180 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11181 for (int i = 0; i < N; ++i) { 11182 intentFilters = packageProviders.get(i).intents; 11183 if (intentFilters != null && intentFilters.size() > 0) { 11184 PackageParser.ProviderIntentInfo[] array = 11185 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11186 intentFilters.toArray(array); 11187 listCut.add(array); 11188 } 11189 } 11190 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11191 } 11192 11193 public final void addProvider(PackageParser.Provider p) { 11194 if (mProviders.containsKey(p.getComponentName())) { 11195 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11196 return; 11197 } 11198 11199 mProviders.put(p.getComponentName(), p); 11200 if (DEBUG_SHOW_INFO) { 11201 Log.v(TAG, " " 11202 + (p.info.nonLocalizedLabel != null 11203 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11204 Log.v(TAG, " Class=" + p.info.name); 11205 } 11206 final int NI = p.intents.size(); 11207 int j; 11208 for (j = 0; j < NI; j++) { 11209 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11210 if (DEBUG_SHOW_INFO) { 11211 Log.v(TAG, " IntentFilter:"); 11212 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11213 } 11214 if (!intent.debugCheck()) { 11215 Log.w(TAG, "==> For Provider " + p.info.name); 11216 } 11217 addFilter(intent); 11218 } 11219 } 11220 11221 public final void removeProvider(PackageParser.Provider p) { 11222 mProviders.remove(p.getComponentName()); 11223 if (DEBUG_SHOW_INFO) { 11224 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11225 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11226 Log.v(TAG, " Class=" + p.info.name); 11227 } 11228 final int NI = p.intents.size(); 11229 int j; 11230 for (j = 0; j < NI; j++) { 11231 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11232 if (DEBUG_SHOW_INFO) { 11233 Log.v(TAG, " IntentFilter:"); 11234 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11235 } 11236 removeFilter(intent); 11237 } 11238 } 11239 11240 @Override 11241 protected boolean allowFilterResult( 11242 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11243 ProviderInfo filterPi = filter.provider.info; 11244 for (int i = dest.size() - 1; i >= 0; i--) { 11245 ProviderInfo destPi = dest.get(i).providerInfo; 11246 if (destPi.name == filterPi.name 11247 && destPi.packageName == filterPi.packageName) { 11248 return false; 11249 } 11250 } 11251 return true; 11252 } 11253 11254 @Override 11255 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11256 return new PackageParser.ProviderIntentInfo[size]; 11257 } 11258 11259 @Override 11260 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11261 if (!sUserManager.exists(userId)) 11262 return true; 11263 PackageParser.Package p = filter.provider.owner; 11264 if (p != null) { 11265 PackageSetting ps = (PackageSetting) p.mExtras; 11266 if (ps != null) { 11267 // System apps are never considered stopped for purposes of 11268 // filtering, because there may be no way for the user to 11269 // actually re-launch them. 11270 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11271 && ps.getStopped(userId); 11272 } 11273 } 11274 return false; 11275 } 11276 11277 @Override 11278 protected boolean isPackageForFilter(String packageName, 11279 PackageParser.ProviderIntentInfo info) { 11280 return packageName.equals(info.provider.owner.packageName); 11281 } 11282 11283 @Override 11284 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11285 int match, int userId) { 11286 if (!sUserManager.exists(userId)) 11287 return null; 11288 final PackageParser.ProviderIntentInfo info = filter; 11289 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11290 return null; 11291 } 11292 final PackageParser.Provider provider = info.provider; 11293 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11294 if (ps == null) { 11295 return null; 11296 } 11297 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11298 ps.readUserState(userId), userId); 11299 if (pi == null) { 11300 return null; 11301 } 11302 final ResolveInfo res = new ResolveInfo(); 11303 res.providerInfo = pi; 11304 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11305 res.filter = filter; 11306 } 11307 res.priority = info.getPriority(); 11308 res.preferredOrder = provider.owner.mPreferredOrder; 11309 res.match = match; 11310 res.isDefault = info.hasDefault; 11311 res.labelRes = info.labelRes; 11312 res.nonLocalizedLabel = info.nonLocalizedLabel; 11313 res.icon = info.icon; 11314 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11315 return res; 11316 } 11317 11318 @Override 11319 protected void sortResults(List<ResolveInfo> results) { 11320 Collections.sort(results, mResolvePrioritySorter); 11321 } 11322 11323 @Override 11324 protected void dumpFilter(PrintWriter out, String prefix, 11325 PackageParser.ProviderIntentInfo filter) { 11326 out.print(prefix); 11327 out.print( 11328 Integer.toHexString(System.identityHashCode(filter.provider))); 11329 out.print(' '); 11330 filter.provider.printComponentShortName(out); 11331 out.print(" filter "); 11332 out.println(Integer.toHexString(System.identityHashCode(filter))); 11333 } 11334 11335 @Override 11336 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11337 return filter.provider; 11338 } 11339 11340 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11341 PackageParser.Provider provider = (PackageParser.Provider)label; 11342 out.print(prefix); out.print( 11343 Integer.toHexString(System.identityHashCode(provider))); 11344 out.print(' '); 11345 provider.printComponentShortName(out); 11346 if (count > 1) { 11347 out.print(" ("); out.print(count); out.print(" filters)"); 11348 } 11349 out.println(); 11350 } 11351 11352 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11353 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11354 private int mFlags; 11355 } 11356 11357 private static final class EphemeralIntentResolver 11358 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11359 @Override 11360 protected EphemeralResolveIntentInfo[] newArray(int size) { 11361 return new EphemeralResolveIntentInfo[size]; 11362 } 11363 11364 @Override 11365 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11366 return true; 11367 } 11368 11369 @Override 11370 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11371 int userId) { 11372 if (!sUserManager.exists(userId)) { 11373 return null; 11374 } 11375 return info.getEphemeralResolveInfo(); 11376 } 11377 } 11378 11379 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11380 new Comparator<ResolveInfo>() { 11381 public int compare(ResolveInfo r1, ResolveInfo r2) { 11382 int v1 = r1.priority; 11383 int v2 = r2.priority; 11384 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11385 if (v1 != v2) { 11386 return (v1 > v2) ? -1 : 1; 11387 } 11388 v1 = r1.preferredOrder; 11389 v2 = r2.preferredOrder; 11390 if (v1 != v2) { 11391 return (v1 > v2) ? -1 : 1; 11392 } 11393 if (r1.isDefault != r2.isDefault) { 11394 return r1.isDefault ? -1 : 1; 11395 } 11396 v1 = r1.match; 11397 v2 = r2.match; 11398 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11399 if (v1 != v2) { 11400 return (v1 > v2) ? -1 : 1; 11401 } 11402 if (r1.system != r2.system) { 11403 return r1.system ? -1 : 1; 11404 } 11405 if (r1.activityInfo != null) { 11406 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11407 } 11408 if (r1.serviceInfo != null) { 11409 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11410 } 11411 if (r1.providerInfo != null) { 11412 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11413 } 11414 return 0; 11415 } 11416 }; 11417 11418 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11419 new Comparator<ProviderInfo>() { 11420 public int compare(ProviderInfo p1, ProviderInfo p2) { 11421 final int v1 = p1.initOrder; 11422 final int v2 = p2.initOrder; 11423 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11424 } 11425 }; 11426 11427 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11428 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11429 final int[] userIds) { 11430 mHandler.post(new Runnable() { 11431 @Override 11432 public void run() { 11433 try { 11434 final IActivityManager am = ActivityManagerNative.getDefault(); 11435 if (am == null) return; 11436 final int[] resolvedUserIds; 11437 if (userIds == null) { 11438 resolvedUserIds = am.getRunningUserIds(); 11439 } else { 11440 resolvedUserIds = userIds; 11441 } 11442 final ShortcutServiceInternal shortcutService = 11443 LocalServices.getService(ShortcutServiceInternal.class); 11444 11445 for (int id : resolvedUserIds) { 11446 final Intent intent = new Intent(action, 11447 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11448 if (extras != null) { 11449 intent.putExtras(extras); 11450 } 11451 if (targetPkg != null) { 11452 intent.setPackage(targetPkg); 11453 } 11454 // Modify the UID when posting to other users 11455 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11456 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11457 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11458 intent.putExtra(Intent.EXTRA_UID, uid); 11459 } 11460 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11461 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11462 if (DEBUG_BROADCASTS) { 11463 RuntimeException here = new RuntimeException("here"); 11464 here.fillInStackTrace(); 11465 Slog.d(TAG, "Sending to user " + id + ": " 11466 + intent.toShortString(false, true, false, false) 11467 + " " + intent.getExtras(), here); 11468 } 11469 // TODO b/29385425 Consider making lifecycle callbacks for this. 11470 if (shortcutService != null) { 11471 shortcutService.onPackageBroadcast(intent); 11472 } 11473 am.broadcastIntent(null, intent, null, finishedReceiver, 11474 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11475 null, finishedReceiver != null, false, id); 11476 } 11477 } catch (RemoteException ex) { 11478 } 11479 } 11480 }); 11481 } 11482 11483 /** 11484 * Check if the external storage media is available. This is true if there 11485 * is a mounted external storage medium or if the external storage is 11486 * emulated. 11487 */ 11488 private boolean isExternalMediaAvailable() { 11489 return mMediaMounted || Environment.isExternalStorageEmulated(); 11490 } 11491 11492 @Override 11493 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11494 // writer 11495 synchronized (mPackages) { 11496 if (!isExternalMediaAvailable()) { 11497 // If the external storage is no longer mounted at this point, 11498 // the caller may not have been able to delete all of this 11499 // packages files and can not delete any more. Bail. 11500 return null; 11501 } 11502 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11503 if (lastPackage != null) { 11504 pkgs.remove(lastPackage); 11505 } 11506 if (pkgs.size() > 0) { 11507 return pkgs.get(0); 11508 } 11509 } 11510 return null; 11511 } 11512 11513 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11514 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11515 userId, andCode ? 1 : 0, packageName); 11516 if (mSystemReady) { 11517 msg.sendToTarget(); 11518 } else { 11519 if (mPostSystemReadyMessages == null) { 11520 mPostSystemReadyMessages = new ArrayList<>(); 11521 } 11522 mPostSystemReadyMessages.add(msg); 11523 } 11524 } 11525 11526 void startCleaningPackages() { 11527 // reader 11528 if (!isExternalMediaAvailable()) { 11529 return; 11530 } 11531 synchronized (mPackages) { 11532 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11533 return; 11534 } 11535 } 11536 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11537 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11538 IActivityManager am = ActivityManagerNative.getDefault(); 11539 if (am != null) { 11540 try { 11541 am.startService(null, intent, null, mContext.getOpPackageName(), 11542 UserHandle.USER_SYSTEM); 11543 } catch (RemoteException e) { 11544 } 11545 } 11546 } 11547 11548 @Override 11549 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11550 int installFlags, String installerPackageName, int userId) { 11551 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11552 11553 final int callingUid = Binder.getCallingUid(); 11554 enforceCrossUserPermission(callingUid, userId, 11555 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11556 11557 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11558 try { 11559 if (observer != null) { 11560 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11561 } 11562 } catch (RemoteException re) { 11563 } 11564 return; 11565 } 11566 11567 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11568 installFlags |= PackageManager.INSTALL_FROM_ADB; 11569 11570 } else { 11571 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11572 // about installerPackageName. 11573 11574 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11575 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11576 } 11577 11578 UserHandle user; 11579 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11580 user = UserHandle.ALL; 11581 } else { 11582 user = new UserHandle(userId); 11583 } 11584 11585 // Only system components can circumvent runtime permissions when installing. 11586 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11587 && mContext.checkCallingOrSelfPermission(Manifest.permission 11588 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11589 throw new SecurityException("You need the " 11590 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11591 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11592 } 11593 11594 final File originFile = new File(originPath); 11595 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11596 11597 final Message msg = mHandler.obtainMessage(INIT_COPY); 11598 final VerificationInfo verificationInfo = new VerificationInfo( 11599 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11600 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11601 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11602 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11603 null /*certificates*/); 11604 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11605 msg.obj = params; 11606 11607 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11608 System.identityHashCode(msg.obj)); 11609 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11610 System.identityHashCode(msg.obj)); 11611 11612 mHandler.sendMessage(msg); 11613 } 11614 11615 void installStage(String packageName, File stagedDir, String stagedCid, 11616 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11617 String installerPackageName, int installerUid, UserHandle user, 11618 Certificate[][] certificates) { 11619 if (DEBUG_EPHEMERAL) { 11620 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11621 Slog.d(TAG, "Ephemeral install of " + packageName); 11622 } 11623 } 11624 final VerificationInfo verificationInfo = new VerificationInfo( 11625 sessionParams.originatingUri, sessionParams.referrerUri, 11626 sessionParams.originatingUid, installerUid); 11627 11628 final OriginInfo origin; 11629 if (stagedDir != null) { 11630 origin = OriginInfo.fromStagedFile(stagedDir); 11631 } else { 11632 origin = OriginInfo.fromStagedContainer(stagedCid); 11633 } 11634 11635 final Message msg = mHandler.obtainMessage(INIT_COPY); 11636 final InstallParams params = new InstallParams(origin, null, observer, 11637 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11638 verificationInfo, user, sessionParams.abiOverride, 11639 sessionParams.grantedRuntimePermissions, certificates); 11640 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11641 msg.obj = params; 11642 11643 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11644 System.identityHashCode(msg.obj)); 11645 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11646 System.identityHashCode(msg.obj)); 11647 11648 mHandler.sendMessage(msg); 11649 } 11650 11651 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11652 int userId) { 11653 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11654 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11655 } 11656 11657 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11658 int appId, int userId) { 11659 Bundle extras = new Bundle(1); 11660 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11661 11662 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11663 packageName, extras, 0, null, null, new int[] {userId}); 11664 try { 11665 IActivityManager am = ActivityManagerNative.getDefault(); 11666 if (isSystem && am.isUserRunning(userId, 0)) { 11667 // The just-installed/enabled app is bundled on the system, so presumed 11668 // to be able to run automatically without needing an explicit launch. 11669 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11670 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11671 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11672 .setPackage(packageName); 11673 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11674 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11675 } 11676 } catch (RemoteException e) { 11677 // shouldn't happen 11678 Slog.w(TAG, "Unable to bootstrap installed package", e); 11679 } 11680 } 11681 11682 @Override 11683 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11684 int userId) { 11685 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11686 PackageSetting pkgSetting; 11687 final int uid = Binder.getCallingUid(); 11688 enforceCrossUserPermission(uid, userId, 11689 true /* requireFullPermission */, true /* checkShell */, 11690 "setApplicationHiddenSetting for user " + userId); 11691 11692 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11693 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11694 return false; 11695 } 11696 11697 long callingId = Binder.clearCallingIdentity(); 11698 try { 11699 boolean sendAdded = false; 11700 boolean sendRemoved = false; 11701 // writer 11702 synchronized (mPackages) { 11703 pkgSetting = mSettings.mPackages.get(packageName); 11704 if (pkgSetting == null) { 11705 return false; 11706 } 11707 // Only allow protected packages to hide themselves. 11708 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11709 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11710 Slog.w(TAG, "Not hiding protected package: " + packageName); 11711 return false; 11712 } 11713 if (pkgSetting.getHidden(userId) != hidden) { 11714 pkgSetting.setHidden(hidden, userId); 11715 mSettings.writePackageRestrictionsLPr(userId); 11716 if (hidden) { 11717 sendRemoved = true; 11718 } else { 11719 sendAdded = true; 11720 } 11721 } 11722 } 11723 if (sendAdded) { 11724 sendPackageAddedForUser(packageName, pkgSetting, userId); 11725 return true; 11726 } 11727 if (sendRemoved) { 11728 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11729 "hiding pkg"); 11730 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11731 return true; 11732 } 11733 } finally { 11734 Binder.restoreCallingIdentity(callingId); 11735 } 11736 return false; 11737 } 11738 11739 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11740 int userId) { 11741 final PackageRemovedInfo info = new PackageRemovedInfo(); 11742 info.removedPackage = packageName; 11743 info.removedUsers = new int[] {userId}; 11744 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11745 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11746 } 11747 11748 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11749 if (pkgList.length > 0) { 11750 Bundle extras = new Bundle(1); 11751 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11752 11753 sendPackageBroadcast( 11754 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11755 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11756 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11757 new int[] {userId}); 11758 } 11759 } 11760 11761 /** 11762 * Returns true if application is not found or there was an error. Otherwise it returns 11763 * the hidden state of the package for the given user. 11764 */ 11765 @Override 11766 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11767 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11768 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11769 true /* requireFullPermission */, false /* checkShell */, 11770 "getApplicationHidden for user " + userId); 11771 PackageSetting pkgSetting; 11772 long callingId = Binder.clearCallingIdentity(); 11773 try { 11774 // writer 11775 synchronized (mPackages) { 11776 pkgSetting = mSettings.mPackages.get(packageName); 11777 if (pkgSetting == null) { 11778 return true; 11779 } 11780 return pkgSetting.getHidden(userId); 11781 } 11782 } finally { 11783 Binder.restoreCallingIdentity(callingId); 11784 } 11785 } 11786 11787 /** 11788 * @hide 11789 */ 11790 @Override 11791 public int installExistingPackageAsUser(String packageName, int userId) { 11792 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11793 null); 11794 PackageSetting pkgSetting; 11795 final int uid = Binder.getCallingUid(); 11796 enforceCrossUserPermission(uid, userId, 11797 true /* requireFullPermission */, true /* checkShell */, 11798 "installExistingPackage for user " + userId); 11799 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11800 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11801 } 11802 11803 long callingId = Binder.clearCallingIdentity(); 11804 try { 11805 boolean installed = false; 11806 11807 // writer 11808 synchronized (mPackages) { 11809 pkgSetting = mSettings.mPackages.get(packageName); 11810 if (pkgSetting == null) { 11811 return PackageManager.INSTALL_FAILED_INVALID_URI; 11812 } 11813 if (!pkgSetting.getInstalled(userId)) { 11814 pkgSetting.setInstalled(true, userId); 11815 pkgSetting.setHidden(false, userId); 11816 mSettings.writePackageRestrictionsLPr(userId); 11817 installed = true; 11818 } 11819 } 11820 11821 if (installed) { 11822 if (pkgSetting.pkg != null) { 11823 synchronized (mInstallLock) { 11824 // We don't need to freeze for a brand new install 11825 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11826 } 11827 } 11828 sendPackageAddedForUser(packageName, pkgSetting, userId); 11829 } 11830 } finally { 11831 Binder.restoreCallingIdentity(callingId); 11832 } 11833 11834 return PackageManager.INSTALL_SUCCEEDED; 11835 } 11836 11837 boolean isUserRestricted(int userId, String restrictionKey) { 11838 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11839 if (restrictions.getBoolean(restrictionKey, false)) { 11840 Log.w(TAG, "User is restricted: " + restrictionKey); 11841 return true; 11842 } 11843 return false; 11844 } 11845 11846 @Override 11847 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11848 int userId) { 11849 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11850 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11851 true /* requireFullPermission */, true /* checkShell */, 11852 "setPackagesSuspended for user " + userId); 11853 11854 if (ArrayUtils.isEmpty(packageNames)) { 11855 return packageNames; 11856 } 11857 11858 // List of package names for whom the suspended state has changed. 11859 List<String> changedPackages = new ArrayList<>(packageNames.length); 11860 // List of package names for whom the suspended state is not set as requested in this 11861 // method. 11862 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11863 long callingId = Binder.clearCallingIdentity(); 11864 try { 11865 for (int i = 0; i < packageNames.length; i++) { 11866 String packageName = packageNames[i]; 11867 boolean changed = false; 11868 final int appId; 11869 synchronized (mPackages) { 11870 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11871 if (pkgSetting == null) { 11872 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11873 + "\". Skipping suspending/un-suspending."); 11874 unactionedPackages.add(packageName); 11875 continue; 11876 } 11877 appId = pkgSetting.appId; 11878 if (pkgSetting.getSuspended(userId) != suspended) { 11879 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11880 unactionedPackages.add(packageName); 11881 continue; 11882 } 11883 pkgSetting.setSuspended(suspended, userId); 11884 mSettings.writePackageRestrictionsLPr(userId); 11885 changed = true; 11886 changedPackages.add(packageName); 11887 } 11888 } 11889 11890 if (changed && suspended) { 11891 killApplication(packageName, UserHandle.getUid(userId, appId), 11892 "suspending package"); 11893 } 11894 } 11895 } finally { 11896 Binder.restoreCallingIdentity(callingId); 11897 } 11898 11899 if (!changedPackages.isEmpty()) { 11900 sendPackagesSuspendedForUser(changedPackages.toArray( 11901 new String[changedPackages.size()]), userId, suspended); 11902 } 11903 11904 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11905 } 11906 11907 @Override 11908 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11909 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11910 true /* requireFullPermission */, false /* checkShell */, 11911 "isPackageSuspendedForUser for user " + userId); 11912 synchronized (mPackages) { 11913 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11914 if (pkgSetting == null) { 11915 throw new IllegalArgumentException("Unknown target package: " + packageName); 11916 } 11917 return pkgSetting.getSuspended(userId); 11918 } 11919 } 11920 11921 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11922 if (isPackageDeviceAdmin(packageName, userId)) { 11923 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11924 + "\": has an active device admin"); 11925 return false; 11926 } 11927 11928 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11929 if (packageName.equals(activeLauncherPackageName)) { 11930 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11931 + "\": contains the active launcher"); 11932 return false; 11933 } 11934 11935 if (packageName.equals(mRequiredInstallerPackage)) { 11936 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11937 + "\": required for package installation"); 11938 return false; 11939 } 11940 11941 if (packageName.equals(mRequiredVerifierPackage)) { 11942 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11943 + "\": required for package verification"); 11944 return false; 11945 } 11946 11947 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11948 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11949 + "\": is the default dialer"); 11950 return false; 11951 } 11952 11953 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11954 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11955 + "\": protected package"); 11956 return false; 11957 } 11958 11959 return true; 11960 } 11961 11962 private String getActiveLauncherPackageName(int userId) { 11963 Intent intent = new Intent(Intent.ACTION_MAIN); 11964 intent.addCategory(Intent.CATEGORY_HOME); 11965 ResolveInfo resolveInfo = resolveIntent( 11966 intent, 11967 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11968 PackageManager.MATCH_DEFAULT_ONLY, 11969 userId); 11970 11971 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11972 } 11973 11974 private String getDefaultDialerPackageName(int userId) { 11975 synchronized (mPackages) { 11976 return mSettings.getDefaultDialerPackageNameLPw(userId); 11977 } 11978 } 11979 11980 @Override 11981 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11982 mContext.enforceCallingOrSelfPermission( 11983 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11984 "Only package verification agents can verify applications"); 11985 11986 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11987 final PackageVerificationResponse response = new PackageVerificationResponse( 11988 verificationCode, Binder.getCallingUid()); 11989 msg.arg1 = id; 11990 msg.obj = response; 11991 mHandler.sendMessage(msg); 11992 } 11993 11994 @Override 11995 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11996 long millisecondsToDelay) { 11997 mContext.enforceCallingOrSelfPermission( 11998 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11999 "Only package verification agents can extend verification timeouts"); 12000 12001 final PackageVerificationState state = mPendingVerification.get(id); 12002 final PackageVerificationResponse response = new PackageVerificationResponse( 12003 verificationCodeAtTimeout, Binder.getCallingUid()); 12004 12005 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12006 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12007 } 12008 if (millisecondsToDelay < 0) { 12009 millisecondsToDelay = 0; 12010 } 12011 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12012 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12013 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12014 } 12015 12016 if ((state != null) && !state.timeoutExtended()) { 12017 state.extendTimeout(); 12018 12019 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12020 msg.arg1 = id; 12021 msg.obj = response; 12022 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12023 } 12024 } 12025 12026 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12027 int verificationCode, UserHandle user) { 12028 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12029 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12030 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12031 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12032 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12033 12034 mContext.sendBroadcastAsUser(intent, user, 12035 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12036 } 12037 12038 private ComponentName matchComponentForVerifier(String packageName, 12039 List<ResolveInfo> receivers) { 12040 ActivityInfo targetReceiver = null; 12041 12042 final int NR = receivers.size(); 12043 for (int i = 0; i < NR; i++) { 12044 final ResolveInfo info = receivers.get(i); 12045 if (info.activityInfo == null) { 12046 continue; 12047 } 12048 12049 if (packageName.equals(info.activityInfo.packageName)) { 12050 targetReceiver = info.activityInfo; 12051 break; 12052 } 12053 } 12054 12055 if (targetReceiver == null) { 12056 return null; 12057 } 12058 12059 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12060 } 12061 12062 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12063 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12064 if (pkgInfo.verifiers.length == 0) { 12065 return null; 12066 } 12067 12068 final int N = pkgInfo.verifiers.length; 12069 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12070 for (int i = 0; i < N; i++) { 12071 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12072 12073 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12074 receivers); 12075 if (comp == null) { 12076 continue; 12077 } 12078 12079 final int verifierUid = getUidForVerifier(verifierInfo); 12080 if (verifierUid == -1) { 12081 continue; 12082 } 12083 12084 if (DEBUG_VERIFY) { 12085 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12086 + " with the correct signature"); 12087 } 12088 sufficientVerifiers.add(comp); 12089 verificationState.addSufficientVerifier(verifierUid); 12090 } 12091 12092 return sufficientVerifiers; 12093 } 12094 12095 private int getUidForVerifier(VerifierInfo verifierInfo) { 12096 synchronized (mPackages) { 12097 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12098 if (pkg == null) { 12099 return -1; 12100 } else if (pkg.mSignatures.length != 1) { 12101 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12102 + " has more than one signature; ignoring"); 12103 return -1; 12104 } 12105 12106 /* 12107 * If the public key of the package's signature does not match 12108 * our expected public key, then this is a different package and 12109 * we should skip. 12110 */ 12111 12112 final byte[] expectedPublicKey; 12113 try { 12114 final Signature verifierSig = pkg.mSignatures[0]; 12115 final PublicKey publicKey = verifierSig.getPublicKey(); 12116 expectedPublicKey = publicKey.getEncoded(); 12117 } catch (CertificateException e) { 12118 return -1; 12119 } 12120 12121 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12122 12123 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12124 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12125 + " does not have the expected public key; ignoring"); 12126 return -1; 12127 } 12128 12129 return pkg.applicationInfo.uid; 12130 } 12131 } 12132 12133 @Override 12134 public void finishPackageInstall(int token, boolean didLaunch) { 12135 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12136 12137 if (DEBUG_INSTALL) { 12138 Slog.v(TAG, "BM finishing package install for " + token); 12139 } 12140 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12141 12142 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12143 mHandler.sendMessage(msg); 12144 } 12145 12146 /** 12147 * Get the verification agent timeout. 12148 * 12149 * @return verification timeout in milliseconds 12150 */ 12151 private long getVerificationTimeout() { 12152 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12153 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12154 DEFAULT_VERIFICATION_TIMEOUT); 12155 } 12156 12157 /** 12158 * Get the default verification agent response code. 12159 * 12160 * @return default verification response code 12161 */ 12162 private int getDefaultVerificationResponse() { 12163 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12164 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12165 DEFAULT_VERIFICATION_RESPONSE); 12166 } 12167 12168 /** 12169 * Check whether or not package verification has been enabled. 12170 * 12171 * @return true if verification should be performed 12172 */ 12173 private boolean isVerificationEnabled(int userId, int installFlags) { 12174 if (!DEFAULT_VERIFY_ENABLE) { 12175 return false; 12176 } 12177 // Ephemeral apps don't get the full verification treatment 12178 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12179 if (DEBUG_EPHEMERAL) { 12180 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12181 } 12182 return false; 12183 } 12184 12185 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12186 12187 // Check if installing from ADB 12188 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12189 // Do not run verification in a test harness environment 12190 if (ActivityManager.isRunningInTestHarness()) { 12191 return false; 12192 } 12193 if (ensureVerifyAppsEnabled) { 12194 return true; 12195 } 12196 // Check if the developer does not want package verification for ADB installs 12197 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12198 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12199 return false; 12200 } 12201 } 12202 12203 if (ensureVerifyAppsEnabled) { 12204 return true; 12205 } 12206 12207 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12208 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12209 } 12210 12211 @Override 12212 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12213 throws RemoteException { 12214 mContext.enforceCallingOrSelfPermission( 12215 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12216 "Only intentfilter verification agents can verify applications"); 12217 12218 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12219 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12220 Binder.getCallingUid(), verificationCode, failedDomains); 12221 msg.arg1 = id; 12222 msg.obj = response; 12223 mHandler.sendMessage(msg); 12224 } 12225 12226 @Override 12227 public int getIntentVerificationStatus(String packageName, int userId) { 12228 synchronized (mPackages) { 12229 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12230 } 12231 } 12232 12233 @Override 12234 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12235 mContext.enforceCallingOrSelfPermission( 12236 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12237 12238 boolean result = false; 12239 synchronized (mPackages) { 12240 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12241 } 12242 if (result) { 12243 scheduleWritePackageRestrictionsLocked(userId); 12244 } 12245 return result; 12246 } 12247 12248 @Override 12249 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12250 String packageName) { 12251 synchronized (mPackages) { 12252 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12253 } 12254 } 12255 12256 @Override 12257 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12258 if (TextUtils.isEmpty(packageName)) { 12259 return ParceledListSlice.emptyList(); 12260 } 12261 synchronized (mPackages) { 12262 PackageParser.Package pkg = mPackages.get(packageName); 12263 if (pkg == null || pkg.activities == null) { 12264 return ParceledListSlice.emptyList(); 12265 } 12266 final int count = pkg.activities.size(); 12267 ArrayList<IntentFilter> result = new ArrayList<>(); 12268 for (int n=0; n<count; n++) { 12269 PackageParser.Activity activity = pkg.activities.get(n); 12270 if (activity.intents != null && activity.intents.size() > 0) { 12271 result.addAll(activity.intents); 12272 } 12273 } 12274 return new ParceledListSlice<>(result); 12275 } 12276 } 12277 12278 @Override 12279 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12280 mContext.enforceCallingOrSelfPermission( 12281 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12282 12283 synchronized (mPackages) { 12284 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12285 if (packageName != null) { 12286 result |= updateIntentVerificationStatus(packageName, 12287 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12288 userId); 12289 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12290 packageName, userId); 12291 } 12292 return result; 12293 } 12294 } 12295 12296 @Override 12297 public String getDefaultBrowserPackageName(int userId) { 12298 synchronized (mPackages) { 12299 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12300 } 12301 } 12302 12303 /** 12304 * Get the "allow unknown sources" setting. 12305 * 12306 * @return the current "allow unknown sources" setting 12307 */ 12308 private int getUnknownSourcesSettings() { 12309 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12310 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12311 -1); 12312 } 12313 12314 @Override 12315 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12316 final int uid = Binder.getCallingUid(); 12317 // writer 12318 synchronized (mPackages) { 12319 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12320 if (targetPackageSetting == null) { 12321 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12322 } 12323 12324 PackageSetting installerPackageSetting; 12325 if (installerPackageName != null) { 12326 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12327 if (installerPackageSetting == null) { 12328 throw new IllegalArgumentException("Unknown installer package: " 12329 + installerPackageName); 12330 } 12331 } else { 12332 installerPackageSetting = null; 12333 } 12334 12335 Signature[] callerSignature; 12336 Object obj = mSettings.getUserIdLPr(uid); 12337 if (obj != null) { 12338 if (obj instanceof SharedUserSetting) { 12339 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12340 } else if (obj instanceof PackageSetting) { 12341 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12342 } else { 12343 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12344 } 12345 } else { 12346 throw new SecurityException("Unknown calling UID: " + uid); 12347 } 12348 12349 // Verify: can't set installerPackageName to a package that is 12350 // not signed with the same cert as the caller. 12351 if (installerPackageSetting != null) { 12352 if (compareSignatures(callerSignature, 12353 installerPackageSetting.signatures.mSignatures) 12354 != PackageManager.SIGNATURE_MATCH) { 12355 throw new SecurityException( 12356 "Caller does not have same cert as new installer package " 12357 + installerPackageName); 12358 } 12359 } 12360 12361 // Verify: if target already has an installer package, it must 12362 // be signed with the same cert as the caller. 12363 if (targetPackageSetting.installerPackageName != null) { 12364 PackageSetting setting = mSettings.mPackages.get( 12365 targetPackageSetting.installerPackageName); 12366 // If the currently set package isn't valid, then it's always 12367 // okay to change it. 12368 if (setting != null) { 12369 if (compareSignatures(callerSignature, 12370 setting.signatures.mSignatures) 12371 != PackageManager.SIGNATURE_MATCH) { 12372 throw new SecurityException( 12373 "Caller does not have same cert as old installer package " 12374 + targetPackageSetting.installerPackageName); 12375 } 12376 } 12377 } 12378 12379 // Okay! 12380 targetPackageSetting.installerPackageName = installerPackageName; 12381 if (installerPackageName != null) { 12382 mSettings.mInstallerPackages.add(installerPackageName); 12383 } 12384 scheduleWriteSettingsLocked(); 12385 } 12386 } 12387 12388 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12389 // Queue up an async operation since the package installation may take a little while. 12390 mHandler.post(new Runnable() { 12391 public void run() { 12392 mHandler.removeCallbacks(this); 12393 // Result object to be returned 12394 PackageInstalledInfo res = new PackageInstalledInfo(); 12395 res.setReturnCode(currentStatus); 12396 res.uid = -1; 12397 res.pkg = null; 12398 res.removedInfo = null; 12399 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12400 args.doPreInstall(res.returnCode); 12401 synchronized (mInstallLock) { 12402 installPackageTracedLI(args, res); 12403 } 12404 args.doPostInstall(res.returnCode, res.uid); 12405 } 12406 12407 // A restore should be performed at this point if (a) the install 12408 // succeeded, (b) the operation is not an update, and (c) the new 12409 // package has not opted out of backup participation. 12410 final boolean update = res.removedInfo != null 12411 && res.removedInfo.removedPackage != null; 12412 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12413 boolean doRestore = !update 12414 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12415 12416 // Set up the post-install work request bookkeeping. This will be used 12417 // and cleaned up by the post-install event handling regardless of whether 12418 // there's a restore pass performed. Token values are >= 1. 12419 int token; 12420 if (mNextInstallToken < 0) mNextInstallToken = 1; 12421 token = mNextInstallToken++; 12422 12423 PostInstallData data = new PostInstallData(args, res); 12424 mRunningInstalls.put(token, data); 12425 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12426 12427 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12428 // Pass responsibility to the Backup Manager. It will perform a 12429 // restore if appropriate, then pass responsibility back to the 12430 // Package Manager to run the post-install observer callbacks 12431 // and broadcasts. 12432 IBackupManager bm = IBackupManager.Stub.asInterface( 12433 ServiceManager.getService(Context.BACKUP_SERVICE)); 12434 if (bm != null) { 12435 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12436 + " to BM for possible restore"); 12437 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12438 try { 12439 // TODO: http://b/22388012 12440 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12441 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12442 } else { 12443 doRestore = false; 12444 } 12445 } catch (RemoteException e) { 12446 // can't happen; the backup manager is local 12447 } catch (Exception e) { 12448 Slog.e(TAG, "Exception trying to enqueue restore", e); 12449 doRestore = false; 12450 } 12451 } else { 12452 Slog.e(TAG, "Backup Manager not found!"); 12453 doRestore = false; 12454 } 12455 } 12456 12457 if (!doRestore) { 12458 // No restore possible, or the Backup Manager was mysteriously not 12459 // available -- just fire the post-install work request directly. 12460 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12461 12462 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12463 12464 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12465 mHandler.sendMessage(msg); 12466 } 12467 } 12468 }); 12469 } 12470 12471 /** 12472 * Callback from PackageSettings whenever an app is first transitioned out of the 12473 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12474 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12475 * here whether the app is the target of an ongoing install, and only send the 12476 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12477 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12478 * handling. 12479 */ 12480 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12481 // Serialize this with the rest of the install-process message chain. In the 12482 // restore-at-install case, this Runnable will necessarily run before the 12483 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12484 // are coherent. In the non-restore case, the app has already completed install 12485 // and been launched through some other means, so it is not in a problematic 12486 // state for observers to see the FIRST_LAUNCH signal. 12487 mHandler.post(new Runnable() { 12488 @Override 12489 public void run() { 12490 for (int i = 0; i < mRunningInstalls.size(); i++) { 12491 final PostInstallData data = mRunningInstalls.valueAt(i); 12492 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12493 // right package; but is it for the right user? 12494 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12495 if (userId == data.res.newUsers[uIndex]) { 12496 if (DEBUG_BACKUP) { 12497 Slog.i(TAG, "Package " + pkgName 12498 + " being restored so deferring FIRST_LAUNCH"); 12499 } 12500 return; 12501 } 12502 } 12503 } 12504 } 12505 // didn't find it, so not being restored 12506 if (DEBUG_BACKUP) { 12507 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12508 } 12509 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12510 } 12511 }); 12512 } 12513 12514 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12515 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12516 installerPkg, null, userIds); 12517 } 12518 12519 private abstract class HandlerParams { 12520 private static final int MAX_RETRIES = 4; 12521 12522 /** 12523 * Number of times startCopy() has been attempted and had a non-fatal 12524 * error. 12525 */ 12526 private int mRetries = 0; 12527 12528 /** User handle for the user requesting the information or installation. */ 12529 private final UserHandle mUser; 12530 String traceMethod; 12531 int traceCookie; 12532 12533 HandlerParams(UserHandle user) { 12534 mUser = user; 12535 } 12536 12537 UserHandle getUser() { 12538 return mUser; 12539 } 12540 12541 HandlerParams setTraceMethod(String traceMethod) { 12542 this.traceMethod = traceMethod; 12543 return this; 12544 } 12545 12546 HandlerParams setTraceCookie(int traceCookie) { 12547 this.traceCookie = traceCookie; 12548 return this; 12549 } 12550 12551 final boolean startCopy() { 12552 boolean res; 12553 try { 12554 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12555 12556 if (++mRetries > MAX_RETRIES) { 12557 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12558 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12559 handleServiceError(); 12560 return false; 12561 } else { 12562 handleStartCopy(); 12563 res = true; 12564 } 12565 } catch (RemoteException e) { 12566 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12567 mHandler.sendEmptyMessage(MCS_RECONNECT); 12568 res = false; 12569 } 12570 handleReturnCode(); 12571 return res; 12572 } 12573 12574 final void serviceError() { 12575 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12576 handleServiceError(); 12577 handleReturnCode(); 12578 } 12579 12580 abstract void handleStartCopy() throws RemoteException; 12581 abstract void handleServiceError(); 12582 abstract void handleReturnCode(); 12583 } 12584 12585 class MeasureParams extends HandlerParams { 12586 private final PackageStats mStats; 12587 private boolean mSuccess; 12588 12589 private final IPackageStatsObserver mObserver; 12590 12591 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12592 super(new UserHandle(stats.userHandle)); 12593 mObserver = observer; 12594 mStats = stats; 12595 } 12596 12597 @Override 12598 public String toString() { 12599 return "MeasureParams{" 12600 + Integer.toHexString(System.identityHashCode(this)) 12601 + " " + mStats.packageName + "}"; 12602 } 12603 12604 @Override 12605 void handleStartCopy() throws RemoteException { 12606 synchronized (mInstallLock) { 12607 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12608 } 12609 12610 if (mSuccess) { 12611 boolean mounted = false; 12612 try { 12613 final String status = Environment.getExternalStorageState(); 12614 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12615 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12616 } catch (Exception e) { 12617 } 12618 12619 if (mounted) { 12620 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12621 12622 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12623 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12624 12625 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12626 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12627 12628 // Always subtract cache size, since it's a subdirectory 12629 mStats.externalDataSize -= mStats.externalCacheSize; 12630 12631 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12632 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12633 12634 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12635 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12636 } 12637 } 12638 } 12639 12640 @Override 12641 void handleReturnCode() { 12642 if (mObserver != null) { 12643 try { 12644 mObserver.onGetStatsCompleted(mStats, mSuccess); 12645 } catch (RemoteException e) { 12646 Slog.i(TAG, "Observer no longer exists."); 12647 } 12648 } 12649 } 12650 12651 @Override 12652 void handleServiceError() { 12653 Slog.e(TAG, "Could not measure application " + mStats.packageName 12654 + " external storage"); 12655 } 12656 } 12657 12658 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12659 throws RemoteException { 12660 long result = 0; 12661 for (File path : paths) { 12662 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12663 } 12664 return result; 12665 } 12666 12667 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12668 for (File path : paths) { 12669 try { 12670 mcs.clearDirectory(path.getAbsolutePath()); 12671 } catch (RemoteException e) { 12672 } 12673 } 12674 } 12675 12676 static class OriginInfo { 12677 /** 12678 * Location where install is coming from, before it has been 12679 * copied/renamed into place. This could be a single monolithic APK 12680 * file, or a cluster directory. This location may be untrusted. 12681 */ 12682 final File file; 12683 final String cid; 12684 12685 /** 12686 * Flag indicating that {@link #file} or {@link #cid} has already been 12687 * staged, meaning downstream users don't need to defensively copy the 12688 * contents. 12689 */ 12690 final boolean staged; 12691 12692 /** 12693 * Flag indicating that {@link #file} or {@link #cid} is an already 12694 * installed app that is being moved. 12695 */ 12696 final boolean existing; 12697 12698 final String resolvedPath; 12699 final File resolvedFile; 12700 12701 static OriginInfo fromNothing() { 12702 return new OriginInfo(null, null, false, false); 12703 } 12704 12705 static OriginInfo fromUntrustedFile(File file) { 12706 return new OriginInfo(file, null, false, false); 12707 } 12708 12709 static OriginInfo fromExistingFile(File file) { 12710 return new OriginInfo(file, null, false, true); 12711 } 12712 12713 static OriginInfo fromStagedFile(File file) { 12714 return new OriginInfo(file, null, true, false); 12715 } 12716 12717 static OriginInfo fromStagedContainer(String cid) { 12718 return new OriginInfo(null, cid, true, false); 12719 } 12720 12721 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12722 this.file = file; 12723 this.cid = cid; 12724 this.staged = staged; 12725 this.existing = existing; 12726 12727 if (cid != null) { 12728 resolvedPath = PackageHelper.getSdDir(cid); 12729 resolvedFile = new File(resolvedPath); 12730 } else if (file != null) { 12731 resolvedPath = file.getAbsolutePath(); 12732 resolvedFile = file; 12733 } else { 12734 resolvedPath = null; 12735 resolvedFile = null; 12736 } 12737 } 12738 } 12739 12740 static class MoveInfo { 12741 final int moveId; 12742 final String fromUuid; 12743 final String toUuid; 12744 final String packageName; 12745 final String dataAppName; 12746 final int appId; 12747 final String seinfo; 12748 final int targetSdkVersion; 12749 12750 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12751 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12752 this.moveId = moveId; 12753 this.fromUuid = fromUuid; 12754 this.toUuid = toUuid; 12755 this.packageName = packageName; 12756 this.dataAppName = dataAppName; 12757 this.appId = appId; 12758 this.seinfo = seinfo; 12759 this.targetSdkVersion = targetSdkVersion; 12760 } 12761 } 12762 12763 static class VerificationInfo { 12764 /** A constant used to indicate that a uid value is not present. */ 12765 public static final int NO_UID = -1; 12766 12767 /** URI referencing where the package was downloaded from. */ 12768 final Uri originatingUri; 12769 12770 /** HTTP referrer URI associated with the originatingURI. */ 12771 final Uri referrer; 12772 12773 /** UID of the application that the install request originated from. */ 12774 final int originatingUid; 12775 12776 /** UID of application requesting the install */ 12777 final int installerUid; 12778 12779 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12780 this.originatingUri = originatingUri; 12781 this.referrer = referrer; 12782 this.originatingUid = originatingUid; 12783 this.installerUid = installerUid; 12784 } 12785 } 12786 12787 class InstallParams extends HandlerParams { 12788 final OriginInfo origin; 12789 final MoveInfo move; 12790 final IPackageInstallObserver2 observer; 12791 int installFlags; 12792 final String installerPackageName; 12793 final String volumeUuid; 12794 private InstallArgs mArgs; 12795 private int mRet; 12796 final String packageAbiOverride; 12797 final String[] grantedRuntimePermissions; 12798 final VerificationInfo verificationInfo; 12799 final Certificate[][] certificates; 12800 12801 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12802 int installFlags, String installerPackageName, String volumeUuid, 12803 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12804 String[] grantedPermissions, Certificate[][] certificates) { 12805 super(user); 12806 this.origin = origin; 12807 this.move = move; 12808 this.observer = observer; 12809 this.installFlags = installFlags; 12810 this.installerPackageName = installerPackageName; 12811 this.volumeUuid = volumeUuid; 12812 this.verificationInfo = verificationInfo; 12813 this.packageAbiOverride = packageAbiOverride; 12814 this.grantedRuntimePermissions = grantedPermissions; 12815 this.certificates = certificates; 12816 } 12817 12818 @Override 12819 public String toString() { 12820 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12821 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12822 } 12823 12824 private int installLocationPolicy(PackageInfoLite pkgLite) { 12825 String packageName = pkgLite.packageName; 12826 int installLocation = pkgLite.installLocation; 12827 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12828 // reader 12829 synchronized (mPackages) { 12830 // Currently installed package which the new package is attempting to replace or 12831 // null if no such package is installed. 12832 PackageParser.Package installedPkg = mPackages.get(packageName); 12833 // Package which currently owns the data which the new package will own if installed. 12834 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12835 // will be null whereas dataOwnerPkg will contain information about the package 12836 // which was uninstalled while keeping its data. 12837 PackageParser.Package dataOwnerPkg = installedPkg; 12838 if (dataOwnerPkg == null) { 12839 PackageSetting ps = mSettings.mPackages.get(packageName); 12840 if (ps != null) { 12841 dataOwnerPkg = ps.pkg; 12842 } 12843 } 12844 12845 if (dataOwnerPkg != null) { 12846 // If installed, the package will get access to data left on the device by its 12847 // predecessor. As a security measure, this is permited only if this is not a 12848 // version downgrade or if the predecessor package is marked as debuggable and 12849 // a downgrade is explicitly requested. 12850 // 12851 // On debuggable platform builds, downgrades are permitted even for 12852 // non-debuggable packages to make testing easier. Debuggable platform builds do 12853 // not offer security guarantees and thus it's OK to disable some security 12854 // mechanisms to make debugging/testing easier on those builds. However, even on 12855 // debuggable builds downgrades of packages are permitted only if requested via 12856 // installFlags. This is because we aim to keep the behavior of debuggable 12857 // platform builds as close as possible to the behavior of non-debuggable 12858 // platform builds. 12859 final boolean downgradeRequested = 12860 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12861 final boolean packageDebuggable = 12862 (dataOwnerPkg.applicationInfo.flags 12863 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12864 final boolean downgradePermitted = 12865 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12866 if (!downgradePermitted) { 12867 try { 12868 checkDowngrade(dataOwnerPkg, pkgLite); 12869 } catch (PackageManagerException e) { 12870 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12871 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12872 } 12873 } 12874 } 12875 12876 if (installedPkg != null) { 12877 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12878 // Check for updated system application. 12879 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12880 if (onSd) { 12881 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12882 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12883 } 12884 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12885 } else { 12886 if (onSd) { 12887 // Install flag overrides everything. 12888 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12889 } 12890 // If current upgrade specifies particular preference 12891 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12892 // Application explicitly specified internal. 12893 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12894 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12895 // App explictly prefers external. Let policy decide 12896 } else { 12897 // Prefer previous location 12898 if (isExternal(installedPkg)) { 12899 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12900 } 12901 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12902 } 12903 } 12904 } else { 12905 // Invalid install. Return error code 12906 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12907 } 12908 } 12909 } 12910 // All the special cases have been taken care of. 12911 // Return result based on recommended install location. 12912 if (onSd) { 12913 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12914 } 12915 return pkgLite.recommendedInstallLocation; 12916 } 12917 12918 /* 12919 * Invoke remote method to get package information and install 12920 * location values. Override install location based on default 12921 * policy if needed and then create install arguments based 12922 * on the install location. 12923 */ 12924 public void handleStartCopy() throws RemoteException { 12925 int ret = PackageManager.INSTALL_SUCCEEDED; 12926 12927 // If we're already staged, we've firmly committed to an install location 12928 if (origin.staged) { 12929 if (origin.file != null) { 12930 installFlags |= PackageManager.INSTALL_INTERNAL; 12931 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12932 } else if (origin.cid != null) { 12933 installFlags |= PackageManager.INSTALL_EXTERNAL; 12934 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12935 } else { 12936 throw new IllegalStateException("Invalid stage location"); 12937 } 12938 } 12939 12940 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12941 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12942 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12943 PackageInfoLite pkgLite = null; 12944 12945 if (onInt && onSd) { 12946 // Check if both bits are set. 12947 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12948 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12949 } else if (onSd && ephemeral) { 12950 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12951 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12952 } else { 12953 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12954 packageAbiOverride); 12955 12956 if (DEBUG_EPHEMERAL && ephemeral) { 12957 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12958 } 12959 12960 /* 12961 * If we have too little free space, try to free cache 12962 * before giving up. 12963 */ 12964 if (!origin.staged && pkgLite.recommendedInstallLocation 12965 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12966 // TODO: focus freeing disk space on the target device 12967 final StorageManager storage = StorageManager.from(mContext); 12968 final long lowThreshold = storage.getStorageLowBytes( 12969 Environment.getDataDirectory()); 12970 12971 final long sizeBytes = mContainerService.calculateInstalledSize( 12972 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12973 12974 try { 12975 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12976 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12977 installFlags, packageAbiOverride); 12978 } catch (InstallerException e) { 12979 Slog.w(TAG, "Failed to free cache", e); 12980 } 12981 12982 /* 12983 * The cache free must have deleted the file we 12984 * downloaded to install. 12985 * 12986 * TODO: fix the "freeCache" call to not delete 12987 * the file we care about. 12988 */ 12989 if (pkgLite.recommendedInstallLocation 12990 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12991 pkgLite.recommendedInstallLocation 12992 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12993 } 12994 } 12995 } 12996 12997 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12998 int loc = pkgLite.recommendedInstallLocation; 12999 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13000 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13001 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13002 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13003 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13004 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13005 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13006 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13007 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13008 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13009 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13010 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13011 } else { 13012 // Override with defaults if needed. 13013 loc = installLocationPolicy(pkgLite); 13014 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13015 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13016 } else if (!onSd && !onInt) { 13017 // Override install location with flags 13018 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13019 // Set the flag to install on external media. 13020 installFlags |= PackageManager.INSTALL_EXTERNAL; 13021 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13022 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13023 if (DEBUG_EPHEMERAL) { 13024 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13025 } 13026 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13027 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13028 |PackageManager.INSTALL_INTERNAL); 13029 } else { 13030 // Make sure the flag for installing on external 13031 // media is unset 13032 installFlags |= PackageManager.INSTALL_INTERNAL; 13033 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13034 } 13035 } 13036 } 13037 } 13038 13039 final InstallArgs args = createInstallArgs(this); 13040 mArgs = args; 13041 13042 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13043 // TODO: http://b/22976637 13044 // Apps installed for "all" users use the device owner to verify the app 13045 UserHandle verifierUser = getUser(); 13046 if (verifierUser == UserHandle.ALL) { 13047 verifierUser = UserHandle.SYSTEM; 13048 } 13049 13050 /* 13051 * Determine if we have any installed package verifiers. If we 13052 * do, then we'll defer to them to verify the packages. 13053 */ 13054 final int requiredUid = mRequiredVerifierPackage == null ? -1 13055 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13056 verifierUser.getIdentifier()); 13057 if (!origin.existing && requiredUid != -1 13058 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13059 final Intent verification = new Intent( 13060 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13061 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13062 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13063 PACKAGE_MIME_TYPE); 13064 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13065 13066 // Query all live verifiers based on current user state 13067 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13068 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13069 13070 if (DEBUG_VERIFY) { 13071 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13072 + verification.toString() + " with " + pkgLite.verifiers.length 13073 + " optional verifiers"); 13074 } 13075 13076 final int verificationId = mPendingVerificationToken++; 13077 13078 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13079 13080 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13081 installerPackageName); 13082 13083 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13084 installFlags); 13085 13086 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13087 pkgLite.packageName); 13088 13089 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13090 pkgLite.versionCode); 13091 13092 if (verificationInfo != null) { 13093 if (verificationInfo.originatingUri != null) { 13094 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13095 verificationInfo.originatingUri); 13096 } 13097 if (verificationInfo.referrer != null) { 13098 verification.putExtra(Intent.EXTRA_REFERRER, 13099 verificationInfo.referrer); 13100 } 13101 if (verificationInfo.originatingUid >= 0) { 13102 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13103 verificationInfo.originatingUid); 13104 } 13105 if (verificationInfo.installerUid >= 0) { 13106 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13107 verificationInfo.installerUid); 13108 } 13109 } 13110 13111 final PackageVerificationState verificationState = new PackageVerificationState( 13112 requiredUid, args); 13113 13114 mPendingVerification.append(verificationId, verificationState); 13115 13116 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13117 receivers, verificationState); 13118 13119 /* 13120 * If any sufficient verifiers were listed in the package 13121 * manifest, attempt to ask them. 13122 */ 13123 if (sufficientVerifiers != null) { 13124 final int N = sufficientVerifiers.size(); 13125 if (N == 0) { 13126 Slog.i(TAG, "Additional verifiers required, but none installed."); 13127 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13128 } else { 13129 for (int i = 0; i < N; i++) { 13130 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13131 13132 final Intent sufficientIntent = new Intent(verification); 13133 sufficientIntent.setComponent(verifierComponent); 13134 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13135 } 13136 } 13137 } 13138 13139 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13140 mRequiredVerifierPackage, receivers); 13141 if (ret == PackageManager.INSTALL_SUCCEEDED 13142 && mRequiredVerifierPackage != null) { 13143 Trace.asyncTraceBegin( 13144 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13145 /* 13146 * Send the intent to the required verification agent, 13147 * but only start the verification timeout after the 13148 * target BroadcastReceivers have run. 13149 */ 13150 verification.setComponent(requiredVerifierComponent); 13151 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13152 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13153 new BroadcastReceiver() { 13154 @Override 13155 public void onReceive(Context context, Intent intent) { 13156 final Message msg = mHandler 13157 .obtainMessage(CHECK_PENDING_VERIFICATION); 13158 msg.arg1 = verificationId; 13159 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13160 } 13161 }, null, 0, null, null); 13162 13163 /* 13164 * We don't want the copy to proceed until verification 13165 * succeeds, so null out this field. 13166 */ 13167 mArgs = null; 13168 } 13169 } else { 13170 /* 13171 * No package verification is enabled, so immediately start 13172 * the remote call to initiate copy using temporary file. 13173 */ 13174 ret = args.copyApk(mContainerService, true); 13175 } 13176 } 13177 13178 mRet = ret; 13179 } 13180 13181 @Override 13182 void handleReturnCode() { 13183 // If mArgs is null, then MCS couldn't be reached. When it 13184 // reconnects, it will try again to install. At that point, this 13185 // will succeed. 13186 if (mArgs != null) { 13187 processPendingInstall(mArgs, mRet); 13188 } 13189 } 13190 13191 @Override 13192 void handleServiceError() { 13193 mArgs = createInstallArgs(this); 13194 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13195 } 13196 13197 public boolean isForwardLocked() { 13198 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13199 } 13200 } 13201 13202 /** 13203 * Used during creation of InstallArgs 13204 * 13205 * @param installFlags package installation flags 13206 * @return true if should be installed on external storage 13207 */ 13208 private static boolean installOnExternalAsec(int installFlags) { 13209 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13210 return false; 13211 } 13212 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13213 return true; 13214 } 13215 return false; 13216 } 13217 13218 /** 13219 * Used during creation of InstallArgs 13220 * 13221 * @param installFlags package installation flags 13222 * @return true if should be installed as forward locked 13223 */ 13224 private static boolean installForwardLocked(int installFlags) { 13225 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13226 } 13227 13228 private InstallArgs createInstallArgs(InstallParams params) { 13229 if (params.move != null) { 13230 return new MoveInstallArgs(params); 13231 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13232 return new AsecInstallArgs(params); 13233 } else { 13234 return new FileInstallArgs(params); 13235 } 13236 } 13237 13238 /** 13239 * Create args that describe an existing installed package. Typically used 13240 * when cleaning up old installs, or used as a move source. 13241 */ 13242 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13243 String resourcePath, String[] instructionSets) { 13244 final boolean isInAsec; 13245 if (installOnExternalAsec(installFlags)) { 13246 /* Apps on SD card are always in ASEC containers. */ 13247 isInAsec = true; 13248 } else if (installForwardLocked(installFlags) 13249 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13250 /* 13251 * Forward-locked apps are only in ASEC containers if they're the 13252 * new style 13253 */ 13254 isInAsec = true; 13255 } else { 13256 isInAsec = false; 13257 } 13258 13259 if (isInAsec) { 13260 return new AsecInstallArgs(codePath, instructionSets, 13261 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13262 } else { 13263 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13264 } 13265 } 13266 13267 static abstract class InstallArgs { 13268 /** @see InstallParams#origin */ 13269 final OriginInfo origin; 13270 /** @see InstallParams#move */ 13271 final MoveInfo move; 13272 13273 final IPackageInstallObserver2 observer; 13274 // Always refers to PackageManager flags only 13275 final int installFlags; 13276 final String installerPackageName; 13277 final String volumeUuid; 13278 final UserHandle user; 13279 final String abiOverride; 13280 final String[] installGrantPermissions; 13281 /** If non-null, drop an async trace when the install completes */ 13282 final String traceMethod; 13283 final int traceCookie; 13284 final Certificate[][] certificates; 13285 13286 // The list of instruction sets supported by this app. This is currently 13287 // only used during the rmdex() phase to clean up resources. We can get rid of this 13288 // if we move dex files under the common app path. 13289 /* nullable */ String[] instructionSets; 13290 13291 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13292 int installFlags, String installerPackageName, String volumeUuid, 13293 UserHandle user, String[] instructionSets, 13294 String abiOverride, String[] installGrantPermissions, 13295 String traceMethod, int traceCookie, Certificate[][] certificates) { 13296 this.origin = origin; 13297 this.move = move; 13298 this.installFlags = installFlags; 13299 this.observer = observer; 13300 this.installerPackageName = installerPackageName; 13301 this.volumeUuid = volumeUuid; 13302 this.user = user; 13303 this.instructionSets = instructionSets; 13304 this.abiOverride = abiOverride; 13305 this.installGrantPermissions = installGrantPermissions; 13306 this.traceMethod = traceMethod; 13307 this.traceCookie = traceCookie; 13308 this.certificates = certificates; 13309 } 13310 13311 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13312 abstract int doPreInstall(int status); 13313 13314 /** 13315 * Rename package into final resting place. All paths on the given 13316 * scanned package should be updated to reflect the rename. 13317 */ 13318 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13319 abstract int doPostInstall(int status, int uid); 13320 13321 /** @see PackageSettingBase#codePathString */ 13322 abstract String getCodePath(); 13323 /** @see PackageSettingBase#resourcePathString */ 13324 abstract String getResourcePath(); 13325 13326 // Need installer lock especially for dex file removal. 13327 abstract void cleanUpResourcesLI(); 13328 abstract boolean doPostDeleteLI(boolean delete); 13329 13330 /** 13331 * Called before the source arguments are copied. This is used mostly 13332 * for MoveParams when it needs to read the source file to put it in the 13333 * destination. 13334 */ 13335 int doPreCopy() { 13336 return PackageManager.INSTALL_SUCCEEDED; 13337 } 13338 13339 /** 13340 * Called after the source arguments are copied. This is used mostly for 13341 * MoveParams when it needs to read the source file to put it in the 13342 * destination. 13343 */ 13344 int doPostCopy(int uid) { 13345 return PackageManager.INSTALL_SUCCEEDED; 13346 } 13347 13348 protected boolean isFwdLocked() { 13349 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13350 } 13351 13352 protected boolean isExternalAsec() { 13353 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13354 } 13355 13356 protected boolean isEphemeral() { 13357 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13358 } 13359 13360 UserHandle getUser() { 13361 return user; 13362 } 13363 } 13364 13365 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13366 if (!allCodePaths.isEmpty()) { 13367 if (instructionSets == null) { 13368 throw new IllegalStateException("instructionSet == null"); 13369 } 13370 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13371 for (String codePath : allCodePaths) { 13372 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13373 try { 13374 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13375 } catch (InstallerException ignored) { 13376 } 13377 } 13378 } 13379 } 13380 } 13381 13382 /** 13383 * Logic to handle installation of non-ASEC applications, including copying 13384 * and renaming logic. 13385 */ 13386 class FileInstallArgs extends InstallArgs { 13387 private File codeFile; 13388 private File resourceFile; 13389 13390 // Example topology: 13391 // /data/app/com.example/base.apk 13392 // /data/app/com.example/split_foo.apk 13393 // /data/app/com.example/lib/arm/libfoo.so 13394 // /data/app/com.example/lib/arm64/libfoo.so 13395 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13396 13397 /** New install */ 13398 FileInstallArgs(InstallParams params) { 13399 super(params.origin, params.move, params.observer, params.installFlags, 13400 params.installerPackageName, params.volumeUuid, 13401 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13402 params.grantedRuntimePermissions, 13403 params.traceMethod, params.traceCookie, params.certificates); 13404 if (isFwdLocked()) { 13405 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13406 } 13407 } 13408 13409 /** Existing install */ 13410 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13411 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13412 null, null, null, 0, null /*certificates*/); 13413 this.codeFile = (codePath != null) ? new File(codePath) : null; 13414 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13415 } 13416 13417 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13418 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13419 try { 13420 return doCopyApk(imcs, temp); 13421 } finally { 13422 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13423 } 13424 } 13425 13426 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13427 if (origin.staged) { 13428 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13429 codeFile = origin.file; 13430 resourceFile = origin.file; 13431 return PackageManager.INSTALL_SUCCEEDED; 13432 } 13433 13434 try { 13435 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13436 final File tempDir = 13437 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13438 codeFile = tempDir; 13439 resourceFile = tempDir; 13440 } catch (IOException e) { 13441 Slog.w(TAG, "Failed to create copy file: " + e); 13442 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13443 } 13444 13445 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13446 @Override 13447 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13448 if (!FileUtils.isValidExtFilename(name)) { 13449 throw new IllegalArgumentException("Invalid filename: " + name); 13450 } 13451 try { 13452 final File file = new File(codeFile, name); 13453 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13454 O_RDWR | O_CREAT, 0644); 13455 Os.chmod(file.getAbsolutePath(), 0644); 13456 return new ParcelFileDescriptor(fd); 13457 } catch (ErrnoException e) { 13458 throw new RemoteException("Failed to open: " + e.getMessage()); 13459 } 13460 } 13461 }; 13462 13463 int ret = PackageManager.INSTALL_SUCCEEDED; 13464 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13465 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13466 Slog.e(TAG, "Failed to copy package"); 13467 return ret; 13468 } 13469 13470 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13471 NativeLibraryHelper.Handle handle = null; 13472 try { 13473 handle = NativeLibraryHelper.Handle.create(codeFile); 13474 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13475 abiOverride); 13476 } catch (IOException e) { 13477 Slog.e(TAG, "Copying native libraries failed", e); 13478 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13479 } finally { 13480 IoUtils.closeQuietly(handle); 13481 } 13482 13483 return ret; 13484 } 13485 13486 int doPreInstall(int status) { 13487 if (status != PackageManager.INSTALL_SUCCEEDED) { 13488 cleanUp(); 13489 } 13490 return status; 13491 } 13492 13493 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13494 if (status != PackageManager.INSTALL_SUCCEEDED) { 13495 cleanUp(); 13496 return false; 13497 } 13498 13499 final File targetDir = codeFile.getParentFile(); 13500 final File beforeCodeFile = codeFile; 13501 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13502 13503 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13504 try { 13505 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13506 } catch (ErrnoException e) { 13507 Slog.w(TAG, "Failed to rename", e); 13508 return false; 13509 } 13510 13511 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13512 Slog.w(TAG, "Failed to restorecon"); 13513 return false; 13514 } 13515 13516 // Reflect the rename internally 13517 codeFile = afterCodeFile; 13518 resourceFile = afterCodeFile; 13519 13520 // Reflect the rename in scanned details 13521 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13522 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13523 afterCodeFile, pkg.baseCodePath)); 13524 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13525 afterCodeFile, pkg.splitCodePaths)); 13526 13527 // Reflect the rename in app info 13528 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13529 pkg.setApplicationInfoCodePath(pkg.codePath); 13530 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13531 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13532 pkg.setApplicationInfoResourcePath(pkg.codePath); 13533 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13534 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13535 13536 return true; 13537 } 13538 13539 int doPostInstall(int status, int uid) { 13540 if (status != PackageManager.INSTALL_SUCCEEDED) { 13541 cleanUp(); 13542 } 13543 return status; 13544 } 13545 13546 @Override 13547 String getCodePath() { 13548 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13549 } 13550 13551 @Override 13552 String getResourcePath() { 13553 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13554 } 13555 13556 private boolean cleanUp() { 13557 if (codeFile == null || !codeFile.exists()) { 13558 return false; 13559 } 13560 13561 removeCodePathLI(codeFile); 13562 13563 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13564 resourceFile.delete(); 13565 } 13566 13567 return true; 13568 } 13569 13570 void cleanUpResourcesLI() { 13571 // Try enumerating all code paths before deleting 13572 List<String> allCodePaths = Collections.EMPTY_LIST; 13573 if (codeFile != null && codeFile.exists()) { 13574 try { 13575 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13576 allCodePaths = pkg.getAllCodePaths(); 13577 } catch (PackageParserException e) { 13578 // Ignored; we tried our best 13579 } 13580 } 13581 13582 cleanUp(); 13583 removeDexFiles(allCodePaths, instructionSets); 13584 } 13585 13586 boolean doPostDeleteLI(boolean delete) { 13587 // XXX err, shouldn't we respect the delete flag? 13588 cleanUpResourcesLI(); 13589 return true; 13590 } 13591 } 13592 13593 private boolean isAsecExternal(String cid) { 13594 final String asecPath = PackageHelper.getSdFilesystem(cid); 13595 return !asecPath.startsWith(mAsecInternalPath); 13596 } 13597 13598 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13599 PackageManagerException { 13600 if (copyRet < 0) { 13601 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13602 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13603 throw new PackageManagerException(copyRet, message); 13604 } 13605 } 13606 } 13607 13608 /** 13609 * Extract the MountService "container ID" from the full code path of an 13610 * .apk. 13611 */ 13612 static String cidFromCodePath(String fullCodePath) { 13613 int eidx = fullCodePath.lastIndexOf("/"); 13614 String subStr1 = fullCodePath.substring(0, eidx); 13615 int sidx = subStr1.lastIndexOf("/"); 13616 return subStr1.substring(sidx+1, eidx); 13617 } 13618 13619 /** 13620 * Logic to handle installation of ASEC applications, including copying and 13621 * renaming logic. 13622 */ 13623 class AsecInstallArgs extends InstallArgs { 13624 static final String RES_FILE_NAME = "pkg.apk"; 13625 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13626 13627 String cid; 13628 String packagePath; 13629 String resourcePath; 13630 13631 /** New install */ 13632 AsecInstallArgs(InstallParams params) { 13633 super(params.origin, params.move, params.observer, params.installFlags, 13634 params.installerPackageName, params.volumeUuid, 13635 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13636 params.grantedRuntimePermissions, 13637 params.traceMethod, params.traceCookie, params.certificates); 13638 } 13639 13640 /** Existing install */ 13641 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13642 boolean isExternal, boolean isForwardLocked) { 13643 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13644 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13645 instructionSets, null, null, null, 0, null /*certificates*/); 13646 // Hackily pretend we're still looking at a full code path 13647 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13648 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13649 } 13650 13651 // Extract cid from fullCodePath 13652 int eidx = fullCodePath.lastIndexOf("/"); 13653 String subStr1 = fullCodePath.substring(0, eidx); 13654 int sidx = subStr1.lastIndexOf("/"); 13655 cid = subStr1.substring(sidx+1, eidx); 13656 setMountPath(subStr1); 13657 } 13658 13659 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13660 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13661 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13662 instructionSets, null, null, null, 0, null /*certificates*/); 13663 this.cid = cid; 13664 setMountPath(PackageHelper.getSdDir(cid)); 13665 } 13666 13667 void createCopyFile() { 13668 cid = mInstallerService.allocateExternalStageCidLegacy(); 13669 } 13670 13671 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13672 if (origin.staged && origin.cid != null) { 13673 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13674 cid = origin.cid; 13675 setMountPath(PackageHelper.getSdDir(cid)); 13676 return PackageManager.INSTALL_SUCCEEDED; 13677 } 13678 13679 if (temp) { 13680 createCopyFile(); 13681 } else { 13682 /* 13683 * Pre-emptively destroy the container since it's destroyed if 13684 * copying fails due to it existing anyway. 13685 */ 13686 PackageHelper.destroySdDir(cid); 13687 } 13688 13689 final String newMountPath = imcs.copyPackageToContainer( 13690 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13691 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13692 13693 if (newMountPath != null) { 13694 setMountPath(newMountPath); 13695 return PackageManager.INSTALL_SUCCEEDED; 13696 } else { 13697 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13698 } 13699 } 13700 13701 @Override 13702 String getCodePath() { 13703 return packagePath; 13704 } 13705 13706 @Override 13707 String getResourcePath() { 13708 return resourcePath; 13709 } 13710 13711 int doPreInstall(int status) { 13712 if (status != PackageManager.INSTALL_SUCCEEDED) { 13713 // Destroy container 13714 PackageHelper.destroySdDir(cid); 13715 } else { 13716 boolean mounted = PackageHelper.isContainerMounted(cid); 13717 if (!mounted) { 13718 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13719 Process.SYSTEM_UID); 13720 if (newMountPath != null) { 13721 setMountPath(newMountPath); 13722 } else { 13723 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13724 } 13725 } 13726 } 13727 return status; 13728 } 13729 13730 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13731 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13732 String newMountPath = null; 13733 if (PackageHelper.isContainerMounted(cid)) { 13734 // Unmount the container 13735 if (!PackageHelper.unMountSdDir(cid)) { 13736 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13737 return false; 13738 } 13739 } 13740 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13741 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13742 " which might be stale. Will try to clean up."); 13743 // Clean up the stale container and proceed to recreate. 13744 if (!PackageHelper.destroySdDir(newCacheId)) { 13745 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13746 return false; 13747 } 13748 // Successfully cleaned up stale container. Try to rename again. 13749 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13750 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13751 + " inspite of cleaning it up."); 13752 return false; 13753 } 13754 } 13755 if (!PackageHelper.isContainerMounted(newCacheId)) { 13756 Slog.w(TAG, "Mounting container " + newCacheId); 13757 newMountPath = PackageHelper.mountSdDir(newCacheId, 13758 getEncryptKey(), Process.SYSTEM_UID); 13759 } else { 13760 newMountPath = PackageHelper.getSdDir(newCacheId); 13761 } 13762 if (newMountPath == null) { 13763 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13764 return false; 13765 } 13766 Log.i(TAG, "Succesfully renamed " + cid + 13767 " to " + newCacheId + 13768 " at new path: " + newMountPath); 13769 cid = newCacheId; 13770 13771 final File beforeCodeFile = new File(packagePath); 13772 setMountPath(newMountPath); 13773 final File afterCodeFile = new File(packagePath); 13774 13775 // Reflect the rename in scanned details 13776 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13777 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13778 afterCodeFile, pkg.baseCodePath)); 13779 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13780 afterCodeFile, pkg.splitCodePaths)); 13781 13782 // Reflect the rename in app info 13783 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13784 pkg.setApplicationInfoCodePath(pkg.codePath); 13785 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13786 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13787 pkg.setApplicationInfoResourcePath(pkg.codePath); 13788 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13789 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13790 13791 return true; 13792 } 13793 13794 private void setMountPath(String mountPath) { 13795 final File mountFile = new File(mountPath); 13796 13797 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13798 if (monolithicFile.exists()) { 13799 packagePath = monolithicFile.getAbsolutePath(); 13800 if (isFwdLocked()) { 13801 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13802 } else { 13803 resourcePath = packagePath; 13804 } 13805 } else { 13806 packagePath = mountFile.getAbsolutePath(); 13807 resourcePath = packagePath; 13808 } 13809 } 13810 13811 int doPostInstall(int status, int uid) { 13812 if (status != PackageManager.INSTALL_SUCCEEDED) { 13813 cleanUp(); 13814 } else { 13815 final int groupOwner; 13816 final String protectedFile; 13817 if (isFwdLocked()) { 13818 groupOwner = UserHandle.getSharedAppGid(uid); 13819 protectedFile = RES_FILE_NAME; 13820 } else { 13821 groupOwner = -1; 13822 protectedFile = null; 13823 } 13824 13825 if (uid < Process.FIRST_APPLICATION_UID 13826 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13827 Slog.e(TAG, "Failed to finalize " + cid); 13828 PackageHelper.destroySdDir(cid); 13829 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13830 } 13831 13832 boolean mounted = PackageHelper.isContainerMounted(cid); 13833 if (!mounted) { 13834 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13835 } 13836 } 13837 return status; 13838 } 13839 13840 private void cleanUp() { 13841 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13842 13843 // Destroy secure container 13844 PackageHelper.destroySdDir(cid); 13845 } 13846 13847 private List<String> getAllCodePaths() { 13848 final File codeFile = new File(getCodePath()); 13849 if (codeFile != null && codeFile.exists()) { 13850 try { 13851 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13852 return pkg.getAllCodePaths(); 13853 } catch (PackageParserException e) { 13854 // Ignored; we tried our best 13855 } 13856 } 13857 return Collections.EMPTY_LIST; 13858 } 13859 13860 void cleanUpResourcesLI() { 13861 // Enumerate all code paths before deleting 13862 cleanUpResourcesLI(getAllCodePaths()); 13863 } 13864 13865 private void cleanUpResourcesLI(List<String> allCodePaths) { 13866 cleanUp(); 13867 removeDexFiles(allCodePaths, instructionSets); 13868 } 13869 13870 String getPackageName() { 13871 return getAsecPackageName(cid); 13872 } 13873 13874 boolean doPostDeleteLI(boolean delete) { 13875 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13876 final List<String> allCodePaths = getAllCodePaths(); 13877 boolean mounted = PackageHelper.isContainerMounted(cid); 13878 if (mounted) { 13879 // Unmount first 13880 if (PackageHelper.unMountSdDir(cid)) { 13881 mounted = false; 13882 } 13883 } 13884 if (!mounted && delete) { 13885 cleanUpResourcesLI(allCodePaths); 13886 } 13887 return !mounted; 13888 } 13889 13890 @Override 13891 int doPreCopy() { 13892 if (isFwdLocked()) { 13893 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13894 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13895 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13896 } 13897 } 13898 13899 return PackageManager.INSTALL_SUCCEEDED; 13900 } 13901 13902 @Override 13903 int doPostCopy(int uid) { 13904 if (isFwdLocked()) { 13905 if (uid < Process.FIRST_APPLICATION_UID 13906 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13907 RES_FILE_NAME)) { 13908 Slog.e(TAG, "Failed to finalize " + cid); 13909 PackageHelper.destroySdDir(cid); 13910 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13911 } 13912 } 13913 13914 return PackageManager.INSTALL_SUCCEEDED; 13915 } 13916 } 13917 13918 /** 13919 * Logic to handle movement of existing installed applications. 13920 */ 13921 class MoveInstallArgs extends InstallArgs { 13922 private File codeFile; 13923 private File resourceFile; 13924 13925 /** New install */ 13926 MoveInstallArgs(InstallParams params) { 13927 super(params.origin, params.move, params.observer, params.installFlags, 13928 params.installerPackageName, params.volumeUuid, 13929 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13930 params.grantedRuntimePermissions, 13931 params.traceMethod, params.traceCookie, params.certificates); 13932 } 13933 13934 int copyApk(IMediaContainerService imcs, boolean temp) { 13935 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13936 + move.fromUuid + " to " + move.toUuid); 13937 synchronized (mInstaller) { 13938 try { 13939 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13940 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13941 } catch (InstallerException e) { 13942 Slog.w(TAG, "Failed to move app", e); 13943 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13944 } 13945 } 13946 13947 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13948 resourceFile = codeFile; 13949 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13950 13951 return PackageManager.INSTALL_SUCCEEDED; 13952 } 13953 13954 int doPreInstall(int status) { 13955 if (status != PackageManager.INSTALL_SUCCEEDED) { 13956 cleanUp(move.toUuid); 13957 } 13958 return status; 13959 } 13960 13961 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13962 if (status != PackageManager.INSTALL_SUCCEEDED) { 13963 cleanUp(move.toUuid); 13964 return false; 13965 } 13966 13967 // Reflect the move in app info 13968 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13969 pkg.setApplicationInfoCodePath(pkg.codePath); 13970 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13971 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13972 pkg.setApplicationInfoResourcePath(pkg.codePath); 13973 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13974 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13975 13976 return true; 13977 } 13978 13979 int doPostInstall(int status, int uid) { 13980 if (status == PackageManager.INSTALL_SUCCEEDED) { 13981 cleanUp(move.fromUuid); 13982 } else { 13983 cleanUp(move.toUuid); 13984 } 13985 return status; 13986 } 13987 13988 @Override 13989 String getCodePath() { 13990 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13991 } 13992 13993 @Override 13994 String getResourcePath() { 13995 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13996 } 13997 13998 private boolean cleanUp(String volumeUuid) { 13999 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14000 move.dataAppName); 14001 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14002 final int[] userIds = sUserManager.getUserIds(); 14003 synchronized (mInstallLock) { 14004 // Clean up both app data and code 14005 // All package moves are frozen until finished 14006 for (int userId : userIds) { 14007 try { 14008 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14009 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14010 } catch (InstallerException e) { 14011 Slog.w(TAG, String.valueOf(e)); 14012 } 14013 } 14014 removeCodePathLI(codeFile); 14015 } 14016 return true; 14017 } 14018 14019 void cleanUpResourcesLI() { 14020 throw new UnsupportedOperationException(); 14021 } 14022 14023 boolean doPostDeleteLI(boolean delete) { 14024 throw new UnsupportedOperationException(); 14025 } 14026 } 14027 14028 static String getAsecPackageName(String packageCid) { 14029 int idx = packageCid.lastIndexOf("-"); 14030 if (idx == -1) { 14031 return packageCid; 14032 } 14033 return packageCid.substring(0, idx); 14034 } 14035 14036 // Utility method used to create code paths based on package name and available index. 14037 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14038 String idxStr = ""; 14039 int idx = 1; 14040 // Fall back to default value of idx=1 if prefix is not 14041 // part of oldCodePath 14042 if (oldCodePath != null) { 14043 String subStr = oldCodePath; 14044 // Drop the suffix right away 14045 if (suffix != null && subStr.endsWith(suffix)) { 14046 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14047 } 14048 // If oldCodePath already contains prefix find out the 14049 // ending index to either increment or decrement. 14050 int sidx = subStr.lastIndexOf(prefix); 14051 if (sidx != -1) { 14052 subStr = subStr.substring(sidx + prefix.length()); 14053 if (subStr != null) { 14054 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14055 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14056 } 14057 try { 14058 idx = Integer.parseInt(subStr); 14059 if (idx <= 1) { 14060 idx++; 14061 } else { 14062 idx--; 14063 } 14064 } catch(NumberFormatException e) { 14065 } 14066 } 14067 } 14068 } 14069 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14070 return prefix + idxStr; 14071 } 14072 14073 private File getNextCodePath(File targetDir, String packageName) { 14074 int suffix = 1; 14075 File result; 14076 do { 14077 result = new File(targetDir, packageName + "-" + suffix); 14078 suffix++; 14079 } while (result.exists()); 14080 return result; 14081 } 14082 14083 // Utility method that returns the relative package path with respect 14084 // to the installation directory. Like say for /data/data/com.test-1.apk 14085 // string com.test-1 is returned. 14086 static String deriveCodePathName(String codePath) { 14087 if (codePath == null) { 14088 return null; 14089 } 14090 final File codeFile = new File(codePath); 14091 final String name = codeFile.getName(); 14092 if (codeFile.isDirectory()) { 14093 return name; 14094 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14095 final int lastDot = name.lastIndexOf('.'); 14096 return name.substring(0, lastDot); 14097 } else { 14098 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14099 return null; 14100 } 14101 } 14102 14103 static class PackageInstalledInfo { 14104 String name; 14105 int uid; 14106 // The set of users that originally had this package installed. 14107 int[] origUsers; 14108 // The set of users that now have this package installed. 14109 int[] newUsers; 14110 PackageParser.Package pkg; 14111 int returnCode; 14112 String returnMsg; 14113 PackageRemovedInfo removedInfo; 14114 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14115 14116 public void setError(int code, String msg) { 14117 setReturnCode(code); 14118 setReturnMessage(msg); 14119 Slog.w(TAG, msg); 14120 } 14121 14122 public void setError(String msg, PackageParserException e) { 14123 setReturnCode(e.error); 14124 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14125 Slog.w(TAG, msg, e); 14126 } 14127 14128 public void setError(String msg, PackageManagerException e) { 14129 returnCode = e.error; 14130 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14131 Slog.w(TAG, msg, e); 14132 } 14133 14134 public void setReturnCode(int returnCode) { 14135 this.returnCode = returnCode; 14136 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14137 for (int i = 0; i < childCount; i++) { 14138 addedChildPackages.valueAt(i).returnCode = returnCode; 14139 } 14140 } 14141 14142 private void setReturnMessage(String returnMsg) { 14143 this.returnMsg = returnMsg; 14144 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14145 for (int i = 0; i < childCount; i++) { 14146 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14147 } 14148 } 14149 14150 // In some error cases we want to convey more info back to the observer 14151 String origPackage; 14152 String origPermission; 14153 } 14154 14155 /* 14156 * Install a non-existing package. 14157 */ 14158 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14159 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14160 PackageInstalledInfo res) { 14161 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14162 14163 // Remember this for later, in case we need to rollback this install 14164 String pkgName = pkg.packageName; 14165 14166 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14167 14168 synchronized(mPackages) { 14169 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14170 // A package with the same name is already installed, though 14171 // it has been renamed to an older name. The package we 14172 // are trying to install should be installed as an update to 14173 // the existing one, but that has not been requested, so bail. 14174 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14175 + " without first uninstalling package running as " 14176 + mSettings.mRenamedPackages.get(pkgName)); 14177 return; 14178 } 14179 if (mPackages.containsKey(pkgName)) { 14180 // Don't allow installation over an existing package with the same name. 14181 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14182 + " without first uninstalling."); 14183 return; 14184 } 14185 } 14186 14187 try { 14188 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14189 System.currentTimeMillis(), user); 14190 14191 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14192 14193 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14194 prepareAppDataAfterInstallLIF(newPackage); 14195 14196 } else { 14197 // Remove package from internal structures, but keep around any 14198 // data that might have already existed 14199 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14200 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14201 } 14202 } catch (PackageManagerException e) { 14203 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14204 } 14205 14206 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14207 } 14208 14209 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14210 // Can't rotate keys during boot or if sharedUser. 14211 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14212 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14213 return false; 14214 } 14215 // app is using upgradeKeySets; make sure all are valid 14216 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14217 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14218 for (int i = 0; i < upgradeKeySets.length; i++) { 14219 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14220 Slog.wtf(TAG, "Package " 14221 + (oldPs.name != null ? oldPs.name : "<null>") 14222 + " contains upgrade-key-set reference to unknown key-set: " 14223 + upgradeKeySets[i] 14224 + " reverting to signatures check."); 14225 return false; 14226 } 14227 } 14228 return true; 14229 } 14230 14231 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14232 // Upgrade keysets are being used. Determine if new package has a superset of the 14233 // required keys. 14234 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14235 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14236 for (int i = 0; i < upgradeKeySets.length; i++) { 14237 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14238 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14239 return true; 14240 } 14241 } 14242 return false; 14243 } 14244 14245 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14246 try (DigestInputStream digestStream = 14247 new DigestInputStream(new FileInputStream(file), digest)) { 14248 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14249 } 14250 } 14251 14252 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14253 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14254 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14255 14256 final PackageParser.Package oldPackage; 14257 final String pkgName = pkg.packageName; 14258 final int[] allUsers; 14259 final int[] installedUsers; 14260 14261 synchronized(mPackages) { 14262 oldPackage = mPackages.get(pkgName); 14263 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14264 14265 // don't allow upgrade to target a release SDK from a pre-release SDK 14266 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14267 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14268 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14269 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14270 if (oldTargetsPreRelease 14271 && !newTargetsPreRelease 14272 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14273 Slog.w(TAG, "Can't install package targeting released sdk"); 14274 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14275 return; 14276 } 14277 14278 // don't allow an upgrade from full to ephemeral 14279 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14280 if (isEphemeral && !oldIsEphemeral) { 14281 // can't downgrade from full to ephemeral 14282 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14283 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14284 return; 14285 } 14286 14287 // verify signatures are valid 14288 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14289 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14290 if (!checkUpgradeKeySetLP(ps, pkg)) { 14291 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14292 "New package not signed by keys specified by upgrade-keysets: " 14293 + pkgName); 14294 return; 14295 } 14296 } else { 14297 // default to original signature matching 14298 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14299 != PackageManager.SIGNATURE_MATCH) { 14300 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14301 "New package has a different signature: " + pkgName); 14302 return; 14303 } 14304 } 14305 14306 // don't allow a system upgrade unless the upgrade hash matches 14307 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14308 byte[] digestBytes = null; 14309 try { 14310 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14311 updateDigest(digest, new File(pkg.baseCodePath)); 14312 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14313 for (String path : pkg.splitCodePaths) { 14314 updateDigest(digest, new File(path)); 14315 } 14316 } 14317 digestBytes = digest.digest(); 14318 } catch (NoSuchAlgorithmException | IOException e) { 14319 res.setError(INSTALL_FAILED_INVALID_APK, 14320 "Could not compute hash: " + pkgName); 14321 return; 14322 } 14323 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14324 res.setError(INSTALL_FAILED_INVALID_APK, 14325 "New package fails restrict-update check: " + pkgName); 14326 return; 14327 } 14328 // retain upgrade restriction 14329 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14330 } 14331 14332 // Check for shared user id changes 14333 String invalidPackageName = 14334 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14335 if (invalidPackageName != null) { 14336 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14337 "Package " + invalidPackageName + " tried to change user " 14338 + oldPackage.mSharedUserId); 14339 return; 14340 } 14341 14342 // In case of rollback, remember per-user/profile install state 14343 allUsers = sUserManager.getUserIds(); 14344 installedUsers = ps.queryInstalledUsers(allUsers, true); 14345 } 14346 14347 // Update what is removed 14348 res.removedInfo = new PackageRemovedInfo(); 14349 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14350 res.removedInfo.removedPackage = oldPackage.packageName; 14351 res.removedInfo.isUpdate = true; 14352 res.removedInfo.origUsers = installedUsers; 14353 final int childCount = (oldPackage.childPackages != null) 14354 ? oldPackage.childPackages.size() : 0; 14355 for (int i = 0; i < childCount; i++) { 14356 boolean childPackageUpdated = false; 14357 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14358 if (res.addedChildPackages != null) { 14359 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14360 if (childRes != null) { 14361 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14362 childRes.removedInfo.removedPackage = childPkg.packageName; 14363 childRes.removedInfo.isUpdate = true; 14364 childPackageUpdated = true; 14365 } 14366 } 14367 if (!childPackageUpdated) { 14368 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14369 childRemovedRes.removedPackage = childPkg.packageName; 14370 childRemovedRes.isUpdate = false; 14371 childRemovedRes.dataRemoved = true; 14372 synchronized (mPackages) { 14373 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14374 if (childPs != null) { 14375 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14376 } 14377 } 14378 if (res.removedInfo.removedChildPackages == null) { 14379 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14380 } 14381 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14382 } 14383 } 14384 14385 boolean sysPkg = (isSystemApp(oldPackage)); 14386 if (sysPkg) { 14387 // Set the system/privileged flags as needed 14388 final boolean privileged = 14389 (oldPackage.applicationInfo.privateFlags 14390 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14391 final int systemPolicyFlags = policyFlags 14392 | PackageParser.PARSE_IS_SYSTEM 14393 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14394 14395 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14396 user, allUsers, installerPackageName, res); 14397 } else { 14398 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14399 user, allUsers, installerPackageName, res); 14400 } 14401 } 14402 14403 public List<String> getPreviousCodePaths(String packageName) { 14404 final PackageSetting ps = mSettings.mPackages.get(packageName); 14405 final List<String> result = new ArrayList<String>(); 14406 if (ps != null && ps.oldCodePaths != null) { 14407 result.addAll(ps.oldCodePaths); 14408 } 14409 return result; 14410 } 14411 14412 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14413 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14414 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14415 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14416 + deletedPackage); 14417 14418 String pkgName = deletedPackage.packageName; 14419 boolean deletedPkg = true; 14420 boolean addedPkg = false; 14421 boolean updatedSettings = false; 14422 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14423 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14424 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14425 14426 final long origUpdateTime = (pkg.mExtras != null) 14427 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14428 14429 // First delete the existing package while retaining the data directory 14430 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14431 res.removedInfo, true, pkg)) { 14432 // If the existing package wasn't successfully deleted 14433 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14434 deletedPkg = false; 14435 } else { 14436 // Successfully deleted the old package; proceed with replace. 14437 14438 // If deleted package lived in a container, give users a chance to 14439 // relinquish resources before killing. 14440 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14441 if (DEBUG_INSTALL) { 14442 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14443 } 14444 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14445 final ArrayList<String> pkgList = new ArrayList<String>(1); 14446 pkgList.add(deletedPackage.applicationInfo.packageName); 14447 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14448 } 14449 14450 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14451 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14452 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14453 14454 try { 14455 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14456 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14457 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14458 14459 // Update the in-memory copy of the previous code paths. 14460 PackageSetting ps = mSettings.mPackages.get(pkgName); 14461 if (!killApp) { 14462 if (ps.oldCodePaths == null) { 14463 ps.oldCodePaths = new ArraySet<>(); 14464 } 14465 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14466 if (deletedPackage.splitCodePaths != null) { 14467 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14468 } 14469 } else { 14470 ps.oldCodePaths = null; 14471 } 14472 if (ps.childPackageNames != null) { 14473 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14474 final String childPkgName = ps.childPackageNames.get(i); 14475 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14476 childPs.oldCodePaths = ps.oldCodePaths; 14477 } 14478 } 14479 prepareAppDataAfterInstallLIF(newPackage); 14480 addedPkg = true; 14481 } catch (PackageManagerException e) { 14482 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14483 } 14484 } 14485 14486 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14487 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14488 14489 // Revert all internal state mutations and added folders for the failed install 14490 if (addedPkg) { 14491 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14492 res.removedInfo, true, null); 14493 } 14494 14495 // Restore the old package 14496 if (deletedPkg) { 14497 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14498 File restoreFile = new File(deletedPackage.codePath); 14499 // Parse old package 14500 boolean oldExternal = isExternal(deletedPackage); 14501 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14502 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14503 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14504 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14505 try { 14506 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14507 null); 14508 } catch (PackageManagerException e) { 14509 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14510 + e.getMessage()); 14511 return; 14512 } 14513 14514 synchronized (mPackages) { 14515 // Ensure the installer package name up to date 14516 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14517 14518 // Update permissions for restored package 14519 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14520 14521 mSettings.writeLPr(); 14522 } 14523 14524 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14525 } 14526 } else { 14527 synchronized (mPackages) { 14528 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14529 if (ps != null) { 14530 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14531 if (res.removedInfo.removedChildPackages != null) { 14532 final int childCount = res.removedInfo.removedChildPackages.size(); 14533 // Iterate in reverse as we may modify the collection 14534 for (int i = childCount - 1; i >= 0; i--) { 14535 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14536 if (res.addedChildPackages.containsKey(childPackageName)) { 14537 res.removedInfo.removedChildPackages.removeAt(i); 14538 } else { 14539 PackageRemovedInfo childInfo = res.removedInfo 14540 .removedChildPackages.valueAt(i); 14541 childInfo.removedForAllUsers = mPackages.get( 14542 childInfo.removedPackage) == null; 14543 } 14544 } 14545 } 14546 } 14547 } 14548 } 14549 } 14550 14551 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14552 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14553 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14554 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14555 + ", old=" + deletedPackage); 14556 14557 final boolean disabledSystem; 14558 14559 // Remove existing system package 14560 removePackageLI(deletedPackage, true); 14561 14562 synchronized (mPackages) { 14563 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14564 } 14565 if (!disabledSystem) { 14566 // We didn't need to disable the .apk as a current system package, 14567 // which means we are replacing another update that is already 14568 // installed. We need to make sure to delete the older one's .apk. 14569 res.removedInfo.args = createInstallArgsForExisting(0, 14570 deletedPackage.applicationInfo.getCodePath(), 14571 deletedPackage.applicationInfo.getResourcePath(), 14572 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14573 } else { 14574 res.removedInfo.args = null; 14575 } 14576 14577 // Successfully disabled the old package. Now proceed with re-installation 14578 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14579 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14580 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14581 14582 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14583 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14584 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14585 14586 PackageParser.Package newPackage = null; 14587 try { 14588 // Add the package to the internal data structures 14589 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14590 14591 // Set the update and install times 14592 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14593 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14594 System.currentTimeMillis()); 14595 14596 // Update the package dynamic state if succeeded 14597 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14598 // Now that the install succeeded make sure we remove data 14599 // directories for any child package the update removed. 14600 final int deletedChildCount = (deletedPackage.childPackages != null) 14601 ? deletedPackage.childPackages.size() : 0; 14602 final int newChildCount = (newPackage.childPackages != null) 14603 ? newPackage.childPackages.size() : 0; 14604 for (int i = 0; i < deletedChildCount; i++) { 14605 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14606 boolean childPackageDeleted = true; 14607 for (int j = 0; j < newChildCount; j++) { 14608 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14609 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14610 childPackageDeleted = false; 14611 break; 14612 } 14613 } 14614 if (childPackageDeleted) { 14615 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14616 deletedChildPkg.packageName); 14617 if (ps != null && res.removedInfo.removedChildPackages != null) { 14618 PackageRemovedInfo removedChildRes = res.removedInfo 14619 .removedChildPackages.get(deletedChildPkg.packageName); 14620 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14621 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14622 } 14623 } 14624 } 14625 14626 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14627 prepareAppDataAfterInstallLIF(newPackage); 14628 } 14629 } catch (PackageManagerException e) { 14630 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14631 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14632 } 14633 14634 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14635 // Re installation failed. Restore old information 14636 // Remove new pkg information 14637 if (newPackage != null) { 14638 removeInstalledPackageLI(newPackage, true); 14639 } 14640 // Add back the old system package 14641 try { 14642 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14643 } catch (PackageManagerException e) { 14644 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14645 } 14646 14647 synchronized (mPackages) { 14648 if (disabledSystem) { 14649 enableSystemPackageLPw(deletedPackage); 14650 } 14651 14652 // Ensure the installer package name up to date 14653 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14654 14655 // Update permissions for restored package 14656 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14657 14658 mSettings.writeLPr(); 14659 } 14660 14661 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14662 + " after failed upgrade"); 14663 } 14664 } 14665 14666 /** 14667 * Checks whether the parent or any of the child packages have a change shared 14668 * user. For a package to be a valid update the shred users of the parent and 14669 * the children should match. We may later support changing child shared users. 14670 * @param oldPkg The updated package. 14671 * @param newPkg The update package. 14672 * @return The shared user that change between the versions. 14673 */ 14674 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14675 PackageParser.Package newPkg) { 14676 // Check parent shared user 14677 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14678 return newPkg.packageName; 14679 } 14680 // Check child shared users 14681 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14682 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14683 for (int i = 0; i < newChildCount; i++) { 14684 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14685 // If this child was present, did it have the same shared user? 14686 for (int j = 0; j < oldChildCount; j++) { 14687 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14688 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14689 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14690 return newChildPkg.packageName; 14691 } 14692 } 14693 } 14694 return null; 14695 } 14696 14697 private void removeNativeBinariesLI(PackageSetting ps) { 14698 // Remove the lib path for the parent package 14699 if (ps != null) { 14700 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14701 // Remove the lib path for the child packages 14702 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14703 for (int i = 0; i < childCount; i++) { 14704 PackageSetting childPs = null; 14705 synchronized (mPackages) { 14706 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14707 } 14708 if (childPs != null) { 14709 NativeLibraryHelper.removeNativeBinariesLI(childPs 14710 .legacyNativeLibraryPathString); 14711 } 14712 } 14713 } 14714 } 14715 14716 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14717 // Enable the parent package 14718 mSettings.enableSystemPackageLPw(pkg.packageName); 14719 // Enable the child packages 14720 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14721 for (int i = 0; i < childCount; i++) { 14722 PackageParser.Package childPkg = pkg.childPackages.get(i); 14723 mSettings.enableSystemPackageLPw(childPkg.packageName); 14724 } 14725 } 14726 14727 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14728 PackageParser.Package newPkg) { 14729 // Disable the parent package (parent always replaced) 14730 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14731 // Disable the child packages 14732 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14733 for (int i = 0; i < childCount; i++) { 14734 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14735 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14736 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14737 } 14738 return disabled; 14739 } 14740 14741 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14742 String installerPackageName) { 14743 // Enable the parent package 14744 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14745 // Enable the child packages 14746 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14747 for (int i = 0; i < childCount; i++) { 14748 PackageParser.Package childPkg = pkg.childPackages.get(i); 14749 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14750 } 14751 } 14752 14753 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14754 // Collect all used permissions in the UID 14755 ArraySet<String> usedPermissions = new ArraySet<>(); 14756 final int packageCount = su.packages.size(); 14757 for (int i = 0; i < packageCount; i++) { 14758 PackageSetting ps = su.packages.valueAt(i); 14759 if (ps.pkg == null) { 14760 continue; 14761 } 14762 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14763 for (int j = 0; j < requestedPermCount; j++) { 14764 String permission = ps.pkg.requestedPermissions.get(j); 14765 BasePermission bp = mSettings.mPermissions.get(permission); 14766 if (bp != null) { 14767 usedPermissions.add(permission); 14768 } 14769 } 14770 } 14771 14772 PermissionsState permissionsState = su.getPermissionsState(); 14773 // Prune install permissions 14774 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14775 final int installPermCount = installPermStates.size(); 14776 for (int i = installPermCount - 1; i >= 0; i--) { 14777 PermissionState permissionState = installPermStates.get(i); 14778 if (!usedPermissions.contains(permissionState.getName())) { 14779 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14780 if (bp != null) { 14781 permissionsState.revokeInstallPermission(bp); 14782 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14783 PackageManager.MASK_PERMISSION_FLAGS, 0); 14784 } 14785 } 14786 } 14787 14788 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14789 14790 // Prune runtime permissions 14791 for (int userId : allUserIds) { 14792 List<PermissionState> runtimePermStates = permissionsState 14793 .getRuntimePermissionStates(userId); 14794 final int runtimePermCount = runtimePermStates.size(); 14795 for (int i = runtimePermCount - 1; i >= 0; i--) { 14796 PermissionState permissionState = runtimePermStates.get(i); 14797 if (!usedPermissions.contains(permissionState.getName())) { 14798 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14799 if (bp != null) { 14800 permissionsState.revokeRuntimePermission(bp, userId); 14801 permissionsState.updatePermissionFlags(bp, userId, 14802 PackageManager.MASK_PERMISSION_FLAGS, 0); 14803 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14804 runtimePermissionChangedUserIds, userId); 14805 } 14806 } 14807 } 14808 } 14809 14810 return runtimePermissionChangedUserIds; 14811 } 14812 14813 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14814 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14815 // Update the parent package setting 14816 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14817 res, user); 14818 // Update the child packages setting 14819 final int childCount = (newPackage.childPackages != null) 14820 ? newPackage.childPackages.size() : 0; 14821 for (int i = 0; i < childCount; i++) { 14822 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14823 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14824 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14825 childRes.origUsers, childRes, user); 14826 } 14827 } 14828 14829 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14830 String installerPackageName, int[] allUsers, int[] installedForUsers, 14831 PackageInstalledInfo res, UserHandle user) { 14832 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14833 14834 String pkgName = newPackage.packageName; 14835 synchronized (mPackages) { 14836 //write settings. the installStatus will be incomplete at this stage. 14837 //note that the new package setting would have already been 14838 //added to mPackages. It hasn't been persisted yet. 14839 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14840 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14841 mSettings.writeLPr(); 14842 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14843 } 14844 14845 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14846 synchronized (mPackages) { 14847 updatePermissionsLPw(newPackage.packageName, newPackage, 14848 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14849 ? UPDATE_PERMISSIONS_ALL : 0)); 14850 // For system-bundled packages, we assume that installing an upgraded version 14851 // of the package implies that the user actually wants to run that new code, 14852 // so we enable the package. 14853 PackageSetting ps = mSettings.mPackages.get(pkgName); 14854 final int userId = user.getIdentifier(); 14855 if (ps != null) { 14856 if (isSystemApp(newPackage)) { 14857 if (DEBUG_INSTALL) { 14858 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14859 } 14860 // Enable system package for requested users 14861 if (res.origUsers != null) { 14862 for (int origUserId : res.origUsers) { 14863 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14864 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14865 origUserId, installerPackageName); 14866 } 14867 } 14868 } 14869 // Also convey the prior install/uninstall state 14870 if (allUsers != null && installedForUsers != null) { 14871 for (int currentUserId : allUsers) { 14872 final boolean installed = ArrayUtils.contains( 14873 installedForUsers, currentUserId); 14874 if (DEBUG_INSTALL) { 14875 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14876 } 14877 ps.setInstalled(installed, currentUserId); 14878 } 14879 // these install state changes will be persisted in the 14880 // upcoming call to mSettings.writeLPr(). 14881 } 14882 } 14883 // It's implied that when a user requests installation, they want the app to be 14884 // installed and enabled. 14885 if (userId != UserHandle.USER_ALL) { 14886 ps.setInstalled(true, userId); 14887 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14888 } 14889 } 14890 res.name = pkgName; 14891 res.uid = newPackage.applicationInfo.uid; 14892 res.pkg = newPackage; 14893 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14894 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14895 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14896 //to update install status 14897 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14898 mSettings.writeLPr(); 14899 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14900 } 14901 14902 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14903 } 14904 14905 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14906 try { 14907 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14908 installPackageLI(args, res); 14909 } finally { 14910 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14911 } 14912 } 14913 14914 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14915 final int installFlags = args.installFlags; 14916 final String installerPackageName = args.installerPackageName; 14917 final String volumeUuid = args.volumeUuid; 14918 final File tmpPackageFile = new File(args.getCodePath()); 14919 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14920 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14921 || (args.volumeUuid != null)); 14922 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14923 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14924 boolean replace = false; 14925 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14926 if (args.move != null) { 14927 // moving a complete application; perform an initial scan on the new install location 14928 scanFlags |= SCAN_INITIAL; 14929 } 14930 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14931 scanFlags |= SCAN_DONT_KILL_APP; 14932 } 14933 14934 // Result object to be returned 14935 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14936 14937 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14938 14939 // Sanity check 14940 if (ephemeral && (forwardLocked || onExternal)) { 14941 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14942 + " external=" + onExternal); 14943 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14944 return; 14945 } 14946 14947 // Retrieve PackageSettings and parse package 14948 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14949 | PackageParser.PARSE_ENFORCE_CODE 14950 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14951 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14952 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14953 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14954 PackageParser pp = new PackageParser(); 14955 pp.setSeparateProcesses(mSeparateProcesses); 14956 pp.setDisplayMetrics(mMetrics); 14957 14958 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14959 final PackageParser.Package pkg; 14960 try { 14961 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14962 } catch (PackageParserException e) { 14963 res.setError("Failed parse during installPackageLI", e); 14964 return; 14965 } finally { 14966 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14967 } 14968 14969 // If we are installing a clustered package add results for the children 14970 if (pkg.childPackages != null) { 14971 synchronized (mPackages) { 14972 final int childCount = pkg.childPackages.size(); 14973 for (int i = 0; i < childCount; i++) { 14974 PackageParser.Package childPkg = pkg.childPackages.get(i); 14975 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14976 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14977 childRes.pkg = childPkg; 14978 childRes.name = childPkg.packageName; 14979 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14980 if (childPs != null) { 14981 childRes.origUsers = childPs.queryInstalledUsers( 14982 sUserManager.getUserIds(), true); 14983 } 14984 if ((mPackages.containsKey(childPkg.packageName))) { 14985 childRes.removedInfo = new PackageRemovedInfo(); 14986 childRes.removedInfo.removedPackage = childPkg.packageName; 14987 } 14988 if (res.addedChildPackages == null) { 14989 res.addedChildPackages = new ArrayMap<>(); 14990 } 14991 res.addedChildPackages.put(childPkg.packageName, childRes); 14992 } 14993 } 14994 } 14995 14996 // If package doesn't declare API override, mark that we have an install 14997 // time CPU ABI override. 14998 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14999 pkg.cpuAbiOverride = args.abiOverride; 15000 } 15001 15002 String pkgName = res.name = pkg.packageName; 15003 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15004 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15005 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15006 return; 15007 } 15008 } 15009 15010 try { 15011 // either use what we've been given or parse directly from the APK 15012 if (args.certificates != null) { 15013 try { 15014 PackageParser.populateCertificates(pkg, args.certificates); 15015 } catch (PackageParserException e) { 15016 // there was something wrong with the certificates we were given; 15017 // try to pull them from the APK 15018 PackageParser.collectCertificates(pkg, parseFlags); 15019 } 15020 } else { 15021 PackageParser.collectCertificates(pkg, parseFlags); 15022 } 15023 } catch (PackageParserException e) { 15024 res.setError("Failed collect during installPackageLI", e); 15025 return; 15026 } 15027 15028 // Get rid of all references to package scan path via parser. 15029 pp = null; 15030 String oldCodePath = null; 15031 boolean systemApp = false; 15032 synchronized (mPackages) { 15033 // Check if installing already existing package 15034 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15035 String oldName = mSettings.mRenamedPackages.get(pkgName); 15036 if (pkg.mOriginalPackages != null 15037 && pkg.mOriginalPackages.contains(oldName) 15038 && mPackages.containsKey(oldName)) { 15039 // This package is derived from an original package, 15040 // and this device has been updating from that original 15041 // name. We must continue using the original name, so 15042 // rename the new package here. 15043 pkg.setPackageName(oldName); 15044 pkgName = pkg.packageName; 15045 replace = true; 15046 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15047 + oldName + " pkgName=" + pkgName); 15048 } else if (mPackages.containsKey(pkgName)) { 15049 // This package, under its official name, already exists 15050 // on the device; we should replace it. 15051 replace = true; 15052 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15053 } 15054 15055 // Child packages are installed through the parent package 15056 if (pkg.parentPackage != null) { 15057 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15058 "Package " + pkg.packageName + " is child of package " 15059 + pkg.parentPackage.parentPackage + ". Child packages " 15060 + "can be updated only through the parent package."); 15061 return; 15062 } 15063 15064 if (replace) { 15065 // Prevent apps opting out from runtime permissions 15066 PackageParser.Package oldPackage = mPackages.get(pkgName); 15067 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15068 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15069 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15070 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15071 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15072 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15073 + " doesn't support runtime permissions but the old" 15074 + " target SDK " + oldTargetSdk + " does."); 15075 return; 15076 } 15077 15078 // Prevent installing of child packages 15079 if (oldPackage.parentPackage != null) { 15080 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15081 "Package " + pkg.packageName + " is child of package " 15082 + oldPackage.parentPackage + ". Child packages " 15083 + "can be updated only through the parent package."); 15084 return; 15085 } 15086 } 15087 } 15088 15089 PackageSetting ps = mSettings.mPackages.get(pkgName); 15090 if (ps != null) { 15091 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15092 15093 // Quick sanity check that we're signed correctly if updating; 15094 // we'll check this again later when scanning, but we want to 15095 // bail early here before tripping over redefined permissions. 15096 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15097 if (!checkUpgradeKeySetLP(ps, pkg)) { 15098 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15099 + pkg.packageName + " upgrade keys do not match the " 15100 + "previously installed version"); 15101 return; 15102 } 15103 } else { 15104 try { 15105 verifySignaturesLP(ps, pkg); 15106 } catch (PackageManagerException e) { 15107 res.setError(e.error, e.getMessage()); 15108 return; 15109 } 15110 } 15111 15112 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15113 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15114 systemApp = (ps.pkg.applicationInfo.flags & 15115 ApplicationInfo.FLAG_SYSTEM) != 0; 15116 } 15117 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15118 } 15119 15120 // Check whether the newly-scanned package wants to define an already-defined perm 15121 int N = pkg.permissions.size(); 15122 for (int i = N-1; i >= 0; i--) { 15123 PackageParser.Permission perm = pkg.permissions.get(i); 15124 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15125 if (bp != null) { 15126 // If the defining package is signed with our cert, it's okay. This 15127 // also includes the "updating the same package" case, of course. 15128 // "updating same package" could also involve key-rotation. 15129 final boolean sigsOk; 15130 if (bp.sourcePackage.equals(pkg.packageName) 15131 && (bp.packageSetting instanceof PackageSetting) 15132 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15133 scanFlags))) { 15134 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15135 } else { 15136 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15137 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15138 } 15139 if (!sigsOk) { 15140 // If the owning package is the system itself, we log but allow 15141 // install to proceed; we fail the install on all other permission 15142 // redefinitions. 15143 if (!bp.sourcePackage.equals("android")) { 15144 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15145 + pkg.packageName + " attempting to redeclare permission " 15146 + perm.info.name + " already owned by " + bp.sourcePackage); 15147 res.origPermission = perm.info.name; 15148 res.origPackage = bp.sourcePackage; 15149 return; 15150 } else { 15151 Slog.w(TAG, "Package " + pkg.packageName 15152 + " attempting to redeclare system permission " 15153 + perm.info.name + "; ignoring new declaration"); 15154 pkg.permissions.remove(i); 15155 } 15156 } 15157 } 15158 } 15159 } 15160 15161 if (systemApp) { 15162 if (onExternal) { 15163 // Abort update; system app can't be replaced with app on sdcard 15164 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15165 "Cannot install updates to system apps on sdcard"); 15166 return; 15167 } else if (ephemeral) { 15168 // Abort update; system app can't be replaced with an ephemeral app 15169 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15170 "Cannot update a system app with an ephemeral app"); 15171 return; 15172 } 15173 } 15174 15175 if (args.move != null) { 15176 // We did an in-place move, so dex is ready to roll 15177 scanFlags |= SCAN_NO_DEX; 15178 scanFlags |= SCAN_MOVE; 15179 15180 synchronized (mPackages) { 15181 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15182 if (ps == null) { 15183 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15184 "Missing settings for moved package " + pkgName); 15185 } 15186 15187 // We moved the entire application as-is, so bring over the 15188 // previously derived ABI information. 15189 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15190 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15191 } 15192 15193 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15194 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15195 scanFlags |= SCAN_NO_DEX; 15196 15197 try { 15198 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15199 args.abiOverride : pkg.cpuAbiOverride); 15200 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15201 true /* extract libs */); 15202 } catch (PackageManagerException pme) { 15203 Slog.e(TAG, "Error deriving application ABI", pme); 15204 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15205 return; 15206 } 15207 15208 // Shared libraries for the package need to be updated. 15209 synchronized (mPackages) { 15210 try { 15211 updateSharedLibrariesLPw(pkg, null); 15212 } catch (PackageManagerException e) { 15213 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15214 } 15215 } 15216 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15217 // Do not run PackageDexOptimizer through the local performDexOpt 15218 // method because `pkg` may not be in `mPackages` yet. 15219 // 15220 // Also, don't fail application installs if the dexopt step fails. 15221 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15222 null /* instructionSets */, false /* checkProfiles */, 15223 getCompilerFilterForReason(REASON_INSTALL)); 15224 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15225 15226 // Notify BackgroundDexOptService that the package has been changed. 15227 // If this is an update of a package which used to fail to compile, 15228 // BDOS will remove it from its blacklist. 15229 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15230 } 15231 15232 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15233 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15234 return; 15235 } 15236 15237 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15238 15239 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15240 "installPackageLI")) { 15241 if (replace) { 15242 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15243 installerPackageName, res); 15244 } else { 15245 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15246 args.user, installerPackageName, volumeUuid, res); 15247 } 15248 } 15249 synchronized (mPackages) { 15250 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15251 if (ps != null) { 15252 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15253 } 15254 15255 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15256 for (int i = 0; i < childCount; i++) { 15257 PackageParser.Package childPkg = pkg.childPackages.get(i); 15258 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15259 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15260 if (childPs != null) { 15261 childRes.newUsers = childPs.queryInstalledUsers( 15262 sUserManager.getUserIds(), true); 15263 } 15264 } 15265 } 15266 } 15267 15268 private void startIntentFilterVerifications(int userId, boolean replacing, 15269 PackageParser.Package pkg) { 15270 if (mIntentFilterVerifierComponent == null) { 15271 Slog.w(TAG, "No IntentFilter verification will not be done as " 15272 + "there is no IntentFilterVerifier available!"); 15273 return; 15274 } 15275 15276 final int verifierUid = getPackageUid( 15277 mIntentFilterVerifierComponent.getPackageName(), 15278 MATCH_DEBUG_TRIAGED_MISSING, 15279 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15280 15281 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15282 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15283 mHandler.sendMessage(msg); 15284 15285 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15286 for (int i = 0; i < childCount; i++) { 15287 PackageParser.Package childPkg = pkg.childPackages.get(i); 15288 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15289 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15290 mHandler.sendMessage(msg); 15291 } 15292 } 15293 15294 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15295 PackageParser.Package pkg) { 15296 int size = pkg.activities.size(); 15297 if (size == 0) { 15298 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15299 "No activity, so no need to verify any IntentFilter!"); 15300 return; 15301 } 15302 15303 final boolean hasDomainURLs = hasDomainURLs(pkg); 15304 if (!hasDomainURLs) { 15305 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15306 "No domain URLs, so no need to verify any IntentFilter!"); 15307 return; 15308 } 15309 15310 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15311 + " if any IntentFilter from the " + size 15312 + " Activities needs verification ..."); 15313 15314 int count = 0; 15315 final String packageName = pkg.packageName; 15316 15317 synchronized (mPackages) { 15318 // If this is a new install and we see that we've already run verification for this 15319 // package, we have nothing to do: it means the state was restored from backup. 15320 if (!replacing) { 15321 IntentFilterVerificationInfo ivi = 15322 mSettings.getIntentFilterVerificationLPr(packageName); 15323 if (ivi != null) { 15324 if (DEBUG_DOMAIN_VERIFICATION) { 15325 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15326 + ivi.getStatusString()); 15327 } 15328 return; 15329 } 15330 } 15331 15332 // If any filters need to be verified, then all need to be. 15333 boolean needToVerify = false; 15334 for (PackageParser.Activity a : pkg.activities) { 15335 for (ActivityIntentInfo filter : a.intents) { 15336 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15337 if (DEBUG_DOMAIN_VERIFICATION) { 15338 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15339 } 15340 needToVerify = true; 15341 break; 15342 } 15343 } 15344 } 15345 15346 if (needToVerify) { 15347 final int verificationId = mIntentFilterVerificationToken++; 15348 for (PackageParser.Activity a : pkg.activities) { 15349 for (ActivityIntentInfo filter : a.intents) { 15350 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15351 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15352 "Verification needed for IntentFilter:" + filter.toString()); 15353 mIntentFilterVerifier.addOneIntentFilterVerification( 15354 verifierUid, userId, verificationId, filter, packageName); 15355 count++; 15356 } 15357 } 15358 } 15359 } 15360 } 15361 15362 if (count > 0) { 15363 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15364 + " IntentFilter verification" + (count > 1 ? "s" : "") 15365 + " for userId:" + userId); 15366 mIntentFilterVerifier.startVerifications(userId); 15367 } else { 15368 if (DEBUG_DOMAIN_VERIFICATION) { 15369 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15370 } 15371 } 15372 } 15373 15374 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15375 final ComponentName cn = filter.activity.getComponentName(); 15376 final String packageName = cn.getPackageName(); 15377 15378 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15379 packageName); 15380 if (ivi == null) { 15381 return true; 15382 } 15383 int status = ivi.getStatus(); 15384 switch (status) { 15385 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15386 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15387 return true; 15388 15389 default: 15390 // Nothing to do 15391 return false; 15392 } 15393 } 15394 15395 private static boolean isMultiArch(ApplicationInfo info) { 15396 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15397 } 15398 15399 private static boolean isExternal(PackageParser.Package pkg) { 15400 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15401 } 15402 15403 private static boolean isExternal(PackageSetting ps) { 15404 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15405 } 15406 15407 private static boolean isEphemeral(PackageParser.Package pkg) { 15408 return pkg.applicationInfo.isEphemeralApp(); 15409 } 15410 15411 private static boolean isEphemeral(PackageSetting ps) { 15412 return ps.pkg != null && isEphemeral(ps.pkg); 15413 } 15414 15415 private static boolean isSystemApp(PackageParser.Package pkg) { 15416 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15417 } 15418 15419 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15420 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15421 } 15422 15423 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15424 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15425 } 15426 15427 private static boolean isSystemApp(PackageSetting ps) { 15428 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15429 } 15430 15431 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15432 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15433 } 15434 15435 private int packageFlagsToInstallFlags(PackageSetting ps) { 15436 int installFlags = 0; 15437 if (isEphemeral(ps)) { 15438 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15439 } 15440 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15441 // This existing package was an external ASEC install when we have 15442 // the external flag without a UUID 15443 installFlags |= PackageManager.INSTALL_EXTERNAL; 15444 } 15445 if (ps.isForwardLocked()) { 15446 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15447 } 15448 return installFlags; 15449 } 15450 15451 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15452 if (isExternal(pkg)) { 15453 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15454 return StorageManager.UUID_PRIMARY_PHYSICAL; 15455 } else { 15456 return pkg.volumeUuid; 15457 } 15458 } else { 15459 return StorageManager.UUID_PRIVATE_INTERNAL; 15460 } 15461 } 15462 15463 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15464 if (isExternal(pkg)) { 15465 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15466 return mSettings.getExternalVersion(); 15467 } else { 15468 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15469 } 15470 } else { 15471 return mSettings.getInternalVersion(); 15472 } 15473 } 15474 15475 private void deleteTempPackageFiles() { 15476 final FilenameFilter filter = new FilenameFilter() { 15477 public boolean accept(File dir, String name) { 15478 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15479 } 15480 }; 15481 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15482 file.delete(); 15483 } 15484 } 15485 15486 @Override 15487 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15488 int flags) { 15489 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15490 flags); 15491 } 15492 15493 @Override 15494 public void deletePackage(final String packageName, 15495 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15496 mContext.enforceCallingOrSelfPermission( 15497 android.Manifest.permission.DELETE_PACKAGES, null); 15498 Preconditions.checkNotNull(packageName); 15499 Preconditions.checkNotNull(observer); 15500 final int uid = Binder.getCallingUid(); 15501 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15502 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15503 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15504 mContext.enforceCallingOrSelfPermission( 15505 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15506 "deletePackage for user " + userId); 15507 } 15508 15509 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15510 try { 15511 observer.onPackageDeleted(packageName, 15512 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15513 } catch (RemoteException re) { 15514 } 15515 return; 15516 } 15517 15518 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15519 try { 15520 observer.onPackageDeleted(packageName, 15521 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15522 } catch (RemoteException re) { 15523 } 15524 return; 15525 } 15526 15527 if (DEBUG_REMOVE) { 15528 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15529 + " deleteAllUsers: " + deleteAllUsers ); 15530 } 15531 // Queue up an async operation since the package deletion may take a little while. 15532 mHandler.post(new Runnable() { 15533 public void run() { 15534 mHandler.removeCallbacks(this); 15535 int returnCode; 15536 if (!deleteAllUsers) { 15537 returnCode = deletePackageX(packageName, userId, deleteFlags); 15538 } else { 15539 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15540 // If nobody is blocking uninstall, proceed with delete for all users 15541 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15542 returnCode = deletePackageX(packageName, userId, deleteFlags); 15543 } else { 15544 // Otherwise uninstall individually for users with blockUninstalls=false 15545 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15546 for (int userId : users) { 15547 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15548 returnCode = deletePackageX(packageName, userId, userFlags); 15549 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15550 Slog.w(TAG, "Package delete failed for user " + userId 15551 + ", returnCode " + returnCode); 15552 } 15553 } 15554 } 15555 // The app has only been marked uninstalled for certain users. 15556 // We still need to report that delete was blocked 15557 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15558 } 15559 } 15560 try { 15561 observer.onPackageDeleted(packageName, returnCode, null); 15562 } catch (RemoteException e) { 15563 Log.i(TAG, "Observer no longer exists."); 15564 } //end catch 15565 } //end run 15566 }); 15567 } 15568 15569 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15570 int[] result = EMPTY_INT_ARRAY; 15571 for (int userId : userIds) { 15572 if (getBlockUninstallForUser(packageName, userId)) { 15573 result = ArrayUtils.appendInt(result, userId); 15574 } 15575 } 15576 return result; 15577 } 15578 15579 @Override 15580 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15581 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15582 } 15583 15584 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15585 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15586 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15587 try { 15588 if (dpm != null) { 15589 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15590 /* callingUserOnly =*/ false); 15591 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15592 : deviceOwnerComponentName.getPackageName(); 15593 // Does the package contains the device owner? 15594 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15595 // this check is probably not needed, since DO should be registered as a device 15596 // admin on some user too. (Original bug for this: b/17657954) 15597 if (packageName.equals(deviceOwnerPackageName)) { 15598 return true; 15599 } 15600 // Does it contain a device admin for any user? 15601 int[] users; 15602 if (userId == UserHandle.USER_ALL) { 15603 users = sUserManager.getUserIds(); 15604 } else { 15605 users = new int[]{userId}; 15606 } 15607 for (int i = 0; i < users.length; ++i) { 15608 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15609 return true; 15610 } 15611 } 15612 } 15613 } catch (RemoteException e) { 15614 } 15615 return false; 15616 } 15617 15618 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15619 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15620 } 15621 15622 /** 15623 * This method is an internal method that could be get invoked either 15624 * to delete an installed package or to clean up a failed installation. 15625 * After deleting an installed package, a broadcast is sent to notify any 15626 * listeners that the package has been removed. For cleaning up a failed 15627 * installation, the broadcast is not necessary since the package's 15628 * installation wouldn't have sent the initial broadcast either 15629 * The key steps in deleting a package are 15630 * deleting the package information in internal structures like mPackages, 15631 * deleting the packages base directories through installd 15632 * updating mSettings to reflect current status 15633 * persisting settings for later use 15634 * sending a broadcast if necessary 15635 */ 15636 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15637 final PackageRemovedInfo info = new PackageRemovedInfo(); 15638 final boolean res; 15639 15640 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15641 ? UserHandle.USER_ALL : userId; 15642 15643 if (isPackageDeviceAdmin(packageName, removeUser)) { 15644 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15645 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15646 } 15647 15648 PackageSetting uninstalledPs = null; 15649 15650 // for the uninstall-updates case and restricted profiles, remember the per- 15651 // user handle installed state 15652 int[] allUsers; 15653 synchronized (mPackages) { 15654 uninstalledPs = mSettings.mPackages.get(packageName); 15655 if (uninstalledPs == null) { 15656 Slog.w(TAG, "Not removing non-existent package " + packageName); 15657 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15658 } 15659 allUsers = sUserManager.getUserIds(); 15660 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15661 } 15662 15663 final int freezeUser; 15664 if (isUpdatedSystemApp(uninstalledPs) 15665 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15666 // We're downgrading a system app, which will apply to all users, so 15667 // freeze them all during the downgrade 15668 freezeUser = UserHandle.USER_ALL; 15669 } else { 15670 freezeUser = removeUser; 15671 } 15672 15673 synchronized (mInstallLock) { 15674 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15675 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15676 deleteFlags, "deletePackageX")) { 15677 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15678 deleteFlags | REMOVE_CHATTY, info, true, null); 15679 } 15680 synchronized (mPackages) { 15681 if (res) { 15682 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15683 } 15684 } 15685 } 15686 15687 if (res) { 15688 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15689 info.sendPackageRemovedBroadcasts(killApp); 15690 info.sendSystemPackageUpdatedBroadcasts(); 15691 info.sendSystemPackageAppearedBroadcasts(); 15692 } 15693 // Force a gc here. 15694 Runtime.getRuntime().gc(); 15695 // Delete the resources here after sending the broadcast to let 15696 // other processes clean up before deleting resources. 15697 if (info.args != null) { 15698 synchronized (mInstallLock) { 15699 info.args.doPostDeleteLI(true); 15700 } 15701 } 15702 15703 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15704 } 15705 15706 class PackageRemovedInfo { 15707 String removedPackage; 15708 int uid = -1; 15709 int removedAppId = -1; 15710 int[] origUsers; 15711 int[] removedUsers = null; 15712 boolean isRemovedPackageSystemUpdate = false; 15713 boolean isUpdate; 15714 boolean dataRemoved; 15715 boolean removedForAllUsers; 15716 // Clean up resources deleted packages. 15717 InstallArgs args = null; 15718 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15719 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15720 15721 void sendPackageRemovedBroadcasts(boolean killApp) { 15722 sendPackageRemovedBroadcastInternal(killApp); 15723 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15724 for (int i = 0; i < childCount; i++) { 15725 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15726 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15727 } 15728 } 15729 15730 void sendSystemPackageUpdatedBroadcasts() { 15731 if (isRemovedPackageSystemUpdate) { 15732 sendSystemPackageUpdatedBroadcastsInternal(); 15733 final int childCount = (removedChildPackages != null) 15734 ? removedChildPackages.size() : 0; 15735 for (int i = 0; i < childCount; i++) { 15736 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15737 if (childInfo.isRemovedPackageSystemUpdate) { 15738 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15739 } 15740 } 15741 } 15742 } 15743 15744 void sendSystemPackageAppearedBroadcasts() { 15745 final int packageCount = (appearedChildPackages != null) 15746 ? appearedChildPackages.size() : 0; 15747 for (int i = 0; i < packageCount; i++) { 15748 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15749 for (int userId : installedInfo.newUsers) { 15750 sendPackageAddedForUser(installedInfo.name, true, 15751 UserHandle.getAppId(installedInfo.uid), userId); 15752 } 15753 } 15754 } 15755 15756 private void sendSystemPackageUpdatedBroadcastsInternal() { 15757 Bundle extras = new Bundle(2); 15758 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15759 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15760 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15761 extras, 0, null, null, null); 15762 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15763 extras, 0, null, null, null); 15764 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15765 null, 0, removedPackage, null, null); 15766 } 15767 15768 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15769 Bundle extras = new Bundle(2); 15770 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15771 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15772 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15773 if (isUpdate || isRemovedPackageSystemUpdate) { 15774 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15775 } 15776 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15777 if (removedPackage != null) { 15778 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15779 extras, 0, null, null, removedUsers); 15780 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15781 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15782 removedPackage, extras, 0, null, null, removedUsers); 15783 } 15784 } 15785 if (removedAppId >= 0) { 15786 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15787 removedUsers); 15788 } 15789 } 15790 } 15791 15792 /* 15793 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15794 * flag is not set, the data directory is removed as well. 15795 * make sure this flag is set for partially installed apps. If not its meaningless to 15796 * delete a partially installed application. 15797 */ 15798 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15799 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15800 String packageName = ps.name; 15801 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15802 // Retrieve object to delete permissions for shared user later on 15803 final PackageParser.Package deletedPkg; 15804 final PackageSetting deletedPs; 15805 // reader 15806 synchronized (mPackages) { 15807 deletedPkg = mPackages.get(packageName); 15808 deletedPs = mSettings.mPackages.get(packageName); 15809 if (outInfo != null) { 15810 outInfo.removedPackage = packageName; 15811 outInfo.removedUsers = deletedPs != null 15812 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15813 : null; 15814 } 15815 } 15816 15817 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15818 15819 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15820 final PackageParser.Package resolvedPkg; 15821 if (deletedPkg != null) { 15822 resolvedPkg = deletedPkg; 15823 } else { 15824 // We don't have a parsed package when it lives on an ejected 15825 // adopted storage device, so fake something together 15826 resolvedPkg = new PackageParser.Package(ps.name); 15827 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15828 } 15829 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15830 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15831 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15832 if (outInfo != null) { 15833 outInfo.dataRemoved = true; 15834 } 15835 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15836 } 15837 15838 // writer 15839 synchronized (mPackages) { 15840 if (deletedPs != null) { 15841 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15842 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15843 clearDefaultBrowserIfNeeded(packageName); 15844 if (outInfo != null) { 15845 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15846 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15847 } 15848 updatePermissionsLPw(deletedPs.name, null, 0); 15849 if (deletedPs.sharedUser != null) { 15850 // Remove permissions associated with package. Since runtime 15851 // permissions are per user we have to kill the removed package 15852 // or packages running under the shared user of the removed 15853 // package if revoking the permissions requested only by the removed 15854 // package is successful and this causes a change in gids. 15855 for (int userId : UserManagerService.getInstance().getUserIds()) { 15856 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15857 userId); 15858 if (userIdToKill == UserHandle.USER_ALL 15859 || userIdToKill >= UserHandle.USER_SYSTEM) { 15860 // If gids changed for this user, kill all affected packages. 15861 mHandler.post(new Runnable() { 15862 @Override 15863 public void run() { 15864 // This has to happen with no lock held. 15865 killApplication(deletedPs.name, deletedPs.appId, 15866 KILL_APP_REASON_GIDS_CHANGED); 15867 } 15868 }); 15869 break; 15870 } 15871 } 15872 } 15873 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15874 } 15875 // make sure to preserve per-user disabled state if this removal was just 15876 // a downgrade of a system app to the factory package 15877 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15878 if (DEBUG_REMOVE) { 15879 Slog.d(TAG, "Propagating install state across downgrade"); 15880 } 15881 for (int userId : allUserHandles) { 15882 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15883 if (DEBUG_REMOVE) { 15884 Slog.d(TAG, " user " + userId + " => " + installed); 15885 } 15886 ps.setInstalled(installed, userId); 15887 } 15888 } 15889 } 15890 // can downgrade to reader 15891 if (writeSettings) { 15892 // Save settings now 15893 mSettings.writeLPr(); 15894 } 15895 } 15896 if (outInfo != null) { 15897 // A user ID was deleted here. Go through all users and remove it 15898 // from KeyStore. 15899 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15900 } 15901 } 15902 15903 static boolean locationIsPrivileged(File path) { 15904 try { 15905 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15906 .getCanonicalPath(); 15907 return path.getCanonicalPath().startsWith(privilegedAppDir); 15908 } catch (IOException e) { 15909 Slog.e(TAG, "Unable to access code path " + path); 15910 } 15911 return false; 15912 } 15913 15914 /* 15915 * Tries to delete system package. 15916 */ 15917 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15918 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15919 boolean writeSettings) { 15920 if (deletedPs.parentPackageName != null) { 15921 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15922 return false; 15923 } 15924 15925 final boolean applyUserRestrictions 15926 = (allUserHandles != null) && (outInfo.origUsers != null); 15927 final PackageSetting disabledPs; 15928 // Confirm if the system package has been updated 15929 // An updated system app can be deleted. This will also have to restore 15930 // the system pkg from system partition 15931 // reader 15932 synchronized (mPackages) { 15933 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15934 } 15935 15936 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15937 + " disabledPs=" + disabledPs); 15938 15939 if (disabledPs == null) { 15940 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15941 return false; 15942 } else if (DEBUG_REMOVE) { 15943 Slog.d(TAG, "Deleting system pkg from data partition"); 15944 } 15945 15946 if (DEBUG_REMOVE) { 15947 if (applyUserRestrictions) { 15948 Slog.d(TAG, "Remembering install states:"); 15949 for (int userId : allUserHandles) { 15950 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15951 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15952 } 15953 } 15954 } 15955 15956 // Delete the updated package 15957 outInfo.isRemovedPackageSystemUpdate = true; 15958 if (outInfo.removedChildPackages != null) { 15959 final int childCount = (deletedPs.childPackageNames != null) 15960 ? deletedPs.childPackageNames.size() : 0; 15961 for (int i = 0; i < childCount; i++) { 15962 String childPackageName = deletedPs.childPackageNames.get(i); 15963 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15964 .contains(childPackageName)) { 15965 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15966 childPackageName); 15967 if (childInfo != null) { 15968 childInfo.isRemovedPackageSystemUpdate = true; 15969 } 15970 } 15971 } 15972 } 15973 15974 if (disabledPs.versionCode < deletedPs.versionCode) { 15975 // Delete data for downgrades 15976 flags &= ~PackageManager.DELETE_KEEP_DATA; 15977 } else { 15978 // Preserve data by setting flag 15979 flags |= PackageManager.DELETE_KEEP_DATA; 15980 } 15981 15982 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15983 outInfo, writeSettings, disabledPs.pkg); 15984 if (!ret) { 15985 return false; 15986 } 15987 15988 // writer 15989 synchronized (mPackages) { 15990 // Reinstate the old system package 15991 enableSystemPackageLPw(disabledPs.pkg); 15992 // Remove any native libraries from the upgraded package. 15993 removeNativeBinariesLI(deletedPs); 15994 } 15995 15996 // Install the system package 15997 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15998 int parseFlags = mDefParseFlags 15999 | PackageParser.PARSE_MUST_BE_APK 16000 | PackageParser.PARSE_IS_SYSTEM 16001 | PackageParser.PARSE_IS_SYSTEM_DIR; 16002 if (locationIsPrivileged(disabledPs.codePath)) { 16003 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16004 } 16005 16006 final PackageParser.Package newPkg; 16007 try { 16008 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 16009 } catch (PackageManagerException e) { 16010 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16011 + e.getMessage()); 16012 return false; 16013 } 16014 16015 prepareAppDataAfterInstallLIF(newPkg); 16016 16017 // writer 16018 synchronized (mPackages) { 16019 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16020 16021 // Propagate the permissions state as we do not want to drop on the floor 16022 // runtime permissions. The update permissions method below will take 16023 // care of removing obsolete permissions and grant install permissions. 16024 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16025 updatePermissionsLPw(newPkg.packageName, newPkg, 16026 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16027 16028 if (applyUserRestrictions) { 16029 if (DEBUG_REMOVE) { 16030 Slog.d(TAG, "Propagating install state across reinstall"); 16031 } 16032 for (int userId : allUserHandles) { 16033 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16034 if (DEBUG_REMOVE) { 16035 Slog.d(TAG, " user " + userId + " => " + installed); 16036 } 16037 ps.setInstalled(installed, userId); 16038 16039 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16040 } 16041 // Regardless of writeSettings we need to ensure that this restriction 16042 // state propagation is persisted 16043 mSettings.writeAllUsersPackageRestrictionsLPr(); 16044 } 16045 // can downgrade to reader here 16046 if (writeSettings) { 16047 mSettings.writeLPr(); 16048 } 16049 } 16050 return true; 16051 } 16052 16053 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16054 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16055 PackageRemovedInfo outInfo, boolean writeSettings, 16056 PackageParser.Package replacingPackage) { 16057 synchronized (mPackages) { 16058 if (outInfo != null) { 16059 outInfo.uid = ps.appId; 16060 } 16061 16062 if (outInfo != null && outInfo.removedChildPackages != null) { 16063 final int childCount = (ps.childPackageNames != null) 16064 ? ps.childPackageNames.size() : 0; 16065 for (int i = 0; i < childCount; i++) { 16066 String childPackageName = ps.childPackageNames.get(i); 16067 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16068 if (childPs == null) { 16069 return false; 16070 } 16071 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16072 childPackageName); 16073 if (childInfo != null) { 16074 childInfo.uid = childPs.appId; 16075 } 16076 } 16077 } 16078 } 16079 16080 // Delete package data from internal structures and also remove data if flag is set 16081 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16082 16083 // Delete the child packages data 16084 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16085 for (int i = 0; i < childCount; i++) { 16086 PackageSetting childPs; 16087 synchronized (mPackages) { 16088 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16089 } 16090 if (childPs != null) { 16091 PackageRemovedInfo childOutInfo = (outInfo != null 16092 && outInfo.removedChildPackages != null) 16093 ? outInfo.removedChildPackages.get(childPs.name) : null; 16094 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16095 && (replacingPackage != null 16096 && !replacingPackage.hasChildPackage(childPs.name)) 16097 ? flags & ~DELETE_KEEP_DATA : flags; 16098 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16099 deleteFlags, writeSettings); 16100 } 16101 } 16102 16103 // Delete application code and resources only for parent packages 16104 if (ps.parentPackageName == null) { 16105 if (deleteCodeAndResources && (outInfo != null)) { 16106 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16107 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16108 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16109 } 16110 } 16111 16112 return true; 16113 } 16114 16115 @Override 16116 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16117 int userId) { 16118 mContext.enforceCallingOrSelfPermission( 16119 android.Manifest.permission.DELETE_PACKAGES, null); 16120 synchronized (mPackages) { 16121 PackageSetting ps = mSettings.mPackages.get(packageName); 16122 if (ps == null) { 16123 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16124 return false; 16125 } 16126 if (!ps.getInstalled(userId)) { 16127 // Can't block uninstall for an app that is not installed or enabled. 16128 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16129 return false; 16130 } 16131 ps.setBlockUninstall(blockUninstall, userId); 16132 mSettings.writePackageRestrictionsLPr(userId); 16133 } 16134 return true; 16135 } 16136 16137 @Override 16138 public boolean getBlockUninstallForUser(String packageName, int userId) { 16139 synchronized (mPackages) { 16140 PackageSetting ps = mSettings.mPackages.get(packageName); 16141 if (ps == null) { 16142 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16143 return false; 16144 } 16145 return ps.getBlockUninstall(userId); 16146 } 16147 } 16148 16149 @Override 16150 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16151 int callingUid = Binder.getCallingUid(); 16152 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16153 throw new SecurityException( 16154 "setRequiredForSystemUser can only be run by the system or root"); 16155 } 16156 synchronized (mPackages) { 16157 PackageSetting ps = mSettings.mPackages.get(packageName); 16158 if (ps == null) { 16159 Log.w(TAG, "Package doesn't exist: " + packageName); 16160 return false; 16161 } 16162 if (systemUserApp) { 16163 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16164 } else { 16165 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16166 } 16167 mSettings.writeLPr(); 16168 } 16169 return true; 16170 } 16171 16172 /* 16173 * This method handles package deletion in general 16174 */ 16175 private boolean deletePackageLIF(String packageName, UserHandle user, 16176 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16177 PackageRemovedInfo outInfo, boolean writeSettings, 16178 PackageParser.Package replacingPackage) { 16179 if (packageName == null) { 16180 Slog.w(TAG, "Attempt to delete null packageName."); 16181 return false; 16182 } 16183 16184 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16185 16186 PackageSetting ps; 16187 16188 synchronized (mPackages) { 16189 ps = mSettings.mPackages.get(packageName); 16190 if (ps == null) { 16191 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16192 return false; 16193 } 16194 16195 if (ps.parentPackageName != null && (!isSystemApp(ps) 16196 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16197 if (DEBUG_REMOVE) { 16198 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16199 + ((user == null) ? UserHandle.USER_ALL : user)); 16200 } 16201 final int removedUserId = (user != null) ? user.getIdentifier() 16202 : UserHandle.USER_ALL; 16203 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16204 return false; 16205 } 16206 markPackageUninstalledForUserLPw(ps, user); 16207 scheduleWritePackageRestrictionsLocked(user); 16208 return true; 16209 } 16210 } 16211 16212 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16213 && user.getIdentifier() != UserHandle.USER_ALL)) { 16214 // The caller is asking that the package only be deleted for a single 16215 // user. To do this, we just mark its uninstalled state and delete 16216 // its data. If this is a system app, we only allow this to happen if 16217 // they have set the special DELETE_SYSTEM_APP which requests different 16218 // semantics than normal for uninstalling system apps. 16219 markPackageUninstalledForUserLPw(ps, user); 16220 16221 if (!isSystemApp(ps)) { 16222 // Do not uninstall the APK if an app should be cached 16223 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16224 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16225 // Other user still have this package installed, so all 16226 // we need to do is clear this user's data and save that 16227 // it is uninstalled. 16228 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16229 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16230 return false; 16231 } 16232 scheduleWritePackageRestrictionsLocked(user); 16233 return true; 16234 } else { 16235 // We need to set it back to 'installed' so the uninstall 16236 // broadcasts will be sent correctly. 16237 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16238 ps.setInstalled(true, user.getIdentifier()); 16239 } 16240 } else { 16241 // This is a system app, so we assume that the 16242 // other users still have this package installed, so all 16243 // we need to do is clear this user's data and save that 16244 // it is uninstalled. 16245 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16246 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16247 return false; 16248 } 16249 scheduleWritePackageRestrictionsLocked(user); 16250 return true; 16251 } 16252 } 16253 16254 // If we are deleting a composite package for all users, keep track 16255 // of result for each child. 16256 if (ps.childPackageNames != null && outInfo != null) { 16257 synchronized (mPackages) { 16258 final int childCount = ps.childPackageNames.size(); 16259 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16260 for (int i = 0; i < childCount; i++) { 16261 String childPackageName = ps.childPackageNames.get(i); 16262 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16263 childInfo.removedPackage = childPackageName; 16264 outInfo.removedChildPackages.put(childPackageName, childInfo); 16265 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16266 if (childPs != null) { 16267 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16268 } 16269 } 16270 } 16271 } 16272 16273 boolean ret = false; 16274 if (isSystemApp(ps)) { 16275 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16276 // When an updated system application is deleted we delete the existing resources 16277 // as well and fall back to existing code in system partition 16278 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16279 } else { 16280 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16281 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16282 outInfo, writeSettings, replacingPackage); 16283 } 16284 16285 // Take a note whether we deleted the package for all users 16286 if (outInfo != null) { 16287 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16288 if (outInfo.removedChildPackages != null) { 16289 synchronized (mPackages) { 16290 final int childCount = outInfo.removedChildPackages.size(); 16291 for (int i = 0; i < childCount; i++) { 16292 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16293 if (childInfo != null) { 16294 childInfo.removedForAllUsers = mPackages.get( 16295 childInfo.removedPackage) == null; 16296 } 16297 } 16298 } 16299 } 16300 // If we uninstalled an update to a system app there may be some 16301 // child packages that appeared as they are declared in the system 16302 // app but were not declared in the update. 16303 if (isSystemApp(ps)) { 16304 synchronized (mPackages) { 16305 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16306 final int childCount = (updatedPs.childPackageNames != null) 16307 ? updatedPs.childPackageNames.size() : 0; 16308 for (int i = 0; i < childCount; i++) { 16309 String childPackageName = updatedPs.childPackageNames.get(i); 16310 if (outInfo.removedChildPackages == null 16311 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16312 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16313 if (childPs == null) { 16314 continue; 16315 } 16316 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16317 installRes.name = childPackageName; 16318 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16319 installRes.pkg = mPackages.get(childPackageName); 16320 installRes.uid = childPs.pkg.applicationInfo.uid; 16321 if (outInfo.appearedChildPackages == null) { 16322 outInfo.appearedChildPackages = new ArrayMap<>(); 16323 } 16324 outInfo.appearedChildPackages.put(childPackageName, installRes); 16325 } 16326 } 16327 } 16328 } 16329 } 16330 16331 return ret; 16332 } 16333 16334 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16335 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16336 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16337 for (int nextUserId : userIds) { 16338 if (DEBUG_REMOVE) { 16339 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16340 } 16341 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16342 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16343 false /*hidden*/, false /*suspended*/, null, null, null, 16344 false /*blockUninstall*/, 16345 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16346 } 16347 } 16348 16349 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16350 PackageRemovedInfo outInfo) { 16351 final PackageParser.Package pkg; 16352 synchronized (mPackages) { 16353 pkg = mPackages.get(ps.name); 16354 } 16355 16356 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16357 : new int[] {userId}; 16358 for (int nextUserId : userIds) { 16359 if (DEBUG_REMOVE) { 16360 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16361 + nextUserId); 16362 } 16363 16364 destroyAppDataLIF(pkg, userId, 16365 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16366 destroyAppProfilesLIF(pkg, userId); 16367 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16368 schedulePackageCleaning(ps.name, nextUserId, false); 16369 synchronized (mPackages) { 16370 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16371 scheduleWritePackageRestrictionsLocked(nextUserId); 16372 } 16373 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16374 } 16375 } 16376 16377 if (outInfo != null) { 16378 outInfo.removedPackage = ps.name; 16379 outInfo.removedAppId = ps.appId; 16380 outInfo.removedUsers = userIds; 16381 } 16382 16383 return true; 16384 } 16385 16386 private final class ClearStorageConnection implements ServiceConnection { 16387 IMediaContainerService mContainerService; 16388 16389 @Override 16390 public void onServiceConnected(ComponentName name, IBinder service) { 16391 synchronized (this) { 16392 mContainerService = IMediaContainerService.Stub.asInterface(service); 16393 notifyAll(); 16394 } 16395 } 16396 16397 @Override 16398 public void onServiceDisconnected(ComponentName name) { 16399 } 16400 } 16401 16402 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16403 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16404 16405 final boolean mounted; 16406 if (Environment.isExternalStorageEmulated()) { 16407 mounted = true; 16408 } else { 16409 final String status = Environment.getExternalStorageState(); 16410 16411 mounted = status.equals(Environment.MEDIA_MOUNTED) 16412 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16413 } 16414 16415 if (!mounted) { 16416 return; 16417 } 16418 16419 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16420 int[] users; 16421 if (userId == UserHandle.USER_ALL) { 16422 users = sUserManager.getUserIds(); 16423 } else { 16424 users = new int[] { userId }; 16425 } 16426 final ClearStorageConnection conn = new ClearStorageConnection(); 16427 if (mContext.bindServiceAsUser( 16428 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16429 try { 16430 for (int curUser : users) { 16431 long timeout = SystemClock.uptimeMillis() + 5000; 16432 synchronized (conn) { 16433 long now; 16434 while (conn.mContainerService == null && 16435 (now = SystemClock.uptimeMillis()) < timeout) { 16436 try { 16437 conn.wait(timeout - now); 16438 } catch (InterruptedException e) { 16439 } 16440 } 16441 } 16442 if (conn.mContainerService == null) { 16443 return; 16444 } 16445 16446 final UserEnvironment userEnv = new UserEnvironment(curUser); 16447 clearDirectory(conn.mContainerService, 16448 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16449 if (allData) { 16450 clearDirectory(conn.mContainerService, 16451 userEnv.buildExternalStorageAppDataDirs(packageName)); 16452 clearDirectory(conn.mContainerService, 16453 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16454 } 16455 } 16456 } finally { 16457 mContext.unbindService(conn); 16458 } 16459 } 16460 } 16461 16462 @Override 16463 public void clearApplicationProfileData(String packageName) { 16464 enforceSystemOrRoot("Only the system can clear all profile data"); 16465 16466 final PackageParser.Package pkg; 16467 synchronized (mPackages) { 16468 pkg = mPackages.get(packageName); 16469 } 16470 16471 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16472 synchronized (mInstallLock) { 16473 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16474 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16475 true /* removeBaseMarker */); 16476 } 16477 } 16478 } 16479 16480 @Override 16481 public void clearApplicationUserData(final String packageName, 16482 final IPackageDataObserver observer, final int userId) { 16483 mContext.enforceCallingOrSelfPermission( 16484 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16485 16486 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16487 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16488 16489 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16490 throw new SecurityException("Cannot clear data for a protected package: " 16491 + packageName); 16492 } 16493 // Queue up an async operation since the package deletion may take a little while. 16494 mHandler.post(new Runnable() { 16495 public void run() { 16496 mHandler.removeCallbacks(this); 16497 final boolean succeeded; 16498 try (PackageFreezer freezer = freezePackage(packageName, 16499 "clearApplicationUserData")) { 16500 synchronized (mInstallLock) { 16501 succeeded = clearApplicationUserDataLIF(packageName, userId); 16502 } 16503 clearExternalStorageDataSync(packageName, userId, true); 16504 } 16505 if (succeeded) { 16506 // invoke DeviceStorageMonitor's update method to clear any notifications 16507 DeviceStorageMonitorInternal dsm = LocalServices 16508 .getService(DeviceStorageMonitorInternal.class); 16509 if (dsm != null) { 16510 dsm.checkMemory(); 16511 } 16512 } 16513 if(observer != null) { 16514 try { 16515 observer.onRemoveCompleted(packageName, succeeded); 16516 } catch (RemoteException e) { 16517 Log.i(TAG, "Observer no longer exists."); 16518 } 16519 } //end if observer 16520 } //end run 16521 }); 16522 } 16523 16524 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16525 if (packageName == null) { 16526 Slog.w(TAG, "Attempt to delete null packageName."); 16527 return false; 16528 } 16529 16530 // Try finding details about the requested package 16531 PackageParser.Package pkg; 16532 synchronized (mPackages) { 16533 pkg = mPackages.get(packageName); 16534 if (pkg == null) { 16535 final PackageSetting ps = mSettings.mPackages.get(packageName); 16536 if (ps != null) { 16537 pkg = ps.pkg; 16538 } 16539 } 16540 16541 if (pkg == null) { 16542 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16543 return false; 16544 } 16545 16546 PackageSetting ps = (PackageSetting) pkg.mExtras; 16547 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16548 } 16549 16550 clearAppDataLIF(pkg, userId, 16551 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16552 16553 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16554 removeKeystoreDataIfNeeded(userId, appId); 16555 16556 UserManagerInternal umInternal = getUserManagerInternal(); 16557 final int flags; 16558 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16559 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16560 } else if (umInternal.isUserRunning(userId)) { 16561 flags = StorageManager.FLAG_STORAGE_DE; 16562 } else { 16563 flags = 0; 16564 } 16565 prepareAppDataContentsLIF(pkg, userId, flags); 16566 16567 return true; 16568 } 16569 16570 /** 16571 * Reverts user permission state changes (permissions and flags) in 16572 * all packages for a given user. 16573 * 16574 * @param userId The device user for which to do a reset. 16575 */ 16576 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16577 final int packageCount = mPackages.size(); 16578 for (int i = 0; i < packageCount; i++) { 16579 PackageParser.Package pkg = mPackages.valueAt(i); 16580 PackageSetting ps = (PackageSetting) pkg.mExtras; 16581 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16582 } 16583 } 16584 16585 private void resetNetworkPolicies(int userId) { 16586 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16587 } 16588 16589 /** 16590 * Reverts user permission state changes (permissions and flags). 16591 * 16592 * @param ps The package for which to reset. 16593 * @param userId The device user for which to do a reset. 16594 */ 16595 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16596 final PackageSetting ps, final int userId) { 16597 if (ps.pkg == null) { 16598 return; 16599 } 16600 16601 // These are flags that can change base on user actions. 16602 final int userSettableMask = FLAG_PERMISSION_USER_SET 16603 | FLAG_PERMISSION_USER_FIXED 16604 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16605 | FLAG_PERMISSION_REVIEW_REQUIRED; 16606 16607 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16608 | FLAG_PERMISSION_POLICY_FIXED; 16609 16610 boolean writeInstallPermissions = false; 16611 boolean writeRuntimePermissions = false; 16612 16613 final int permissionCount = ps.pkg.requestedPermissions.size(); 16614 for (int i = 0; i < permissionCount; i++) { 16615 String permission = ps.pkg.requestedPermissions.get(i); 16616 16617 BasePermission bp = mSettings.mPermissions.get(permission); 16618 if (bp == null) { 16619 continue; 16620 } 16621 16622 // If shared user we just reset the state to which only this app contributed. 16623 if (ps.sharedUser != null) { 16624 boolean used = false; 16625 final int packageCount = ps.sharedUser.packages.size(); 16626 for (int j = 0; j < packageCount; j++) { 16627 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16628 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16629 && pkg.pkg.requestedPermissions.contains(permission)) { 16630 used = true; 16631 break; 16632 } 16633 } 16634 if (used) { 16635 continue; 16636 } 16637 } 16638 16639 PermissionsState permissionsState = ps.getPermissionsState(); 16640 16641 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16642 16643 // Always clear the user settable flags. 16644 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16645 bp.name) != null; 16646 // If permission review is enabled and this is a legacy app, mark the 16647 // permission as requiring a review as this is the initial state. 16648 int flags = 0; 16649 if (Build.PERMISSIONS_REVIEW_REQUIRED 16650 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16651 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16652 } 16653 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16654 if (hasInstallState) { 16655 writeInstallPermissions = true; 16656 } else { 16657 writeRuntimePermissions = true; 16658 } 16659 } 16660 16661 // Below is only runtime permission handling. 16662 if (!bp.isRuntime()) { 16663 continue; 16664 } 16665 16666 // Never clobber system or policy. 16667 if ((oldFlags & policyOrSystemFlags) != 0) { 16668 continue; 16669 } 16670 16671 // If this permission was granted by default, make sure it is. 16672 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16673 if (permissionsState.grantRuntimePermission(bp, userId) 16674 != PERMISSION_OPERATION_FAILURE) { 16675 writeRuntimePermissions = true; 16676 } 16677 // If permission review is enabled the permissions for a legacy apps 16678 // are represented as constantly granted runtime ones, so don't revoke. 16679 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16680 // Otherwise, reset the permission. 16681 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16682 switch (revokeResult) { 16683 case PERMISSION_OPERATION_SUCCESS: 16684 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16685 writeRuntimePermissions = true; 16686 final int appId = ps.appId; 16687 mHandler.post(new Runnable() { 16688 @Override 16689 public void run() { 16690 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16691 } 16692 }); 16693 } break; 16694 } 16695 } 16696 } 16697 16698 // Synchronously write as we are taking permissions away. 16699 if (writeRuntimePermissions) { 16700 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16701 } 16702 16703 // Synchronously write as we are taking permissions away. 16704 if (writeInstallPermissions) { 16705 mSettings.writeLPr(); 16706 } 16707 } 16708 16709 /** 16710 * Remove entries from the keystore daemon. Will only remove it if the 16711 * {@code appId} is valid. 16712 */ 16713 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16714 if (appId < 0) { 16715 return; 16716 } 16717 16718 final KeyStore keyStore = KeyStore.getInstance(); 16719 if (keyStore != null) { 16720 if (userId == UserHandle.USER_ALL) { 16721 for (final int individual : sUserManager.getUserIds()) { 16722 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16723 } 16724 } else { 16725 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16726 } 16727 } else { 16728 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16729 } 16730 } 16731 16732 @Override 16733 public void deleteApplicationCacheFiles(final String packageName, 16734 final IPackageDataObserver observer) { 16735 final int userId = UserHandle.getCallingUserId(); 16736 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16737 } 16738 16739 @Override 16740 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16741 final IPackageDataObserver observer) { 16742 mContext.enforceCallingOrSelfPermission( 16743 android.Manifest.permission.DELETE_CACHE_FILES, null); 16744 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16745 /* requireFullPermission= */ true, /* checkShell= */ false, 16746 "delete application cache files"); 16747 16748 final PackageParser.Package pkg; 16749 synchronized (mPackages) { 16750 pkg = mPackages.get(packageName); 16751 } 16752 16753 // Queue up an async operation since the package deletion may take a little while. 16754 mHandler.post(new Runnable() { 16755 public void run() { 16756 synchronized (mInstallLock) { 16757 final int flags = StorageManager.FLAG_STORAGE_DE 16758 | StorageManager.FLAG_STORAGE_CE; 16759 // We're only clearing cache files, so we don't care if the 16760 // app is unfrozen and still able to run 16761 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16762 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16763 } 16764 clearExternalStorageDataSync(packageName, userId, false); 16765 if (observer != null) { 16766 try { 16767 observer.onRemoveCompleted(packageName, true); 16768 } catch (RemoteException e) { 16769 Log.i(TAG, "Observer no longer exists."); 16770 } 16771 } 16772 } 16773 }); 16774 } 16775 16776 @Override 16777 public void getPackageSizeInfo(final String packageName, int userHandle, 16778 final IPackageStatsObserver observer) { 16779 mContext.enforceCallingOrSelfPermission( 16780 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16781 if (packageName == null) { 16782 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16783 } 16784 16785 PackageStats stats = new PackageStats(packageName, userHandle); 16786 16787 /* 16788 * Queue up an async operation since the package measurement may take a 16789 * little while. 16790 */ 16791 Message msg = mHandler.obtainMessage(INIT_COPY); 16792 msg.obj = new MeasureParams(stats, observer); 16793 mHandler.sendMessage(msg); 16794 } 16795 16796 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16797 final PackageSetting ps; 16798 synchronized (mPackages) { 16799 ps = mSettings.mPackages.get(packageName); 16800 if (ps == null) { 16801 Slog.w(TAG, "Failed to find settings for " + packageName); 16802 return false; 16803 } 16804 } 16805 try { 16806 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16807 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16808 ps.getCeDataInode(userId), ps.codePathString, stats); 16809 } catch (InstallerException e) { 16810 Slog.w(TAG, String.valueOf(e)); 16811 return false; 16812 } 16813 16814 // For now, ignore code size of packages on system partition 16815 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16816 stats.codeSize = 0; 16817 } 16818 16819 return true; 16820 } 16821 16822 private int getUidTargetSdkVersionLockedLPr(int uid) { 16823 Object obj = mSettings.getUserIdLPr(uid); 16824 if (obj instanceof SharedUserSetting) { 16825 final SharedUserSetting sus = (SharedUserSetting) obj; 16826 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16827 final Iterator<PackageSetting> it = sus.packages.iterator(); 16828 while (it.hasNext()) { 16829 final PackageSetting ps = it.next(); 16830 if (ps.pkg != null) { 16831 int v = ps.pkg.applicationInfo.targetSdkVersion; 16832 if (v < vers) vers = v; 16833 } 16834 } 16835 return vers; 16836 } else if (obj instanceof PackageSetting) { 16837 final PackageSetting ps = (PackageSetting) obj; 16838 if (ps.pkg != null) { 16839 return ps.pkg.applicationInfo.targetSdkVersion; 16840 } 16841 } 16842 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16843 } 16844 16845 @Override 16846 public void addPreferredActivity(IntentFilter filter, int match, 16847 ComponentName[] set, ComponentName activity, int userId) { 16848 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16849 "Adding preferred"); 16850 } 16851 16852 private void addPreferredActivityInternal(IntentFilter filter, int match, 16853 ComponentName[] set, ComponentName activity, boolean always, int userId, 16854 String opname) { 16855 // writer 16856 int callingUid = Binder.getCallingUid(); 16857 enforceCrossUserPermission(callingUid, userId, 16858 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16859 if (filter.countActions() == 0) { 16860 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16861 return; 16862 } 16863 synchronized (mPackages) { 16864 if (mContext.checkCallingOrSelfPermission( 16865 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16866 != PackageManager.PERMISSION_GRANTED) { 16867 if (getUidTargetSdkVersionLockedLPr(callingUid) 16868 < Build.VERSION_CODES.FROYO) { 16869 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16870 + callingUid); 16871 return; 16872 } 16873 mContext.enforceCallingOrSelfPermission( 16874 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16875 } 16876 16877 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16878 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16879 + userId + ":"); 16880 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16881 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16882 scheduleWritePackageRestrictionsLocked(userId); 16883 } 16884 } 16885 16886 @Override 16887 public void replacePreferredActivity(IntentFilter filter, int match, 16888 ComponentName[] set, ComponentName activity, int userId) { 16889 if (filter.countActions() != 1) { 16890 throw new IllegalArgumentException( 16891 "replacePreferredActivity expects filter to have only 1 action."); 16892 } 16893 if (filter.countDataAuthorities() != 0 16894 || filter.countDataPaths() != 0 16895 || filter.countDataSchemes() > 1 16896 || filter.countDataTypes() != 0) { 16897 throw new IllegalArgumentException( 16898 "replacePreferredActivity expects filter to have no data authorities, " + 16899 "paths, or types; and at most one scheme."); 16900 } 16901 16902 final int callingUid = Binder.getCallingUid(); 16903 enforceCrossUserPermission(callingUid, userId, 16904 true /* requireFullPermission */, false /* checkShell */, 16905 "replace preferred activity"); 16906 synchronized (mPackages) { 16907 if (mContext.checkCallingOrSelfPermission( 16908 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16909 != PackageManager.PERMISSION_GRANTED) { 16910 if (getUidTargetSdkVersionLockedLPr(callingUid) 16911 < Build.VERSION_CODES.FROYO) { 16912 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16913 + Binder.getCallingUid()); 16914 return; 16915 } 16916 mContext.enforceCallingOrSelfPermission( 16917 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16918 } 16919 16920 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16921 if (pir != null) { 16922 // Get all of the existing entries that exactly match this filter. 16923 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16924 if (existing != null && existing.size() == 1) { 16925 PreferredActivity cur = existing.get(0); 16926 if (DEBUG_PREFERRED) { 16927 Slog.i(TAG, "Checking replace of preferred:"); 16928 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16929 if (!cur.mPref.mAlways) { 16930 Slog.i(TAG, " -- CUR; not mAlways!"); 16931 } else { 16932 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16933 Slog.i(TAG, " -- CUR: mSet=" 16934 + Arrays.toString(cur.mPref.mSetComponents)); 16935 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16936 Slog.i(TAG, " -- NEW: mMatch=" 16937 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16938 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16939 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16940 } 16941 } 16942 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16943 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16944 && cur.mPref.sameSet(set)) { 16945 // Setting the preferred activity to what it happens to be already 16946 if (DEBUG_PREFERRED) { 16947 Slog.i(TAG, "Replacing with same preferred activity " 16948 + cur.mPref.mShortComponent + " for user " 16949 + userId + ":"); 16950 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16951 } 16952 return; 16953 } 16954 } 16955 16956 if (existing != null) { 16957 if (DEBUG_PREFERRED) { 16958 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16959 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16960 } 16961 for (int i = 0; i < existing.size(); i++) { 16962 PreferredActivity pa = existing.get(i); 16963 if (DEBUG_PREFERRED) { 16964 Slog.i(TAG, "Removing existing preferred activity " 16965 + pa.mPref.mComponent + ":"); 16966 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16967 } 16968 pir.removeFilter(pa); 16969 } 16970 } 16971 } 16972 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16973 "Replacing preferred"); 16974 } 16975 } 16976 16977 @Override 16978 public void clearPackagePreferredActivities(String packageName) { 16979 final int uid = Binder.getCallingUid(); 16980 // writer 16981 synchronized (mPackages) { 16982 PackageParser.Package pkg = mPackages.get(packageName); 16983 if (pkg == null || pkg.applicationInfo.uid != uid) { 16984 if (mContext.checkCallingOrSelfPermission( 16985 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16986 != PackageManager.PERMISSION_GRANTED) { 16987 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16988 < Build.VERSION_CODES.FROYO) { 16989 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16990 + Binder.getCallingUid()); 16991 return; 16992 } 16993 mContext.enforceCallingOrSelfPermission( 16994 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16995 } 16996 } 16997 16998 int user = UserHandle.getCallingUserId(); 16999 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17000 scheduleWritePackageRestrictionsLocked(user); 17001 } 17002 } 17003 } 17004 17005 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17006 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17007 ArrayList<PreferredActivity> removed = null; 17008 boolean changed = false; 17009 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17010 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17011 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17012 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17013 continue; 17014 } 17015 Iterator<PreferredActivity> it = pir.filterIterator(); 17016 while (it.hasNext()) { 17017 PreferredActivity pa = it.next(); 17018 // Mark entry for removal only if it matches the package name 17019 // and the entry is of type "always". 17020 if (packageName == null || 17021 (pa.mPref.mComponent.getPackageName().equals(packageName) 17022 && pa.mPref.mAlways)) { 17023 if (removed == null) { 17024 removed = new ArrayList<PreferredActivity>(); 17025 } 17026 removed.add(pa); 17027 } 17028 } 17029 if (removed != null) { 17030 for (int j=0; j<removed.size(); j++) { 17031 PreferredActivity pa = removed.get(j); 17032 pir.removeFilter(pa); 17033 } 17034 changed = true; 17035 } 17036 } 17037 return changed; 17038 } 17039 17040 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17041 private void clearIntentFilterVerificationsLPw(int userId) { 17042 final int packageCount = mPackages.size(); 17043 for (int i = 0; i < packageCount; i++) { 17044 PackageParser.Package pkg = mPackages.valueAt(i); 17045 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17046 } 17047 } 17048 17049 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17050 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17051 if (userId == UserHandle.USER_ALL) { 17052 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17053 sUserManager.getUserIds())) { 17054 for (int oneUserId : sUserManager.getUserIds()) { 17055 scheduleWritePackageRestrictionsLocked(oneUserId); 17056 } 17057 } 17058 } else { 17059 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17060 scheduleWritePackageRestrictionsLocked(userId); 17061 } 17062 } 17063 } 17064 17065 void clearDefaultBrowserIfNeeded(String packageName) { 17066 for (int oneUserId : sUserManager.getUserIds()) { 17067 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17068 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17069 if (packageName.equals(defaultBrowserPackageName)) { 17070 setDefaultBrowserPackageName(null, oneUserId); 17071 } 17072 } 17073 } 17074 17075 @Override 17076 public void resetApplicationPreferences(int userId) { 17077 mContext.enforceCallingOrSelfPermission( 17078 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17079 final long identity = Binder.clearCallingIdentity(); 17080 // writer 17081 try { 17082 synchronized (mPackages) { 17083 clearPackagePreferredActivitiesLPw(null, userId); 17084 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17085 // TODO: We have to reset the default SMS and Phone. This requires 17086 // significant refactoring to keep all default apps in the package 17087 // manager (cleaner but more work) or have the services provide 17088 // callbacks to the package manager to request a default app reset. 17089 applyFactoryDefaultBrowserLPw(userId); 17090 clearIntentFilterVerificationsLPw(userId); 17091 primeDomainVerificationsLPw(userId); 17092 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17093 scheduleWritePackageRestrictionsLocked(userId); 17094 } 17095 resetNetworkPolicies(userId); 17096 } finally { 17097 Binder.restoreCallingIdentity(identity); 17098 } 17099 } 17100 17101 @Override 17102 public int getPreferredActivities(List<IntentFilter> outFilters, 17103 List<ComponentName> outActivities, String packageName) { 17104 17105 int num = 0; 17106 final int userId = UserHandle.getCallingUserId(); 17107 // reader 17108 synchronized (mPackages) { 17109 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17110 if (pir != null) { 17111 final Iterator<PreferredActivity> it = pir.filterIterator(); 17112 while (it.hasNext()) { 17113 final PreferredActivity pa = it.next(); 17114 if (packageName == null 17115 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17116 && pa.mPref.mAlways)) { 17117 if (outFilters != null) { 17118 outFilters.add(new IntentFilter(pa)); 17119 } 17120 if (outActivities != null) { 17121 outActivities.add(pa.mPref.mComponent); 17122 } 17123 } 17124 } 17125 } 17126 } 17127 17128 return num; 17129 } 17130 17131 @Override 17132 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17133 int userId) { 17134 int callingUid = Binder.getCallingUid(); 17135 if (callingUid != Process.SYSTEM_UID) { 17136 throw new SecurityException( 17137 "addPersistentPreferredActivity can only be run by the system"); 17138 } 17139 if (filter.countActions() == 0) { 17140 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17141 return; 17142 } 17143 synchronized (mPackages) { 17144 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17145 ":"); 17146 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17147 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17148 new PersistentPreferredActivity(filter, activity)); 17149 scheduleWritePackageRestrictionsLocked(userId); 17150 } 17151 } 17152 17153 @Override 17154 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17155 int callingUid = Binder.getCallingUid(); 17156 if (callingUid != Process.SYSTEM_UID) { 17157 throw new SecurityException( 17158 "clearPackagePersistentPreferredActivities can only be run by the system"); 17159 } 17160 ArrayList<PersistentPreferredActivity> removed = null; 17161 boolean changed = false; 17162 synchronized (mPackages) { 17163 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17164 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17165 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17166 .valueAt(i); 17167 if (userId != thisUserId) { 17168 continue; 17169 } 17170 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17171 while (it.hasNext()) { 17172 PersistentPreferredActivity ppa = it.next(); 17173 // Mark entry for removal only if it matches the package name. 17174 if (ppa.mComponent.getPackageName().equals(packageName)) { 17175 if (removed == null) { 17176 removed = new ArrayList<PersistentPreferredActivity>(); 17177 } 17178 removed.add(ppa); 17179 } 17180 } 17181 if (removed != null) { 17182 for (int j=0; j<removed.size(); j++) { 17183 PersistentPreferredActivity ppa = removed.get(j); 17184 ppir.removeFilter(ppa); 17185 } 17186 changed = true; 17187 } 17188 } 17189 17190 if (changed) { 17191 scheduleWritePackageRestrictionsLocked(userId); 17192 } 17193 } 17194 } 17195 17196 /** 17197 * Common machinery for picking apart a restored XML blob and passing 17198 * it to a caller-supplied functor to be applied to the running system. 17199 */ 17200 private void restoreFromXml(XmlPullParser parser, int userId, 17201 String expectedStartTag, BlobXmlRestorer functor) 17202 throws IOException, XmlPullParserException { 17203 int type; 17204 while ((type = parser.next()) != XmlPullParser.START_TAG 17205 && type != XmlPullParser.END_DOCUMENT) { 17206 } 17207 if (type != XmlPullParser.START_TAG) { 17208 // oops didn't find a start tag?! 17209 if (DEBUG_BACKUP) { 17210 Slog.e(TAG, "Didn't find start tag during restore"); 17211 } 17212 return; 17213 } 17214Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17215 // this is supposed to be TAG_PREFERRED_BACKUP 17216 if (!expectedStartTag.equals(parser.getName())) { 17217 if (DEBUG_BACKUP) { 17218 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17219 } 17220 return; 17221 } 17222 17223 // skip interfering stuff, then we're aligned with the backing implementation 17224 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17225Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17226 functor.apply(parser, userId); 17227 } 17228 17229 private interface BlobXmlRestorer { 17230 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17231 } 17232 17233 /** 17234 * Non-Binder method, support for the backup/restore mechanism: write the 17235 * full set of preferred activities in its canonical XML format. Returns the 17236 * XML output as a byte array, or null if there is none. 17237 */ 17238 @Override 17239 public byte[] getPreferredActivityBackup(int userId) { 17240 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17241 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17242 } 17243 17244 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17245 try { 17246 final XmlSerializer serializer = new FastXmlSerializer(); 17247 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17248 serializer.startDocument(null, true); 17249 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17250 17251 synchronized (mPackages) { 17252 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17253 } 17254 17255 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17256 serializer.endDocument(); 17257 serializer.flush(); 17258 } catch (Exception e) { 17259 if (DEBUG_BACKUP) { 17260 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17261 } 17262 return null; 17263 } 17264 17265 return dataStream.toByteArray(); 17266 } 17267 17268 @Override 17269 public void restorePreferredActivities(byte[] backup, int userId) { 17270 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17271 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17272 } 17273 17274 try { 17275 final XmlPullParser parser = Xml.newPullParser(); 17276 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17277 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17278 new BlobXmlRestorer() { 17279 @Override 17280 public void apply(XmlPullParser parser, int userId) 17281 throws XmlPullParserException, IOException { 17282 synchronized (mPackages) { 17283 mSettings.readPreferredActivitiesLPw(parser, userId); 17284 } 17285 } 17286 } ); 17287 } catch (Exception e) { 17288 if (DEBUG_BACKUP) { 17289 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17290 } 17291 } 17292 } 17293 17294 /** 17295 * Non-Binder method, support for the backup/restore mechanism: write the 17296 * default browser (etc) settings in its canonical XML format. Returns the default 17297 * browser XML representation as a byte array, or null if there is none. 17298 */ 17299 @Override 17300 public byte[] getDefaultAppsBackup(int userId) { 17301 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17302 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17303 } 17304 17305 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17306 try { 17307 final XmlSerializer serializer = new FastXmlSerializer(); 17308 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17309 serializer.startDocument(null, true); 17310 serializer.startTag(null, TAG_DEFAULT_APPS); 17311 17312 synchronized (mPackages) { 17313 mSettings.writeDefaultAppsLPr(serializer, userId); 17314 } 17315 17316 serializer.endTag(null, TAG_DEFAULT_APPS); 17317 serializer.endDocument(); 17318 serializer.flush(); 17319 } catch (Exception e) { 17320 if (DEBUG_BACKUP) { 17321 Slog.e(TAG, "Unable to write default apps for backup", e); 17322 } 17323 return null; 17324 } 17325 17326 return dataStream.toByteArray(); 17327 } 17328 17329 @Override 17330 public void restoreDefaultApps(byte[] backup, int userId) { 17331 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17332 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17333 } 17334 17335 try { 17336 final XmlPullParser parser = Xml.newPullParser(); 17337 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17338 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17339 new BlobXmlRestorer() { 17340 @Override 17341 public void apply(XmlPullParser parser, int userId) 17342 throws XmlPullParserException, IOException { 17343 synchronized (mPackages) { 17344 mSettings.readDefaultAppsLPw(parser, userId); 17345 } 17346 } 17347 } ); 17348 } catch (Exception e) { 17349 if (DEBUG_BACKUP) { 17350 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17351 } 17352 } 17353 } 17354 17355 @Override 17356 public byte[] getIntentFilterVerificationBackup(int userId) { 17357 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17358 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17359 } 17360 17361 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17362 try { 17363 final XmlSerializer serializer = new FastXmlSerializer(); 17364 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17365 serializer.startDocument(null, true); 17366 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17367 17368 synchronized (mPackages) { 17369 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17370 } 17371 17372 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17373 serializer.endDocument(); 17374 serializer.flush(); 17375 } catch (Exception e) { 17376 if (DEBUG_BACKUP) { 17377 Slog.e(TAG, "Unable to write default apps for backup", e); 17378 } 17379 return null; 17380 } 17381 17382 return dataStream.toByteArray(); 17383 } 17384 17385 @Override 17386 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17387 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17388 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17389 } 17390 17391 try { 17392 final XmlPullParser parser = Xml.newPullParser(); 17393 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17394 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17395 new BlobXmlRestorer() { 17396 @Override 17397 public void apply(XmlPullParser parser, int userId) 17398 throws XmlPullParserException, IOException { 17399 synchronized (mPackages) { 17400 mSettings.readAllDomainVerificationsLPr(parser, userId); 17401 mSettings.writeLPr(); 17402 } 17403 } 17404 } ); 17405 } catch (Exception e) { 17406 if (DEBUG_BACKUP) { 17407 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17408 } 17409 } 17410 } 17411 17412 @Override 17413 public byte[] getPermissionGrantBackup(int userId) { 17414 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17415 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17416 } 17417 17418 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17419 try { 17420 final XmlSerializer serializer = new FastXmlSerializer(); 17421 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17422 serializer.startDocument(null, true); 17423 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17424 17425 synchronized (mPackages) { 17426 serializeRuntimePermissionGrantsLPr(serializer, userId); 17427 } 17428 17429 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17430 serializer.endDocument(); 17431 serializer.flush(); 17432 } catch (Exception e) { 17433 if (DEBUG_BACKUP) { 17434 Slog.e(TAG, "Unable to write default apps for backup", e); 17435 } 17436 return null; 17437 } 17438 17439 return dataStream.toByteArray(); 17440 } 17441 17442 @Override 17443 public void restorePermissionGrants(byte[] backup, int userId) { 17444 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17445 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17446 } 17447 17448 try { 17449 final XmlPullParser parser = Xml.newPullParser(); 17450 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17451 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17452 new BlobXmlRestorer() { 17453 @Override 17454 public void apply(XmlPullParser parser, int userId) 17455 throws XmlPullParserException, IOException { 17456 synchronized (mPackages) { 17457 processRestoredPermissionGrantsLPr(parser, userId); 17458 } 17459 } 17460 } ); 17461 } catch (Exception e) { 17462 if (DEBUG_BACKUP) { 17463 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17464 } 17465 } 17466 } 17467 17468 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17469 throws IOException { 17470 serializer.startTag(null, TAG_ALL_GRANTS); 17471 17472 final int N = mSettings.mPackages.size(); 17473 for (int i = 0; i < N; i++) { 17474 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17475 boolean pkgGrantsKnown = false; 17476 17477 PermissionsState packagePerms = ps.getPermissionsState(); 17478 17479 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17480 final int grantFlags = state.getFlags(); 17481 // only look at grants that are not system/policy fixed 17482 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17483 final boolean isGranted = state.isGranted(); 17484 // And only back up the user-twiddled state bits 17485 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17486 final String packageName = mSettings.mPackages.keyAt(i); 17487 if (!pkgGrantsKnown) { 17488 serializer.startTag(null, TAG_GRANT); 17489 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17490 pkgGrantsKnown = true; 17491 } 17492 17493 final boolean userSet = 17494 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17495 final boolean userFixed = 17496 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17497 final boolean revoke = 17498 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17499 17500 serializer.startTag(null, TAG_PERMISSION); 17501 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17502 if (isGranted) { 17503 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17504 } 17505 if (userSet) { 17506 serializer.attribute(null, ATTR_USER_SET, "true"); 17507 } 17508 if (userFixed) { 17509 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17510 } 17511 if (revoke) { 17512 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17513 } 17514 serializer.endTag(null, TAG_PERMISSION); 17515 } 17516 } 17517 } 17518 17519 if (pkgGrantsKnown) { 17520 serializer.endTag(null, TAG_GRANT); 17521 } 17522 } 17523 17524 serializer.endTag(null, TAG_ALL_GRANTS); 17525 } 17526 17527 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17528 throws XmlPullParserException, IOException { 17529 String pkgName = null; 17530 int outerDepth = parser.getDepth(); 17531 int type; 17532 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17533 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17534 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17535 continue; 17536 } 17537 17538 final String tagName = parser.getName(); 17539 if (tagName.equals(TAG_GRANT)) { 17540 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17541 if (DEBUG_BACKUP) { 17542 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17543 } 17544 } else if (tagName.equals(TAG_PERMISSION)) { 17545 17546 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17547 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17548 17549 int newFlagSet = 0; 17550 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17551 newFlagSet |= FLAG_PERMISSION_USER_SET; 17552 } 17553 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17554 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17555 } 17556 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17557 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17558 } 17559 if (DEBUG_BACKUP) { 17560 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17561 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17562 } 17563 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17564 if (ps != null) { 17565 // Already installed so we apply the grant immediately 17566 if (DEBUG_BACKUP) { 17567 Slog.v(TAG, " + already installed; applying"); 17568 } 17569 PermissionsState perms = ps.getPermissionsState(); 17570 BasePermission bp = mSettings.mPermissions.get(permName); 17571 if (bp != null) { 17572 if (isGranted) { 17573 perms.grantRuntimePermission(bp, userId); 17574 } 17575 if (newFlagSet != 0) { 17576 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17577 } 17578 } 17579 } else { 17580 // Need to wait for post-restore install to apply the grant 17581 if (DEBUG_BACKUP) { 17582 Slog.v(TAG, " - not yet installed; saving for later"); 17583 } 17584 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17585 isGranted, newFlagSet, userId); 17586 } 17587 } else { 17588 PackageManagerService.reportSettingsProblem(Log.WARN, 17589 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17590 XmlUtils.skipCurrentTag(parser); 17591 } 17592 } 17593 17594 scheduleWriteSettingsLocked(); 17595 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17596 } 17597 17598 @Override 17599 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17600 int sourceUserId, int targetUserId, int flags) { 17601 mContext.enforceCallingOrSelfPermission( 17602 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17603 int callingUid = Binder.getCallingUid(); 17604 enforceOwnerRights(ownerPackage, callingUid); 17605 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17606 if (intentFilter.countActions() == 0) { 17607 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17608 return; 17609 } 17610 synchronized (mPackages) { 17611 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17612 ownerPackage, targetUserId, flags); 17613 CrossProfileIntentResolver resolver = 17614 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17615 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17616 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17617 if (existing != null) { 17618 int size = existing.size(); 17619 for (int i = 0; i < size; i++) { 17620 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17621 return; 17622 } 17623 } 17624 } 17625 resolver.addFilter(newFilter); 17626 scheduleWritePackageRestrictionsLocked(sourceUserId); 17627 } 17628 } 17629 17630 @Override 17631 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17632 mContext.enforceCallingOrSelfPermission( 17633 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17634 int callingUid = Binder.getCallingUid(); 17635 enforceOwnerRights(ownerPackage, callingUid); 17636 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17637 synchronized (mPackages) { 17638 CrossProfileIntentResolver resolver = 17639 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17640 ArraySet<CrossProfileIntentFilter> set = 17641 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17642 for (CrossProfileIntentFilter filter : set) { 17643 if (filter.getOwnerPackage().equals(ownerPackage)) { 17644 resolver.removeFilter(filter); 17645 } 17646 } 17647 scheduleWritePackageRestrictionsLocked(sourceUserId); 17648 } 17649 } 17650 17651 // Enforcing that callingUid is owning pkg on userId 17652 private void enforceOwnerRights(String pkg, int callingUid) { 17653 // The system owns everything. 17654 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17655 return; 17656 } 17657 int callingUserId = UserHandle.getUserId(callingUid); 17658 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17659 if (pi == null) { 17660 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17661 + callingUserId); 17662 } 17663 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17664 throw new SecurityException("Calling uid " + callingUid 17665 + " does not own package " + pkg); 17666 } 17667 } 17668 17669 @Override 17670 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17671 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17672 } 17673 17674 private Intent getHomeIntent() { 17675 Intent intent = new Intent(Intent.ACTION_MAIN); 17676 intent.addCategory(Intent.CATEGORY_HOME); 17677 intent.addCategory(Intent.CATEGORY_DEFAULT); 17678 return intent; 17679 } 17680 17681 private IntentFilter getHomeFilter() { 17682 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17683 filter.addCategory(Intent.CATEGORY_HOME); 17684 filter.addCategory(Intent.CATEGORY_DEFAULT); 17685 return filter; 17686 } 17687 17688 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17689 int userId) { 17690 Intent intent = getHomeIntent(); 17691 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17692 PackageManager.GET_META_DATA, userId); 17693 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17694 true, false, false, userId); 17695 17696 allHomeCandidates.clear(); 17697 if (list != null) { 17698 for (ResolveInfo ri : list) { 17699 allHomeCandidates.add(ri); 17700 } 17701 } 17702 return (preferred == null || preferred.activityInfo == null) 17703 ? null 17704 : new ComponentName(preferred.activityInfo.packageName, 17705 preferred.activityInfo.name); 17706 } 17707 17708 @Override 17709 public void setHomeActivity(ComponentName comp, int userId) { 17710 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17711 getHomeActivitiesAsUser(homeActivities, userId); 17712 17713 boolean found = false; 17714 17715 final int size = homeActivities.size(); 17716 final ComponentName[] set = new ComponentName[size]; 17717 for (int i = 0; i < size; i++) { 17718 final ResolveInfo candidate = homeActivities.get(i); 17719 final ActivityInfo info = candidate.activityInfo; 17720 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17721 set[i] = activityName; 17722 if (!found && activityName.equals(comp)) { 17723 found = true; 17724 } 17725 } 17726 if (!found) { 17727 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17728 + userId); 17729 } 17730 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17731 set, comp, userId); 17732 } 17733 17734 private @Nullable String getSetupWizardPackageName() { 17735 final Intent intent = new Intent(Intent.ACTION_MAIN); 17736 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17737 17738 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17739 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17740 | MATCH_DISABLED_COMPONENTS, 17741 UserHandle.myUserId()); 17742 if (matches.size() == 1) { 17743 return matches.get(0).getComponentInfo().packageName; 17744 } else { 17745 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17746 + ": matches=" + matches); 17747 return null; 17748 } 17749 } 17750 17751 @Override 17752 public void setApplicationEnabledSetting(String appPackageName, 17753 int newState, int flags, int userId, String callingPackage) { 17754 if (!sUserManager.exists(userId)) return; 17755 if (callingPackage == null) { 17756 callingPackage = Integer.toString(Binder.getCallingUid()); 17757 } 17758 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17759 } 17760 17761 @Override 17762 public void setComponentEnabledSetting(ComponentName componentName, 17763 int newState, int flags, int userId) { 17764 if (!sUserManager.exists(userId)) return; 17765 setEnabledSetting(componentName.getPackageName(), 17766 componentName.getClassName(), newState, flags, userId, null); 17767 } 17768 17769 private void setEnabledSetting(final String packageName, String className, int newState, 17770 final int flags, int userId, String callingPackage) { 17771 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17772 || newState == COMPONENT_ENABLED_STATE_ENABLED 17773 || newState == COMPONENT_ENABLED_STATE_DISABLED 17774 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17775 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17776 throw new IllegalArgumentException("Invalid new component state: " 17777 + newState); 17778 } 17779 PackageSetting pkgSetting; 17780 final int uid = Binder.getCallingUid(); 17781 final int permission; 17782 if (uid == Process.SYSTEM_UID) { 17783 permission = PackageManager.PERMISSION_GRANTED; 17784 } else { 17785 permission = mContext.checkCallingOrSelfPermission( 17786 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17787 } 17788 enforceCrossUserPermission(uid, userId, 17789 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17790 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17791 boolean sendNow = false; 17792 boolean isApp = (className == null); 17793 String componentName = isApp ? packageName : className; 17794 int packageUid = -1; 17795 ArrayList<String> components; 17796 17797 // writer 17798 synchronized (mPackages) { 17799 pkgSetting = mSettings.mPackages.get(packageName); 17800 if (pkgSetting == null) { 17801 if (className == null) { 17802 throw new IllegalArgumentException("Unknown package: " + packageName); 17803 } 17804 throw new IllegalArgumentException( 17805 "Unknown component: " + packageName + "/" + className); 17806 } 17807 } 17808 17809 // Limit who can change which apps 17810 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17811 // Don't allow apps that don't have permission to modify other apps 17812 if (!allowedByPermission) { 17813 throw new SecurityException( 17814 "Permission Denial: attempt to change component state from pid=" 17815 + Binder.getCallingPid() 17816 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17817 } 17818 // Don't allow changing protected packages. 17819 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17820 throw new SecurityException("Cannot disable a protected package: " + packageName); 17821 } 17822 } 17823 17824 synchronized (mPackages) { 17825 if (uid == Process.SHELL_UID) { 17826 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17827 int oldState = pkgSetting.getEnabled(userId); 17828 if (className == null 17829 && 17830 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17831 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17832 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17833 && 17834 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17835 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17836 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17837 // ok 17838 } else { 17839 throw new SecurityException( 17840 "Shell cannot change component state for " + packageName + "/" 17841 + className + " to " + newState); 17842 } 17843 } 17844 if (className == null) { 17845 // We're dealing with an application/package level state change 17846 if (pkgSetting.getEnabled(userId) == newState) { 17847 // Nothing to do 17848 return; 17849 } 17850 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17851 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17852 // Don't care about who enables an app. 17853 callingPackage = null; 17854 } 17855 pkgSetting.setEnabled(newState, userId, callingPackage); 17856 // pkgSetting.pkg.mSetEnabled = newState; 17857 } else { 17858 // We're dealing with a component level state change 17859 // First, verify that this is a valid class name. 17860 PackageParser.Package pkg = pkgSetting.pkg; 17861 if (pkg == null || !pkg.hasComponentClassName(className)) { 17862 if (pkg != null && 17863 pkg.applicationInfo.targetSdkVersion >= 17864 Build.VERSION_CODES.JELLY_BEAN) { 17865 throw new IllegalArgumentException("Component class " + className 17866 + " does not exist in " + packageName); 17867 } else { 17868 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17869 + className + " does not exist in " + packageName); 17870 } 17871 } 17872 switch (newState) { 17873 case COMPONENT_ENABLED_STATE_ENABLED: 17874 if (!pkgSetting.enableComponentLPw(className, userId)) { 17875 return; 17876 } 17877 break; 17878 case COMPONENT_ENABLED_STATE_DISABLED: 17879 if (!pkgSetting.disableComponentLPw(className, userId)) { 17880 return; 17881 } 17882 break; 17883 case COMPONENT_ENABLED_STATE_DEFAULT: 17884 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17885 return; 17886 } 17887 break; 17888 default: 17889 Slog.e(TAG, "Invalid new component state: " + newState); 17890 return; 17891 } 17892 } 17893 scheduleWritePackageRestrictionsLocked(userId); 17894 components = mPendingBroadcasts.get(userId, packageName); 17895 final boolean newPackage = components == null; 17896 if (newPackage) { 17897 components = new ArrayList<String>(); 17898 } 17899 if (!components.contains(componentName)) { 17900 components.add(componentName); 17901 } 17902 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17903 sendNow = true; 17904 // Purge entry from pending broadcast list if another one exists already 17905 // since we are sending one right away. 17906 mPendingBroadcasts.remove(userId, packageName); 17907 } else { 17908 if (newPackage) { 17909 mPendingBroadcasts.put(userId, packageName, components); 17910 } 17911 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17912 // Schedule a message 17913 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17914 } 17915 } 17916 } 17917 17918 long callingId = Binder.clearCallingIdentity(); 17919 try { 17920 if (sendNow) { 17921 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17922 sendPackageChangedBroadcast(packageName, 17923 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17924 } 17925 } finally { 17926 Binder.restoreCallingIdentity(callingId); 17927 } 17928 } 17929 17930 @Override 17931 public void flushPackageRestrictionsAsUser(int userId) { 17932 if (!sUserManager.exists(userId)) { 17933 return; 17934 } 17935 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17936 false /* checkShell */, "flushPackageRestrictions"); 17937 synchronized (mPackages) { 17938 mSettings.writePackageRestrictionsLPr(userId); 17939 mDirtyUsers.remove(userId); 17940 if (mDirtyUsers.isEmpty()) { 17941 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17942 } 17943 } 17944 } 17945 17946 private void sendPackageChangedBroadcast(String packageName, 17947 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17948 if (DEBUG_INSTALL) 17949 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17950 + componentNames); 17951 Bundle extras = new Bundle(4); 17952 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17953 String nameList[] = new String[componentNames.size()]; 17954 componentNames.toArray(nameList); 17955 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17956 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17957 extras.putInt(Intent.EXTRA_UID, packageUid); 17958 // If this is not reporting a change of the overall package, then only send it 17959 // to registered receivers. We don't want to launch a swath of apps for every 17960 // little component state change. 17961 final int flags = !componentNames.contains(packageName) 17962 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17963 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17964 new int[] {UserHandle.getUserId(packageUid)}); 17965 } 17966 17967 @Override 17968 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17969 if (!sUserManager.exists(userId)) return; 17970 final int uid = Binder.getCallingUid(); 17971 final int permission = mContext.checkCallingOrSelfPermission( 17972 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17973 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17974 enforceCrossUserPermission(uid, userId, 17975 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17976 // writer 17977 synchronized (mPackages) { 17978 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17979 allowedByPermission, uid, userId)) { 17980 scheduleWritePackageRestrictionsLocked(userId); 17981 } 17982 } 17983 } 17984 17985 @Override 17986 public String getInstallerPackageName(String packageName) { 17987 // reader 17988 synchronized (mPackages) { 17989 return mSettings.getInstallerPackageNameLPr(packageName); 17990 } 17991 } 17992 17993 public boolean isOrphaned(String packageName) { 17994 // reader 17995 synchronized (mPackages) { 17996 return mSettings.isOrphaned(packageName); 17997 } 17998 } 17999 18000 @Override 18001 public int getApplicationEnabledSetting(String packageName, int userId) { 18002 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18003 int uid = Binder.getCallingUid(); 18004 enforceCrossUserPermission(uid, userId, 18005 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18006 // reader 18007 synchronized (mPackages) { 18008 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18009 } 18010 } 18011 18012 @Override 18013 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18014 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18015 int uid = Binder.getCallingUid(); 18016 enforceCrossUserPermission(uid, userId, 18017 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18018 // reader 18019 synchronized (mPackages) { 18020 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18021 } 18022 } 18023 18024 @Override 18025 public void enterSafeMode() { 18026 enforceSystemOrRoot("Only the system can request entering safe mode"); 18027 18028 if (!mSystemReady) { 18029 mSafeMode = true; 18030 } 18031 } 18032 18033 @Override 18034 public void systemReady() { 18035 mSystemReady = true; 18036 18037 // Read the compatibilty setting when the system is ready. 18038 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18039 mContext.getContentResolver(), 18040 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18041 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18042 if (DEBUG_SETTINGS) { 18043 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18044 } 18045 18046 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18047 18048 synchronized (mPackages) { 18049 // Verify that all of the preferred activity components actually 18050 // exist. It is possible for applications to be updated and at 18051 // that point remove a previously declared activity component that 18052 // had been set as a preferred activity. We try to clean this up 18053 // the next time we encounter that preferred activity, but it is 18054 // possible for the user flow to never be able to return to that 18055 // situation so here we do a sanity check to make sure we haven't 18056 // left any junk around. 18057 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18058 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18059 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18060 removed.clear(); 18061 for (PreferredActivity pa : pir.filterSet()) { 18062 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18063 removed.add(pa); 18064 } 18065 } 18066 if (removed.size() > 0) { 18067 for (int r=0; r<removed.size(); r++) { 18068 PreferredActivity pa = removed.get(r); 18069 Slog.w(TAG, "Removing dangling preferred activity: " 18070 + pa.mPref.mComponent); 18071 pir.removeFilter(pa); 18072 } 18073 mSettings.writePackageRestrictionsLPr( 18074 mSettings.mPreferredActivities.keyAt(i)); 18075 } 18076 } 18077 18078 for (int userId : UserManagerService.getInstance().getUserIds()) { 18079 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18080 grantPermissionsUserIds = ArrayUtils.appendInt( 18081 grantPermissionsUserIds, userId); 18082 } 18083 } 18084 } 18085 sUserManager.systemReady(); 18086 18087 // If we upgraded grant all default permissions before kicking off. 18088 for (int userId : grantPermissionsUserIds) { 18089 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18090 } 18091 18092 // Kick off any messages waiting for system ready 18093 if (mPostSystemReadyMessages != null) { 18094 for (Message msg : mPostSystemReadyMessages) { 18095 msg.sendToTarget(); 18096 } 18097 mPostSystemReadyMessages = null; 18098 } 18099 18100 // Watch for external volumes that come and go over time 18101 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18102 storage.registerListener(mStorageListener); 18103 18104 mInstallerService.systemReady(); 18105 mPackageDexOptimizer.systemReady(); 18106 18107 MountServiceInternal mountServiceInternal = LocalServices.getService( 18108 MountServiceInternal.class); 18109 mountServiceInternal.addExternalStoragePolicy( 18110 new MountServiceInternal.ExternalStorageMountPolicy() { 18111 @Override 18112 public int getMountMode(int uid, String packageName) { 18113 if (Process.isIsolated(uid)) { 18114 return Zygote.MOUNT_EXTERNAL_NONE; 18115 } 18116 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18117 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18118 } 18119 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18120 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18121 } 18122 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18123 return Zygote.MOUNT_EXTERNAL_READ; 18124 } 18125 return Zygote.MOUNT_EXTERNAL_WRITE; 18126 } 18127 18128 @Override 18129 public boolean hasExternalStorage(int uid, String packageName) { 18130 return true; 18131 } 18132 }); 18133 18134 // Now that we're mostly running, clean up stale users and apps 18135 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18136 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18137 } 18138 18139 @Override 18140 public boolean isSafeMode() { 18141 return mSafeMode; 18142 } 18143 18144 @Override 18145 public boolean hasSystemUidErrors() { 18146 return mHasSystemUidErrors; 18147 } 18148 18149 static String arrayToString(int[] array) { 18150 StringBuffer buf = new StringBuffer(128); 18151 buf.append('['); 18152 if (array != null) { 18153 for (int i=0; i<array.length; i++) { 18154 if (i > 0) buf.append(", "); 18155 buf.append(array[i]); 18156 } 18157 } 18158 buf.append(']'); 18159 return buf.toString(); 18160 } 18161 18162 static class DumpState { 18163 public static final int DUMP_LIBS = 1 << 0; 18164 public static final int DUMP_FEATURES = 1 << 1; 18165 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18166 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18167 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18168 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18169 public static final int DUMP_PERMISSIONS = 1 << 6; 18170 public static final int DUMP_PACKAGES = 1 << 7; 18171 public static final int DUMP_SHARED_USERS = 1 << 8; 18172 public static final int DUMP_MESSAGES = 1 << 9; 18173 public static final int DUMP_PROVIDERS = 1 << 10; 18174 public static final int DUMP_VERIFIERS = 1 << 11; 18175 public static final int DUMP_PREFERRED = 1 << 12; 18176 public static final int DUMP_PREFERRED_XML = 1 << 13; 18177 public static final int DUMP_KEYSETS = 1 << 14; 18178 public static final int DUMP_VERSION = 1 << 15; 18179 public static final int DUMP_INSTALLS = 1 << 16; 18180 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18181 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18182 public static final int DUMP_FROZEN = 1 << 19; 18183 public static final int DUMP_DEXOPT = 1 << 20; 18184 18185 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18186 18187 private int mTypes; 18188 18189 private int mOptions; 18190 18191 private boolean mTitlePrinted; 18192 18193 private SharedUserSetting mSharedUser; 18194 18195 public boolean isDumping(int type) { 18196 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18197 return true; 18198 } 18199 18200 return (mTypes & type) != 0; 18201 } 18202 18203 public void setDump(int type) { 18204 mTypes |= type; 18205 } 18206 18207 public boolean isOptionEnabled(int option) { 18208 return (mOptions & option) != 0; 18209 } 18210 18211 public void setOptionEnabled(int option) { 18212 mOptions |= option; 18213 } 18214 18215 public boolean onTitlePrinted() { 18216 final boolean printed = mTitlePrinted; 18217 mTitlePrinted = true; 18218 return printed; 18219 } 18220 18221 public boolean getTitlePrinted() { 18222 return mTitlePrinted; 18223 } 18224 18225 public void setTitlePrinted(boolean enabled) { 18226 mTitlePrinted = enabled; 18227 } 18228 18229 public SharedUserSetting getSharedUser() { 18230 return mSharedUser; 18231 } 18232 18233 public void setSharedUser(SharedUserSetting user) { 18234 mSharedUser = user; 18235 } 18236 } 18237 18238 @Override 18239 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18240 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18241 (new PackageManagerShellCommand(this)).exec( 18242 this, in, out, err, args, resultReceiver); 18243 } 18244 18245 @Override 18246 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18247 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18248 != PackageManager.PERMISSION_GRANTED) { 18249 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18250 + Binder.getCallingPid() 18251 + ", uid=" + Binder.getCallingUid() 18252 + " without permission " 18253 + android.Manifest.permission.DUMP); 18254 return; 18255 } 18256 18257 DumpState dumpState = new DumpState(); 18258 boolean fullPreferred = false; 18259 boolean checkin = false; 18260 18261 String packageName = null; 18262 ArraySet<String> permissionNames = null; 18263 18264 int opti = 0; 18265 while (opti < args.length) { 18266 String opt = args[opti]; 18267 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18268 break; 18269 } 18270 opti++; 18271 18272 if ("-a".equals(opt)) { 18273 // Right now we only know how to print all. 18274 } else if ("-h".equals(opt)) { 18275 pw.println("Package manager dump options:"); 18276 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18277 pw.println(" --checkin: dump for a checkin"); 18278 pw.println(" -f: print details of intent filters"); 18279 pw.println(" -h: print this help"); 18280 pw.println(" cmd may be one of:"); 18281 pw.println(" l[ibraries]: list known shared libraries"); 18282 pw.println(" f[eatures]: list device features"); 18283 pw.println(" k[eysets]: print known keysets"); 18284 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18285 pw.println(" perm[issions]: dump permissions"); 18286 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18287 pw.println(" pref[erred]: print preferred package settings"); 18288 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18289 pw.println(" prov[iders]: dump content providers"); 18290 pw.println(" p[ackages]: dump installed packages"); 18291 pw.println(" s[hared-users]: dump shared user IDs"); 18292 pw.println(" m[essages]: print collected runtime messages"); 18293 pw.println(" v[erifiers]: print package verifier info"); 18294 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18295 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18296 pw.println(" version: print database version info"); 18297 pw.println(" write: write current settings now"); 18298 pw.println(" installs: details about install sessions"); 18299 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18300 pw.println(" dexopt: dump dexopt state"); 18301 pw.println(" <package.name>: info about given package"); 18302 return; 18303 } else if ("--checkin".equals(opt)) { 18304 checkin = true; 18305 } else if ("-f".equals(opt)) { 18306 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18307 } else { 18308 pw.println("Unknown argument: " + opt + "; use -h for help"); 18309 } 18310 } 18311 18312 // Is the caller requesting to dump a particular piece of data? 18313 if (opti < args.length) { 18314 String cmd = args[opti]; 18315 opti++; 18316 // Is this a package name? 18317 if ("android".equals(cmd) || cmd.contains(".")) { 18318 packageName = cmd; 18319 // When dumping a single package, we always dump all of its 18320 // filter information since the amount of data will be reasonable. 18321 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18322 } else if ("check-permission".equals(cmd)) { 18323 if (opti >= args.length) { 18324 pw.println("Error: check-permission missing permission argument"); 18325 return; 18326 } 18327 String perm = args[opti]; 18328 opti++; 18329 if (opti >= args.length) { 18330 pw.println("Error: check-permission missing package argument"); 18331 return; 18332 } 18333 String pkg = args[opti]; 18334 opti++; 18335 int user = UserHandle.getUserId(Binder.getCallingUid()); 18336 if (opti < args.length) { 18337 try { 18338 user = Integer.parseInt(args[opti]); 18339 } catch (NumberFormatException e) { 18340 pw.println("Error: check-permission user argument is not a number: " 18341 + args[opti]); 18342 return; 18343 } 18344 } 18345 pw.println(checkPermission(perm, pkg, user)); 18346 return; 18347 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18348 dumpState.setDump(DumpState.DUMP_LIBS); 18349 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18350 dumpState.setDump(DumpState.DUMP_FEATURES); 18351 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18352 if (opti >= args.length) { 18353 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18354 | DumpState.DUMP_SERVICE_RESOLVERS 18355 | DumpState.DUMP_RECEIVER_RESOLVERS 18356 | DumpState.DUMP_CONTENT_RESOLVERS); 18357 } else { 18358 while (opti < args.length) { 18359 String name = args[opti]; 18360 if ("a".equals(name) || "activity".equals(name)) { 18361 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18362 } else if ("s".equals(name) || "service".equals(name)) { 18363 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18364 } else if ("r".equals(name) || "receiver".equals(name)) { 18365 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18366 } else if ("c".equals(name) || "content".equals(name)) { 18367 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18368 } else { 18369 pw.println("Error: unknown resolver table type: " + name); 18370 return; 18371 } 18372 opti++; 18373 } 18374 } 18375 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18376 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18377 } else if ("permission".equals(cmd)) { 18378 if (opti >= args.length) { 18379 pw.println("Error: permission requires permission name"); 18380 return; 18381 } 18382 permissionNames = new ArraySet<>(); 18383 while (opti < args.length) { 18384 permissionNames.add(args[opti]); 18385 opti++; 18386 } 18387 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18388 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18389 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18390 dumpState.setDump(DumpState.DUMP_PREFERRED); 18391 } else if ("preferred-xml".equals(cmd)) { 18392 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18393 if (opti < args.length && "--full".equals(args[opti])) { 18394 fullPreferred = true; 18395 opti++; 18396 } 18397 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18398 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18399 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18400 dumpState.setDump(DumpState.DUMP_PACKAGES); 18401 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18402 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18403 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18404 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18405 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18406 dumpState.setDump(DumpState.DUMP_MESSAGES); 18407 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18408 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18409 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18410 || "intent-filter-verifiers".equals(cmd)) { 18411 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18412 } else if ("version".equals(cmd)) { 18413 dumpState.setDump(DumpState.DUMP_VERSION); 18414 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18415 dumpState.setDump(DumpState.DUMP_KEYSETS); 18416 } else if ("installs".equals(cmd)) { 18417 dumpState.setDump(DumpState.DUMP_INSTALLS); 18418 } else if ("frozen".equals(cmd)) { 18419 dumpState.setDump(DumpState.DUMP_FROZEN); 18420 } else if ("dexopt".equals(cmd)) { 18421 dumpState.setDump(DumpState.DUMP_DEXOPT); 18422 } else if ("write".equals(cmd)) { 18423 synchronized (mPackages) { 18424 mSettings.writeLPr(); 18425 pw.println("Settings written."); 18426 return; 18427 } 18428 } 18429 } 18430 18431 if (checkin) { 18432 pw.println("vers,1"); 18433 } 18434 18435 // reader 18436 synchronized (mPackages) { 18437 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18438 if (!checkin) { 18439 if (dumpState.onTitlePrinted()) 18440 pw.println(); 18441 pw.println("Database versions:"); 18442 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18443 } 18444 } 18445 18446 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18447 if (!checkin) { 18448 if (dumpState.onTitlePrinted()) 18449 pw.println(); 18450 pw.println("Verifiers:"); 18451 pw.print(" Required: "); 18452 pw.print(mRequiredVerifierPackage); 18453 pw.print(" (uid="); 18454 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18455 UserHandle.USER_SYSTEM)); 18456 pw.println(")"); 18457 } else if (mRequiredVerifierPackage != null) { 18458 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18459 pw.print(","); 18460 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18461 UserHandle.USER_SYSTEM)); 18462 } 18463 } 18464 18465 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18466 packageName == null) { 18467 if (mIntentFilterVerifierComponent != null) { 18468 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18469 if (!checkin) { 18470 if (dumpState.onTitlePrinted()) 18471 pw.println(); 18472 pw.println("Intent Filter Verifier:"); 18473 pw.print(" Using: "); 18474 pw.print(verifierPackageName); 18475 pw.print(" (uid="); 18476 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18477 UserHandle.USER_SYSTEM)); 18478 pw.println(")"); 18479 } else if (verifierPackageName != null) { 18480 pw.print("ifv,"); pw.print(verifierPackageName); 18481 pw.print(","); 18482 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18483 UserHandle.USER_SYSTEM)); 18484 } 18485 } else { 18486 pw.println(); 18487 pw.println("No Intent Filter Verifier available!"); 18488 } 18489 } 18490 18491 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18492 boolean printedHeader = false; 18493 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18494 while (it.hasNext()) { 18495 String name = it.next(); 18496 SharedLibraryEntry ent = mSharedLibraries.get(name); 18497 if (!checkin) { 18498 if (!printedHeader) { 18499 if (dumpState.onTitlePrinted()) 18500 pw.println(); 18501 pw.println("Libraries:"); 18502 printedHeader = true; 18503 } 18504 pw.print(" "); 18505 } else { 18506 pw.print("lib,"); 18507 } 18508 pw.print(name); 18509 if (!checkin) { 18510 pw.print(" -> "); 18511 } 18512 if (ent.path != null) { 18513 if (!checkin) { 18514 pw.print("(jar) "); 18515 pw.print(ent.path); 18516 } else { 18517 pw.print(",jar,"); 18518 pw.print(ent.path); 18519 } 18520 } else { 18521 if (!checkin) { 18522 pw.print("(apk) "); 18523 pw.print(ent.apk); 18524 } else { 18525 pw.print(",apk,"); 18526 pw.print(ent.apk); 18527 } 18528 } 18529 pw.println(); 18530 } 18531 } 18532 18533 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18534 if (dumpState.onTitlePrinted()) 18535 pw.println(); 18536 if (!checkin) { 18537 pw.println("Features:"); 18538 } 18539 18540 for (FeatureInfo feat : mAvailableFeatures.values()) { 18541 if (checkin) { 18542 pw.print("feat,"); 18543 pw.print(feat.name); 18544 pw.print(","); 18545 pw.println(feat.version); 18546 } else { 18547 pw.print(" "); 18548 pw.print(feat.name); 18549 if (feat.version > 0) { 18550 pw.print(" version="); 18551 pw.print(feat.version); 18552 } 18553 pw.println(); 18554 } 18555 } 18556 } 18557 18558 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18559 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18560 : "Activity Resolver Table:", " ", packageName, 18561 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18562 dumpState.setTitlePrinted(true); 18563 } 18564 } 18565 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18566 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18567 : "Receiver Resolver Table:", " ", packageName, 18568 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18569 dumpState.setTitlePrinted(true); 18570 } 18571 } 18572 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18573 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18574 : "Service Resolver Table:", " ", packageName, 18575 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18576 dumpState.setTitlePrinted(true); 18577 } 18578 } 18579 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18580 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18581 : "Provider Resolver Table:", " ", packageName, 18582 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18583 dumpState.setTitlePrinted(true); 18584 } 18585 } 18586 18587 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18588 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18589 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18590 int user = mSettings.mPreferredActivities.keyAt(i); 18591 if (pir.dump(pw, 18592 dumpState.getTitlePrinted() 18593 ? "\nPreferred Activities User " + user + ":" 18594 : "Preferred Activities User " + user + ":", " ", 18595 packageName, true, false)) { 18596 dumpState.setTitlePrinted(true); 18597 } 18598 } 18599 } 18600 18601 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18602 pw.flush(); 18603 FileOutputStream fout = new FileOutputStream(fd); 18604 BufferedOutputStream str = new BufferedOutputStream(fout); 18605 XmlSerializer serializer = new FastXmlSerializer(); 18606 try { 18607 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18608 serializer.startDocument(null, true); 18609 serializer.setFeature( 18610 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18611 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18612 serializer.endDocument(); 18613 serializer.flush(); 18614 } catch (IllegalArgumentException e) { 18615 pw.println("Failed writing: " + e); 18616 } catch (IllegalStateException e) { 18617 pw.println("Failed writing: " + e); 18618 } catch (IOException e) { 18619 pw.println("Failed writing: " + e); 18620 } 18621 } 18622 18623 if (!checkin 18624 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18625 && packageName == null) { 18626 pw.println(); 18627 int count = mSettings.mPackages.size(); 18628 if (count == 0) { 18629 pw.println("No applications!"); 18630 pw.println(); 18631 } else { 18632 final String prefix = " "; 18633 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18634 if (allPackageSettings.size() == 0) { 18635 pw.println("No domain preferred apps!"); 18636 pw.println(); 18637 } else { 18638 pw.println("App verification status:"); 18639 pw.println(); 18640 count = 0; 18641 for (PackageSetting ps : allPackageSettings) { 18642 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18643 if (ivi == null || ivi.getPackageName() == null) continue; 18644 pw.println(prefix + "Package: " + ivi.getPackageName()); 18645 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18646 pw.println(prefix + "Status: " + ivi.getStatusString()); 18647 pw.println(); 18648 count++; 18649 } 18650 if (count == 0) { 18651 pw.println(prefix + "No app verification established."); 18652 pw.println(); 18653 } 18654 for (int userId : sUserManager.getUserIds()) { 18655 pw.println("App linkages for user " + userId + ":"); 18656 pw.println(); 18657 count = 0; 18658 for (PackageSetting ps : allPackageSettings) { 18659 final long status = ps.getDomainVerificationStatusForUser(userId); 18660 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18661 continue; 18662 } 18663 pw.println(prefix + "Package: " + ps.name); 18664 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18665 String statusStr = IntentFilterVerificationInfo. 18666 getStatusStringFromValue(status); 18667 pw.println(prefix + "Status: " + statusStr); 18668 pw.println(); 18669 count++; 18670 } 18671 if (count == 0) { 18672 pw.println(prefix + "No configured app linkages."); 18673 pw.println(); 18674 } 18675 } 18676 } 18677 } 18678 } 18679 18680 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18681 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18682 if (packageName == null && permissionNames == null) { 18683 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18684 if (iperm == 0) { 18685 if (dumpState.onTitlePrinted()) 18686 pw.println(); 18687 pw.println("AppOp Permissions:"); 18688 } 18689 pw.print(" AppOp Permission "); 18690 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18691 pw.println(":"); 18692 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18693 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18694 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18695 } 18696 } 18697 } 18698 } 18699 18700 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18701 boolean printedSomething = false; 18702 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18703 if (packageName != null && !packageName.equals(p.info.packageName)) { 18704 continue; 18705 } 18706 if (!printedSomething) { 18707 if (dumpState.onTitlePrinted()) 18708 pw.println(); 18709 pw.println("Registered ContentProviders:"); 18710 printedSomething = true; 18711 } 18712 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18713 pw.print(" "); pw.println(p.toString()); 18714 } 18715 printedSomething = false; 18716 for (Map.Entry<String, PackageParser.Provider> entry : 18717 mProvidersByAuthority.entrySet()) { 18718 PackageParser.Provider p = entry.getValue(); 18719 if (packageName != null && !packageName.equals(p.info.packageName)) { 18720 continue; 18721 } 18722 if (!printedSomething) { 18723 if (dumpState.onTitlePrinted()) 18724 pw.println(); 18725 pw.println("ContentProvider Authorities:"); 18726 printedSomething = true; 18727 } 18728 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18729 pw.print(" "); pw.println(p.toString()); 18730 if (p.info != null && p.info.applicationInfo != null) { 18731 final String appInfo = p.info.applicationInfo.toString(); 18732 pw.print(" applicationInfo="); pw.println(appInfo); 18733 } 18734 } 18735 } 18736 18737 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18738 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18739 } 18740 18741 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18742 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18743 } 18744 18745 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18746 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18747 } 18748 18749 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18750 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18751 } 18752 18753 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18754 // XXX should handle packageName != null by dumping only install data that 18755 // the given package is involved with. 18756 if (dumpState.onTitlePrinted()) pw.println(); 18757 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18758 } 18759 18760 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18761 // XXX should handle packageName != null by dumping only install data that 18762 // the given package is involved with. 18763 if (dumpState.onTitlePrinted()) pw.println(); 18764 18765 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18766 ipw.println(); 18767 ipw.println("Frozen packages:"); 18768 ipw.increaseIndent(); 18769 if (mFrozenPackages.size() == 0) { 18770 ipw.println("(none)"); 18771 } else { 18772 for (int i = 0; i < mFrozenPackages.size(); i++) { 18773 ipw.println(mFrozenPackages.valueAt(i)); 18774 } 18775 } 18776 ipw.decreaseIndent(); 18777 } 18778 18779 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18780 if (dumpState.onTitlePrinted()) pw.println(); 18781 dumpDexoptStateLPr(pw, packageName); 18782 } 18783 18784 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18785 if (dumpState.onTitlePrinted()) pw.println(); 18786 mSettings.dumpReadMessagesLPr(pw, dumpState); 18787 18788 pw.println(); 18789 pw.println("Package warning messages:"); 18790 BufferedReader in = null; 18791 String line = null; 18792 try { 18793 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18794 while ((line = in.readLine()) != null) { 18795 if (line.contains("ignored: updated version")) continue; 18796 pw.println(line); 18797 } 18798 } catch (IOException ignored) { 18799 } finally { 18800 IoUtils.closeQuietly(in); 18801 } 18802 } 18803 18804 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18805 BufferedReader in = null; 18806 String line = null; 18807 try { 18808 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18809 while ((line = in.readLine()) != null) { 18810 if (line.contains("ignored: updated version")) continue; 18811 pw.print("msg,"); 18812 pw.println(line); 18813 } 18814 } catch (IOException ignored) { 18815 } finally { 18816 IoUtils.closeQuietly(in); 18817 } 18818 } 18819 } 18820 } 18821 18822 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18823 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18824 ipw.println(); 18825 ipw.println("Dexopt state:"); 18826 ipw.increaseIndent(); 18827 Collection<PackageParser.Package> packages = null; 18828 if (packageName != null) { 18829 PackageParser.Package targetPackage = mPackages.get(packageName); 18830 if (targetPackage != null) { 18831 packages = Collections.singletonList(targetPackage); 18832 } else { 18833 ipw.println("Unable to find package: " + packageName); 18834 return; 18835 } 18836 } else { 18837 packages = mPackages.values(); 18838 } 18839 18840 for (PackageParser.Package pkg : packages) { 18841 ipw.println("[" + pkg.packageName + "]"); 18842 ipw.increaseIndent(); 18843 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18844 ipw.decreaseIndent(); 18845 } 18846 } 18847 18848 private String dumpDomainString(String packageName) { 18849 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18850 .getList(); 18851 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18852 18853 ArraySet<String> result = new ArraySet<>(); 18854 if (iviList.size() > 0) { 18855 for (IntentFilterVerificationInfo ivi : iviList) { 18856 for (String host : ivi.getDomains()) { 18857 result.add(host); 18858 } 18859 } 18860 } 18861 if (filters != null && filters.size() > 0) { 18862 for (IntentFilter filter : filters) { 18863 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18864 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18865 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18866 result.addAll(filter.getHostsList()); 18867 } 18868 } 18869 } 18870 18871 StringBuilder sb = new StringBuilder(result.size() * 16); 18872 for (String domain : result) { 18873 if (sb.length() > 0) sb.append(" "); 18874 sb.append(domain); 18875 } 18876 return sb.toString(); 18877 } 18878 18879 // ------- apps on sdcard specific code ------- 18880 static final boolean DEBUG_SD_INSTALL = false; 18881 18882 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18883 18884 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18885 18886 private boolean mMediaMounted = false; 18887 18888 static String getEncryptKey() { 18889 try { 18890 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18891 SD_ENCRYPTION_KEYSTORE_NAME); 18892 if (sdEncKey == null) { 18893 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18894 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18895 if (sdEncKey == null) { 18896 Slog.e(TAG, "Failed to create encryption keys"); 18897 return null; 18898 } 18899 } 18900 return sdEncKey; 18901 } catch (NoSuchAlgorithmException nsae) { 18902 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18903 return null; 18904 } catch (IOException ioe) { 18905 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18906 return null; 18907 } 18908 } 18909 18910 /* 18911 * Update media status on PackageManager. 18912 */ 18913 @Override 18914 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18915 int callingUid = Binder.getCallingUid(); 18916 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18917 throw new SecurityException("Media status can only be updated by the system"); 18918 } 18919 // reader; this apparently protects mMediaMounted, but should probably 18920 // be a different lock in that case. 18921 synchronized (mPackages) { 18922 Log.i(TAG, "Updating external media status from " 18923 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18924 + (mediaStatus ? "mounted" : "unmounted")); 18925 if (DEBUG_SD_INSTALL) 18926 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18927 + ", mMediaMounted=" + mMediaMounted); 18928 if (mediaStatus == mMediaMounted) { 18929 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18930 : 0, -1); 18931 mHandler.sendMessage(msg); 18932 return; 18933 } 18934 mMediaMounted = mediaStatus; 18935 } 18936 // Queue up an async operation since the package installation may take a 18937 // little while. 18938 mHandler.post(new Runnable() { 18939 public void run() { 18940 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18941 } 18942 }); 18943 } 18944 18945 /** 18946 * Called by MountService when the initial ASECs to scan are available. 18947 * Should block until all the ASEC containers are finished being scanned. 18948 */ 18949 public void scanAvailableAsecs() { 18950 updateExternalMediaStatusInner(true, false, false); 18951 } 18952 18953 /* 18954 * Collect information of applications on external media, map them against 18955 * existing containers and update information based on current mount status. 18956 * Please note that we always have to report status if reportStatus has been 18957 * set to true especially when unloading packages. 18958 */ 18959 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18960 boolean externalStorage) { 18961 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18962 int[] uidArr = EmptyArray.INT; 18963 18964 final String[] list = PackageHelper.getSecureContainerList(); 18965 if (ArrayUtils.isEmpty(list)) { 18966 Log.i(TAG, "No secure containers found"); 18967 } else { 18968 // Process list of secure containers and categorize them 18969 // as active or stale based on their package internal state. 18970 18971 // reader 18972 synchronized (mPackages) { 18973 for (String cid : list) { 18974 // Leave stages untouched for now; installer service owns them 18975 if (PackageInstallerService.isStageName(cid)) continue; 18976 18977 if (DEBUG_SD_INSTALL) 18978 Log.i(TAG, "Processing container " + cid); 18979 String pkgName = getAsecPackageName(cid); 18980 if (pkgName == null) { 18981 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18982 continue; 18983 } 18984 if (DEBUG_SD_INSTALL) 18985 Log.i(TAG, "Looking for pkg : " + pkgName); 18986 18987 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18988 if (ps == null) { 18989 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18990 continue; 18991 } 18992 18993 /* 18994 * Skip packages that are not external if we're unmounting 18995 * external storage. 18996 */ 18997 if (externalStorage && !isMounted && !isExternal(ps)) { 18998 continue; 18999 } 19000 19001 final AsecInstallArgs args = new AsecInstallArgs(cid, 19002 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19003 // The package status is changed only if the code path 19004 // matches between settings and the container id. 19005 if (ps.codePathString != null 19006 && ps.codePathString.startsWith(args.getCodePath())) { 19007 if (DEBUG_SD_INSTALL) { 19008 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19009 + " at code path: " + ps.codePathString); 19010 } 19011 19012 // We do have a valid package installed on sdcard 19013 processCids.put(args, ps.codePathString); 19014 final int uid = ps.appId; 19015 if (uid != -1) { 19016 uidArr = ArrayUtils.appendInt(uidArr, uid); 19017 } 19018 } else { 19019 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19020 + ps.codePathString); 19021 } 19022 } 19023 } 19024 19025 Arrays.sort(uidArr); 19026 } 19027 19028 // Process packages with valid entries. 19029 if (isMounted) { 19030 if (DEBUG_SD_INSTALL) 19031 Log.i(TAG, "Loading packages"); 19032 loadMediaPackages(processCids, uidArr, externalStorage); 19033 startCleaningPackages(); 19034 mInstallerService.onSecureContainersAvailable(); 19035 } else { 19036 if (DEBUG_SD_INSTALL) 19037 Log.i(TAG, "Unloading packages"); 19038 unloadMediaPackages(processCids, uidArr, reportStatus); 19039 } 19040 } 19041 19042 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19043 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19044 final int size = infos.size(); 19045 final String[] packageNames = new String[size]; 19046 final int[] packageUids = new int[size]; 19047 for (int i = 0; i < size; i++) { 19048 final ApplicationInfo info = infos.get(i); 19049 packageNames[i] = info.packageName; 19050 packageUids[i] = info.uid; 19051 } 19052 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19053 finishedReceiver); 19054 } 19055 19056 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19057 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19058 sendResourcesChangedBroadcast(mediaStatus, replacing, 19059 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19060 } 19061 19062 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19063 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19064 int size = pkgList.length; 19065 if (size > 0) { 19066 // Send broadcasts here 19067 Bundle extras = new Bundle(); 19068 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19069 if (uidArr != null) { 19070 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19071 } 19072 if (replacing) { 19073 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19074 } 19075 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19076 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19077 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19078 } 19079 } 19080 19081 /* 19082 * Look at potentially valid container ids from processCids If package 19083 * information doesn't match the one on record or package scanning fails, 19084 * the cid is added to list of removeCids. We currently don't delete stale 19085 * containers. 19086 */ 19087 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19088 boolean externalStorage) { 19089 ArrayList<String> pkgList = new ArrayList<String>(); 19090 Set<AsecInstallArgs> keys = processCids.keySet(); 19091 19092 for (AsecInstallArgs args : keys) { 19093 String codePath = processCids.get(args); 19094 if (DEBUG_SD_INSTALL) 19095 Log.i(TAG, "Loading container : " + args.cid); 19096 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19097 try { 19098 // Make sure there are no container errors first. 19099 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19100 Slog.e(TAG, "Failed to mount cid : " + args.cid 19101 + " when installing from sdcard"); 19102 continue; 19103 } 19104 // Check code path here. 19105 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19106 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19107 + " does not match one in settings " + codePath); 19108 continue; 19109 } 19110 // Parse package 19111 int parseFlags = mDefParseFlags; 19112 if (args.isExternalAsec()) { 19113 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19114 } 19115 if (args.isFwdLocked()) { 19116 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19117 } 19118 19119 synchronized (mInstallLock) { 19120 PackageParser.Package pkg = null; 19121 try { 19122 // Sadly we don't know the package name yet to freeze it 19123 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19124 SCAN_IGNORE_FROZEN, 0, null); 19125 } catch (PackageManagerException e) { 19126 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19127 } 19128 // Scan the package 19129 if (pkg != null) { 19130 /* 19131 * TODO why is the lock being held? doPostInstall is 19132 * called in other places without the lock. This needs 19133 * to be straightened out. 19134 */ 19135 // writer 19136 synchronized (mPackages) { 19137 retCode = PackageManager.INSTALL_SUCCEEDED; 19138 pkgList.add(pkg.packageName); 19139 // Post process args 19140 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19141 pkg.applicationInfo.uid); 19142 } 19143 } else { 19144 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19145 } 19146 } 19147 19148 } finally { 19149 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19150 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19151 } 19152 } 19153 } 19154 // writer 19155 synchronized (mPackages) { 19156 // If the platform SDK has changed since the last time we booted, 19157 // we need to re-grant app permission to catch any new ones that 19158 // appear. This is really a hack, and means that apps can in some 19159 // cases get permissions that the user didn't initially explicitly 19160 // allow... it would be nice to have some better way to handle 19161 // this situation. 19162 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19163 : mSettings.getInternalVersion(); 19164 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19165 : StorageManager.UUID_PRIVATE_INTERNAL; 19166 19167 int updateFlags = UPDATE_PERMISSIONS_ALL; 19168 if (ver.sdkVersion != mSdkVersion) { 19169 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19170 + mSdkVersion + "; regranting permissions for external"); 19171 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19172 } 19173 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19174 19175 // Yay, everything is now upgraded 19176 ver.forceCurrent(); 19177 19178 // can downgrade to reader 19179 // Persist settings 19180 mSettings.writeLPr(); 19181 } 19182 // Send a broadcast to let everyone know we are done processing 19183 if (pkgList.size() > 0) { 19184 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19185 } 19186 } 19187 19188 /* 19189 * Utility method to unload a list of specified containers 19190 */ 19191 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19192 // Just unmount all valid containers. 19193 for (AsecInstallArgs arg : cidArgs) { 19194 synchronized (mInstallLock) { 19195 arg.doPostDeleteLI(false); 19196 } 19197 } 19198 } 19199 19200 /* 19201 * Unload packages mounted on external media. This involves deleting package 19202 * data from internal structures, sending broadcasts about disabled packages, 19203 * gc'ing to free up references, unmounting all secure containers 19204 * corresponding to packages on external media, and posting a 19205 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19206 * that we always have to post this message if status has been requested no 19207 * matter what. 19208 */ 19209 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19210 final boolean reportStatus) { 19211 if (DEBUG_SD_INSTALL) 19212 Log.i(TAG, "unloading media packages"); 19213 ArrayList<String> pkgList = new ArrayList<String>(); 19214 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19215 final Set<AsecInstallArgs> keys = processCids.keySet(); 19216 for (AsecInstallArgs args : keys) { 19217 String pkgName = args.getPackageName(); 19218 if (DEBUG_SD_INSTALL) 19219 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19220 // Delete package internally 19221 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19222 synchronized (mInstallLock) { 19223 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19224 final boolean res; 19225 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19226 "unloadMediaPackages")) { 19227 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19228 null); 19229 } 19230 if (res) { 19231 pkgList.add(pkgName); 19232 } else { 19233 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19234 failedList.add(args); 19235 } 19236 } 19237 } 19238 19239 // reader 19240 synchronized (mPackages) { 19241 // We didn't update the settings after removing each package; 19242 // write them now for all packages. 19243 mSettings.writeLPr(); 19244 } 19245 19246 // We have to absolutely send UPDATED_MEDIA_STATUS only 19247 // after confirming that all the receivers processed the ordered 19248 // broadcast when packages get disabled, force a gc to clean things up. 19249 // and unload all the containers. 19250 if (pkgList.size() > 0) { 19251 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19252 new IIntentReceiver.Stub() { 19253 public void performReceive(Intent intent, int resultCode, String data, 19254 Bundle extras, boolean ordered, boolean sticky, 19255 int sendingUser) throws RemoteException { 19256 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19257 reportStatus ? 1 : 0, 1, keys); 19258 mHandler.sendMessage(msg); 19259 } 19260 }); 19261 } else { 19262 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19263 keys); 19264 mHandler.sendMessage(msg); 19265 } 19266 } 19267 19268 private void loadPrivatePackages(final VolumeInfo vol) { 19269 mHandler.post(new Runnable() { 19270 @Override 19271 public void run() { 19272 loadPrivatePackagesInner(vol); 19273 } 19274 }); 19275 } 19276 19277 private void loadPrivatePackagesInner(VolumeInfo vol) { 19278 final String volumeUuid = vol.fsUuid; 19279 if (TextUtils.isEmpty(volumeUuid)) { 19280 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19281 return; 19282 } 19283 19284 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19285 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19286 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19287 19288 final VersionInfo ver; 19289 final List<PackageSetting> packages; 19290 synchronized (mPackages) { 19291 ver = mSettings.findOrCreateVersion(volumeUuid); 19292 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19293 } 19294 19295 for (PackageSetting ps : packages) { 19296 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19297 synchronized (mInstallLock) { 19298 final PackageParser.Package pkg; 19299 try { 19300 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19301 loaded.add(pkg.applicationInfo); 19302 19303 } catch (PackageManagerException e) { 19304 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19305 } 19306 19307 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19308 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19309 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19310 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19311 } 19312 } 19313 } 19314 19315 // Reconcile app data for all started/unlocked users 19316 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19317 final UserManager um = mContext.getSystemService(UserManager.class); 19318 UserManagerInternal umInternal = getUserManagerInternal(); 19319 for (UserInfo user : um.getUsers()) { 19320 final int flags; 19321 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19322 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19323 } else if (umInternal.isUserRunning(user.id)) { 19324 flags = StorageManager.FLAG_STORAGE_DE; 19325 } else { 19326 continue; 19327 } 19328 19329 try { 19330 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19331 synchronized (mInstallLock) { 19332 reconcileAppsDataLI(volumeUuid, user.id, flags); 19333 } 19334 } catch (IllegalStateException e) { 19335 // Device was probably ejected, and we'll process that event momentarily 19336 Slog.w(TAG, "Failed to prepare storage: " + e); 19337 } 19338 } 19339 19340 synchronized (mPackages) { 19341 int updateFlags = UPDATE_PERMISSIONS_ALL; 19342 if (ver.sdkVersion != mSdkVersion) { 19343 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19344 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19345 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19346 } 19347 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19348 19349 // Yay, everything is now upgraded 19350 ver.forceCurrent(); 19351 19352 mSettings.writeLPr(); 19353 } 19354 19355 for (PackageFreezer freezer : freezers) { 19356 freezer.close(); 19357 } 19358 19359 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19360 sendResourcesChangedBroadcast(true, false, loaded, null); 19361 } 19362 19363 private void unloadPrivatePackages(final VolumeInfo vol) { 19364 mHandler.post(new Runnable() { 19365 @Override 19366 public void run() { 19367 unloadPrivatePackagesInner(vol); 19368 } 19369 }); 19370 } 19371 19372 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19373 final String volumeUuid = vol.fsUuid; 19374 if (TextUtils.isEmpty(volumeUuid)) { 19375 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19376 return; 19377 } 19378 19379 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19380 synchronized (mInstallLock) { 19381 synchronized (mPackages) { 19382 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19383 for (PackageSetting ps : packages) { 19384 if (ps.pkg == null) continue; 19385 19386 final ApplicationInfo info = ps.pkg.applicationInfo; 19387 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19388 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19389 19390 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19391 "unloadPrivatePackagesInner")) { 19392 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19393 false, null)) { 19394 unloaded.add(info); 19395 } else { 19396 Slog.w(TAG, "Failed to unload " + ps.codePath); 19397 } 19398 } 19399 19400 // Try very hard to release any references to this package 19401 // so we don't risk the system server being killed due to 19402 // open FDs 19403 AttributeCache.instance().removePackage(ps.name); 19404 } 19405 19406 mSettings.writeLPr(); 19407 } 19408 } 19409 19410 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19411 sendResourcesChangedBroadcast(false, false, unloaded, null); 19412 19413 // Try very hard to release any references to this path so we don't risk 19414 // the system server being killed due to open FDs 19415 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19416 19417 for (int i = 0; i < 3; i++) { 19418 System.gc(); 19419 System.runFinalization(); 19420 } 19421 } 19422 19423 /** 19424 * Prepare storage areas for given user on all mounted devices. 19425 */ 19426 void prepareUserData(int userId, int userSerial, int flags) { 19427 synchronized (mInstallLock) { 19428 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19429 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19430 final String volumeUuid = vol.getFsUuid(); 19431 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19432 } 19433 } 19434 } 19435 19436 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19437 boolean allowRecover) { 19438 // Prepare storage and verify that serial numbers are consistent; if 19439 // there's a mismatch we need to destroy to avoid leaking data 19440 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19441 try { 19442 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19443 19444 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19445 UserManagerService.enforceSerialNumber( 19446 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19447 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19448 UserManagerService.enforceSerialNumber( 19449 Environment.getDataSystemDeDirectory(userId), userSerial); 19450 } 19451 } 19452 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19453 UserManagerService.enforceSerialNumber( 19454 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19455 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19456 UserManagerService.enforceSerialNumber( 19457 Environment.getDataSystemCeDirectory(userId), userSerial); 19458 } 19459 } 19460 19461 synchronized (mInstallLock) { 19462 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19463 } 19464 } catch (Exception e) { 19465 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19466 + " because we failed to prepare: " + e); 19467 destroyUserDataLI(volumeUuid, userId, 19468 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19469 19470 if (allowRecover) { 19471 // Try one last time; if we fail again we're really in trouble 19472 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19473 } 19474 } 19475 } 19476 19477 /** 19478 * Destroy storage areas for given user on all mounted devices. 19479 */ 19480 void destroyUserData(int userId, int flags) { 19481 synchronized (mInstallLock) { 19482 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19483 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19484 final String volumeUuid = vol.getFsUuid(); 19485 destroyUserDataLI(volumeUuid, userId, flags); 19486 } 19487 } 19488 } 19489 19490 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19491 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19492 try { 19493 // Clean up app data, profile data, and media data 19494 mInstaller.destroyUserData(volumeUuid, userId, flags); 19495 19496 // Clean up system data 19497 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19498 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19499 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19500 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19501 } 19502 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19503 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19504 } 19505 } 19506 19507 // Data with special labels is now gone, so finish the job 19508 storage.destroyUserStorage(volumeUuid, userId, flags); 19509 19510 } catch (Exception e) { 19511 logCriticalInfo(Log.WARN, 19512 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19513 } 19514 } 19515 19516 /** 19517 * Examine all users present on given mounted volume, and destroy data 19518 * belonging to users that are no longer valid, or whose user ID has been 19519 * recycled. 19520 */ 19521 private void reconcileUsers(String volumeUuid) { 19522 final List<File> files = new ArrayList<>(); 19523 Collections.addAll(files, FileUtils 19524 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19525 Collections.addAll(files, FileUtils 19526 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19527 Collections.addAll(files, FileUtils 19528 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19529 Collections.addAll(files, FileUtils 19530 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19531 for (File file : files) { 19532 if (!file.isDirectory()) continue; 19533 19534 final int userId; 19535 final UserInfo info; 19536 try { 19537 userId = Integer.parseInt(file.getName()); 19538 info = sUserManager.getUserInfo(userId); 19539 } catch (NumberFormatException e) { 19540 Slog.w(TAG, "Invalid user directory " + file); 19541 continue; 19542 } 19543 19544 boolean destroyUser = false; 19545 if (info == null) { 19546 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19547 + " because no matching user was found"); 19548 destroyUser = true; 19549 } else if (!mOnlyCore) { 19550 try { 19551 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19552 } catch (IOException e) { 19553 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19554 + " because we failed to enforce serial number: " + e); 19555 destroyUser = true; 19556 } 19557 } 19558 19559 if (destroyUser) { 19560 synchronized (mInstallLock) { 19561 destroyUserDataLI(volumeUuid, userId, 19562 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19563 } 19564 } 19565 } 19566 } 19567 19568 private void assertPackageKnown(String volumeUuid, String packageName) 19569 throws PackageManagerException { 19570 synchronized (mPackages) { 19571 final PackageSetting ps = mSettings.mPackages.get(packageName); 19572 if (ps == null) { 19573 throw new PackageManagerException("Package " + packageName + " is unknown"); 19574 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19575 throw new PackageManagerException( 19576 "Package " + packageName + " found on unknown volume " + volumeUuid 19577 + "; expected volume " + ps.volumeUuid); 19578 } 19579 } 19580 } 19581 19582 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19583 throws PackageManagerException { 19584 synchronized (mPackages) { 19585 final PackageSetting ps = mSettings.mPackages.get(packageName); 19586 if (ps == null) { 19587 throw new PackageManagerException("Package " + packageName + " is unknown"); 19588 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19589 throw new PackageManagerException( 19590 "Package " + packageName + " found on unknown volume " + volumeUuid 19591 + "; expected volume " + ps.volumeUuid); 19592 } else if (!ps.getInstalled(userId)) { 19593 throw new PackageManagerException( 19594 "Package " + packageName + " not installed for user " + userId); 19595 } 19596 } 19597 } 19598 19599 /** 19600 * Examine all apps present on given mounted volume, and destroy apps that 19601 * aren't expected, either due to uninstallation or reinstallation on 19602 * another volume. 19603 */ 19604 private void reconcileApps(String volumeUuid) { 19605 final File[] files = FileUtils 19606 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19607 for (File file : files) { 19608 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19609 && !PackageInstallerService.isStageName(file.getName()); 19610 if (!isPackage) { 19611 // Ignore entries which are not packages 19612 continue; 19613 } 19614 19615 try { 19616 final PackageLite pkg = PackageParser.parsePackageLite(file, 19617 PackageParser.PARSE_MUST_BE_APK); 19618 assertPackageKnown(volumeUuid, pkg.packageName); 19619 19620 } catch (PackageParserException | PackageManagerException e) { 19621 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19622 synchronized (mInstallLock) { 19623 removeCodePathLI(file); 19624 } 19625 } 19626 } 19627 } 19628 19629 /** 19630 * Reconcile all app data for the given user. 19631 * <p> 19632 * Verifies that directories exist and that ownership and labeling is 19633 * correct for all installed apps on all mounted volumes. 19634 */ 19635 void reconcileAppsData(int userId, int flags) { 19636 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19637 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19638 final String volumeUuid = vol.getFsUuid(); 19639 synchronized (mInstallLock) { 19640 reconcileAppsDataLI(volumeUuid, userId, flags); 19641 } 19642 } 19643 } 19644 19645 /** 19646 * Reconcile all app data on given mounted volume. 19647 * <p> 19648 * Destroys app data that isn't expected, either due to uninstallation or 19649 * reinstallation on another volume. 19650 * <p> 19651 * Verifies that directories exist and that ownership and labeling is 19652 * correct for all installed apps. 19653 */ 19654 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19655 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19656 + Integer.toHexString(flags)); 19657 19658 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19659 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19660 19661 boolean restoreconNeeded = false; 19662 19663 // First look for stale data that doesn't belong, and check if things 19664 // have changed since we did our last restorecon 19665 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19666 if (StorageManager.isFileEncryptedNativeOrEmulated() 19667 && !StorageManager.isUserKeyUnlocked(userId)) { 19668 throw new RuntimeException( 19669 "Yikes, someone asked us to reconcile CE storage while " + userId 19670 + " was still locked; this would have caused massive data loss!"); 19671 } 19672 19673 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19674 19675 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19676 for (File file : files) { 19677 final String packageName = file.getName(); 19678 try { 19679 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19680 } catch (PackageManagerException e) { 19681 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19682 try { 19683 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19684 StorageManager.FLAG_STORAGE_CE, 0); 19685 } catch (InstallerException e2) { 19686 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19687 } 19688 } 19689 } 19690 } 19691 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19692 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19693 19694 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19695 for (File file : files) { 19696 final String packageName = file.getName(); 19697 try { 19698 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19699 } catch (PackageManagerException e) { 19700 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19701 try { 19702 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19703 StorageManager.FLAG_STORAGE_DE, 0); 19704 } catch (InstallerException e2) { 19705 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19706 } 19707 } 19708 } 19709 } 19710 19711 // Ensure that data directories are ready to roll for all packages 19712 // installed for this volume and user 19713 final List<PackageSetting> packages; 19714 synchronized (mPackages) { 19715 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19716 } 19717 int preparedCount = 0; 19718 for (PackageSetting ps : packages) { 19719 final String packageName = ps.name; 19720 if (ps.pkg == null) { 19721 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19722 // TODO: might be due to legacy ASEC apps; we should circle back 19723 // and reconcile again once they're scanned 19724 continue; 19725 } 19726 19727 if (ps.getInstalled(userId)) { 19728 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19729 19730 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19731 // We may have just shuffled around app data directories, so 19732 // prepare them one more time 19733 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19734 } 19735 19736 preparedCount++; 19737 } 19738 } 19739 19740 if (restoreconNeeded) { 19741 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19742 SELinuxMMAC.setRestoreconDone(ceDir); 19743 } 19744 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19745 SELinuxMMAC.setRestoreconDone(deDir); 19746 } 19747 } 19748 19749 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19750 + " packages; restoreconNeeded was " + restoreconNeeded); 19751 } 19752 19753 /** 19754 * Prepare app data for the given app just after it was installed or 19755 * upgraded. This method carefully only touches users that it's installed 19756 * for, and it forces a restorecon to handle any seinfo changes. 19757 * <p> 19758 * Verifies that directories exist and that ownership and labeling is 19759 * correct for all installed apps. If there is an ownership mismatch, it 19760 * will try recovering system apps by wiping data; third-party app data is 19761 * left intact. 19762 * <p> 19763 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19764 */ 19765 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19766 final PackageSetting ps; 19767 synchronized (mPackages) { 19768 ps = mSettings.mPackages.get(pkg.packageName); 19769 mSettings.writeKernelMappingLPr(ps); 19770 } 19771 19772 final UserManager um = mContext.getSystemService(UserManager.class); 19773 UserManagerInternal umInternal = getUserManagerInternal(); 19774 for (UserInfo user : um.getUsers()) { 19775 final int flags; 19776 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19777 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19778 } else if (umInternal.isUserRunning(user.id)) { 19779 flags = StorageManager.FLAG_STORAGE_DE; 19780 } else { 19781 continue; 19782 } 19783 19784 if (ps.getInstalled(user.id)) { 19785 // Whenever an app changes, force a restorecon of its data 19786 // TODO: when user data is locked, mark that we're still dirty 19787 prepareAppDataLIF(pkg, user.id, flags, true); 19788 } 19789 } 19790 } 19791 19792 /** 19793 * Prepare app data for the given app. 19794 * <p> 19795 * Verifies that directories exist and that ownership and labeling is 19796 * correct for all installed apps. If there is an ownership mismatch, this 19797 * will try recovering system apps by wiping data; third-party app data is 19798 * left intact. 19799 */ 19800 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19801 boolean restoreconNeeded) { 19802 if (pkg == null) { 19803 Slog.wtf(TAG, "Package was null!", new Throwable()); 19804 return; 19805 } 19806 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19807 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19808 for (int i = 0; i < childCount; i++) { 19809 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19810 } 19811 } 19812 19813 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19814 boolean restoreconNeeded) { 19815 if (DEBUG_APP_DATA) { 19816 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19817 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19818 } 19819 19820 final String volumeUuid = pkg.volumeUuid; 19821 final String packageName = pkg.packageName; 19822 final ApplicationInfo app = pkg.applicationInfo; 19823 final int appId = UserHandle.getAppId(app.uid); 19824 19825 Preconditions.checkNotNull(app.seinfo); 19826 19827 try { 19828 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19829 appId, app.seinfo, app.targetSdkVersion); 19830 } catch (InstallerException e) { 19831 if (app.isSystemApp()) { 19832 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19833 + ", but trying to recover: " + e); 19834 destroyAppDataLeafLIF(pkg, userId, flags); 19835 try { 19836 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19837 appId, app.seinfo, app.targetSdkVersion); 19838 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19839 } catch (InstallerException e2) { 19840 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19841 } 19842 } else { 19843 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19844 } 19845 } 19846 19847 if (restoreconNeeded) { 19848 try { 19849 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19850 app.seinfo); 19851 } catch (InstallerException e) { 19852 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19853 } 19854 } 19855 19856 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19857 try { 19858 // CE storage is unlocked right now, so read out the inode and 19859 // remember for use later when it's locked 19860 // TODO: mark this structure as dirty so we persist it! 19861 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19862 StorageManager.FLAG_STORAGE_CE); 19863 synchronized (mPackages) { 19864 final PackageSetting ps = mSettings.mPackages.get(packageName); 19865 if (ps != null) { 19866 ps.setCeDataInode(ceDataInode, userId); 19867 } 19868 } 19869 } catch (InstallerException e) { 19870 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19871 } 19872 } 19873 19874 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19875 } 19876 19877 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19878 if (pkg == null) { 19879 Slog.wtf(TAG, "Package was null!", new Throwable()); 19880 return; 19881 } 19882 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19883 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19884 for (int i = 0; i < childCount; i++) { 19885 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19886 } 19887 } 19888 19889 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19890 final String volumeUuid = pkg.volumeUuid; 19891 final String packageName = pkg.packageName; 19892 final ApplicationInfo app = pkg.applicationInfo; 19893 19894 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19895 // Create a native library symlink only if we have native libraries 19896 // and if the native libraries are 32 bit libraries. We do not provide 19897 // this symlink for 64 bit libraries. 19898 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19899 final String nativeLibPath = app.nativeLibraryDir; 19900 try { 19901 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19902 nativeLibPath, userId); 19903 } catch (InstallerException e) { 19904 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19905 } 19906 } 19907 } 19908 } 19909 19910 /** 19911 * For system apps on non-FBE devices, this method migrates any existing 19912 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19913 * requested by the app. 19914 */ 19915 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19916 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19917 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19918 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19919 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19920 try { 19921 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19922 storageTarget); 19923 } catch (InstallerException e) { 19924 logCriticalInfo(Log.WARN, 19925 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19926 } 19927 return true; 19928 } else { 19929 return false; 19930 } 19931 } 19932 19933 public PackageFreezer freezePackage(String packageName, String killReason) { 19934 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 19935 } 19936 19937 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 19938 return new PackageFreezer(packageName, userId, killReason); 19939 } 19940 19941 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19942 String killReason) { 19943 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 19944 } 19945 19946 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 19947 String killReason) { 19948 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19949 return new PackageFreezer(); 19950 } else { 19951 return freezePackage(packageName, userId, killReason); 19952 } 19953 } 19954 19955 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19956 String killReason) { 19957 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 19958 } 19959 19960 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 19961 String killReason) { 19962 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19963 return new PackageFreezer(); 19964 } else { 19965 return freezePackage(packageName, userId, killReason); 19966 } 19967 } 19968 19969 /** 19970 * Class that freezes and kills the given package upon creation, and 19971 * unfreezes it upon closing. This is typically used when doing surgery on 19972 * app code/data to prevent the app from running while you're working. 19973 */ 19974 private class PackageFreezer implements AutoCloseable { 19975 private final String mPackageName; 19976 private final PackageFreezer[] mChildren; 19977 19978 private final boolean mWeFroze; 19979 19980 private final AtomicBoolean mClosed = new AtomicBoolean(); 19981 private final CloseGuard mCloseGuard = CloseGuard.get(); 19982 19983 /** 19984 * Create and return a stub freezer that doesn't actually do anything, 19985 * typically used when someone requested 19986 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19987 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19988 */ 19989 public PackageFreezer() { 19990 mPackageName = null; 19991 mChildren = null; 19992 mWeFroze = false; 19993 mCloseGuard.open("close"); 19994 } 19995 19996 public PackageFreezer(String packageName, int userId, String killReason) { 19997 synchronized (mPackages) { 19998 mPackageName = packageName; 19999 mWeFroze = mFrozenPackages.add(mPackageName); 20000 20001 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20002 if (ps != null) { 20003 killApplication(ps.name, ps.appId, userId, killReason); 20004 } 20005 20006 final PackageParser.Package p = mPackages.get(packageName); 20007 if (p != null && p.childPackages != null) { 20008 final int N = p.childPackages.size(); 20009 mChildren = new PackageFreezer[N]; 20010 for (int i = 0; i < N; i++) { 20011 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20012 userId, killReason); 20013 } 20014 } else { 20015 mChildren = null; 20016 } 20017 } 20018 mCloseGuard.open("close"); 20019 } 20020 20021 @Override 20022 protected void finalize() throws Throwable { 20023 try { 20024 mCloseGuard.warnIfOpen(); 20025 close(); 20026 } finally { 20027 super.finalize(); 20028 } 20029 } 20030 20031 @Override 20032 public void close() { 20033 mCloseGuard.close(); 20034 if (mClosed.compareAndSet(false, true)) { 20035 synchronized (mPackages) { 20036 if (mWeFroze) { 20037 mFrozenPackages.remove(mPackageName); 20038 } 20039 20040 if (mChildren != null) { 20041 for (PackageFreezer freezer : mChildren) { 20042 freezer.close(); 20043 } 20044 } 20045 } 20046 } 20047 } 20048 } 20049 20050 /** 20051 * Verify that given package is currently frozen. 20052 */ 20053 private void checkPackageFrozen(String packageName) { 20054 synchronized (mPackages) { 20055 if (!mFrozenPackages.contains(packageName)) { 20056 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20057 } 20058 } 20059 } 20060 20061 @Override 20062 public int movePackage(final String packageName, final String volumeUuid) { 20063 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20064 20065 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20066 final int moveId = mNextMoveId.getAndIncrement(); 20067 mHandler.post(new Runnable() { 20068 @Override 20069 public void run() { 20070 try { 20071 movePackageInternal(packageName, volumeUuid, moveId, user); 20072 } catch (PackageManagerException e) { 20073 Slog.w(TAG, "Failed to move " + packageName, e); 20074 mMoveCallbacks.notifyStatusChanged(moveId, 20075 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20076 } 20077 } 20078 }); 20079 return moveId; 20080 } 20081 20082 private void movePackageInternal(final String packageName, final String volumeUuid, 20083 final int moveId, UserHandle user) throws PackageManagerException { 20084 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20085 final PackageManager pm = mContext.getPackageManager(); 20086 20087 final boolean currentAsec; 20088 final String currentVolumeUuid; 20089 final File codeFile; 20090 final String installerPackageName; 20091 final String packageAbiOverride; 20092 final int appId; 20093 final String seinfo; 20094 final String label; 20095 final int targetSdkVersion; 20096 final PackageFreezer freezer; 20097 final int[] installedUserIds; 20098 20099 // reader 20100 synchronized (mPackages) { 20101 final PackageParser.Package pkg = mPackages.get(packageName); 20102 final PackageSetting ps = mSettings.mPackages.get(packageName); 20103 if (pkg == null || ps == null) { 20104 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20105 } 20106 20107 if (pkg.applicationInfo.isSystemApp()) { 20108 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20109 "Cannot move system application"); 20110 } 20111 20112 if (pkg.applicationInfo.isExternalAsec()) { 20113 currentAsec = true; 20114 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20115 } else if (pkg.applicationInfo.isForwardLocked()) { 20116 currentAsec = true; 20117 currentVolumeUuid = "forward_locked"; 20118 } else { 20119 currentAsec = false; 20120 currentVolumeUuid = ps.volumeUuid; 20121 20122 final File probe = new File(pkg.codePath); 20123 final File probeOat = new File(probe, "oat"); 20124 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20125 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20126 "Move only supported for modern cluster style installs"); 20127 } 20128 } 20129 20130 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20131 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20132 "Package already moved to " + volumeUuid); 20133 } 20134 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20135 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20136 "Device admin cannot be moved"); 20137 } 20138 20139 if (mFrozenPackages.contains(packageName)) { 20140 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20141 "Failed to move already frozen package"); 20142 } 20143 20144 codeFile = new File(pkg.codePath); 20145 installerPackageName = ps.installerPackageName; 20146 packageAbiOverride = ps.cpuAbiOverrideString; 20147 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20148 seinfo = pkg.applicationInfo.seinfo; 20149 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20150 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20151 freezer = freezePackage(packageName, "movePackageInternal"); 20152 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20153 } 20154 20155 final Bundle extras = new Bundle(); 20156 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20157 extras.putString(Intent.EXTRA_TITLE, label); 20158 mMoveCallbacks.notifyCreated(moveId, extras); 20159 20160 int installFlags; 20161 final boolean moveCompleteApp; 20162 final File measurePath; 20163 20164 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20165 installFlags = INSTALL_INTERNAL; 20166 moveCompleteApp = !currentAsec; 20167 measurePath = Environment.getDataAppDirectory(volumeUuid); 20168 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20169 installFlags = INSTALL_EXTERNAL; 20170 moveCompleteApp = false; 20171 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20172 } else { 20173 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20174 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20175 || !volume.isMountedWritable()) { 20176 freezer.close(); 20177 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20178 "Move location not mounted private volume"); 20179 } 20180 20181 Preconditions.checkState(!currentAsec); 20182 20183 installFlags = INSTALL_INTERNAL; 20184 moveCompleteApp = true; 20185 measurePath = Environment.getDataAppDirectory(volumeUuid); 20186 } 20187 20188 final PackageStats stats = new PackageStats(null, -1); 20189 synchronized (mInstaller) { 20190 for (int userId : installedUserIds) { 20191 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20192 freezer.close(); 20193 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20194 "Failed to measure package size"); 20195 } 20196 } 20197 } 20198 20199 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20200 + stats.dataSize); 20201 20202 final long startFreeBytes = measurePath.getFreeSpace(); 20203 final long sizeBytes; 20204 if (moveCompleteApp) { 20205 sizeBytes = stats.codeSize + stats.dataSize; 20206 } else { 20207 sizeBytes = stats.codeSize; 20208 } 20209 20210 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20211 freezer.close(); 20212 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20213 "Not enough free space to move"); 20214 } 20215 20216 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20217 20218 final CountDownLatch installedLatch = new CountDownLatch(1); 20219 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20220 @Override 20221 public void onUserActionRequired(Intent intent) throws RemoteException { 20222 throw new IllegalStateException(); 20223 } 20224 20225 @Override 20226 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20227 Bundle extras) throws RemoteException { 20228 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20229 + PackageManager.installStatusToString(returnCode, msg)); 20230 20231 installedLatch.countDown(); 20232 freezer.close(); 20233 20234 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20235 switch (status) { 20236 case PackageInstaller.STATUS_SUCCESS: 20237 mMoveCallbacks.notifyStatusChanged(moveId, 20238 PackageManager.MOVE_SUCCEEDED); 20239 break; 20240 case PackageInstaller.STATUS_FAILURE_STORAGE: 20241 mMoveCallbacks.notifyStatusChanged(moveId, 20242 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20243 break; 20244 default: 20245 mMoveCallbacks.notifyStatusChanged(moveId, 20246 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20247 break; 20248 } 20249 } 20250 }; 20251 20252 final MoveInfo move; 20253 if (moveCompleteApp) { 20254 // Kick off a thread to report progress estimates 20255 new Thread() { 20256 @Override 20257 public void run() { 20258 while (true) { 20259 try { 20260 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20261 break; 20262 } 20263 } catch (InterruptedException ignored) { 20264 } 20265 20266 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20267 final int progress = 10 + (int) MathUtils.constrain( 20268 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20269 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20270 } 20271 } 20272 }.start(); 20273 20274 final String dataAppName = codeFile.getName(); 20275 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20276 dataAppName, appId, seinfo, targetSdkVersion); 20277 } else { 20278 move = null; 20279 } 20280 20281 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20282 20283 final Message msg = mHandler.obtainMessage(INIT_COPY); 20284 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20285 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20286 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20287 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20288 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20289 msg.obj = params; 20290 20291 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20292 System.identityHashCode(msg.obj)); 20293 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20294 System.identityHashCode(msg.obj)); 20295 20296 mHandler.sendMessage(msg); 20297 } 20298 20299 @Override 20300 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20301 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20302 20303 final int realMoveId = mNextMoveId.getAndIncrement(); 20304 final Bundle extras = new Bundle(); 20305 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20306 mMoveCallbacks.notifyCreated(realMoveId, extras); 20307 20308 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20309 @Override 20310 public void onCreated(int moveId, Bundle extras) { 20311 // Ignored 20312 } 20313 20314 @Override 20315 public void onStatusChanged(int moveId, int status, long estMillis) { 20316 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20317 } 20318 }; 20319 20320 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20321 storage.setPrimaryStorageUuid(volumeUuid, callback); 20322 return realMoveId; 20323 } 20324 20325 @Override 20326 public int getMoveStatus(int moveId) { 20327 mContext.enforceCallingOrSelfPermission( 20328 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20329 return mMoveCallbacks.mLastStatus.get(moveId); 20330 } 20331 20332 @Override 20333 public void registerMoveCallback(IPackageMoveObserver callback) { 20334 mContext.enforceCallingOrSelfPermission( 20335 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20336 mMoveCallbacks.register(callback); 20337 } 20338 20339 @Override 20340 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20341 mContext.enforceCallingOrSelfPermission( 20342 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20343 mMoveCallbacks.unregister(callback); 20344 } 20345 20346 @Override 20347 public boolean setInstallLocation(int loc) { 20348 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20349 null); 20350 if (getInstallLocation() == loc) { 20351 return true; 20352 } 20353 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20354 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20355 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20356 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20357 return true; 20358 } 20359 return false; 20360 } 20361 20362 @Override 20363 public int getInstallLocation() { 20364 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20365 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20366 PackageHelper.APP_INSTALL_AUTO); 20367 } 20368 20369 /** Called by UserManagerService */ 20370 void cleanUpUser(UserManagerService userManager, int userHandle) { 20371 synchronized (mPackages) { 20372 mDirtyUsers.remove(userHandle); 20373 mUserNeedsBadging.delete(userHandle); 20374 mSettings.removeUserLPw(userHandle); 20375 mPendingBroadcasts.remove(userHandle); 20376 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20377 removeUnusedPackagesLPw(userManager, userHandle); 20378 } 20379 } 20380 20381 /** 20382 * We're removing userHandle and would like to remove any downloaded packages 20383 * that are no longer in use by any other user. 20384 * @param userHandle the user being removed 20385 */ 20386 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20387 final boolean DEBUG_CLEAN_APKS = false; 20388 int [] users = userManager.getUserIds(); 20389 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20390 while (psit.hasNext()) { 20391 PackageSetting ps = psit.next(); 20392 if (ps.pkg == null) { 20393 continue; 20394 } 20395 final String packageName = ps.pkg.packageName; 20396 // Skip over if system app 20397 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20398 continue; 20399 } 20400 if (DEBUG_CLEAN_APKS) { 20401 Slog.i(TAG, "Checking package " + packageName); 20402 } 20403 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20404 if (keep) { 20405 if (DEBUG_CLEAN_APKS) { 20406 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20407 } 20408 } else { 20409 for (int i = 0; i < users.length; i++) { 20410 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20411 keep = true; 20412 if (DEBUG_CLEAN_APKS) { 20413 Slog.i(TAG, " Keeping package " + packageName + " for user " 20414 + users[i]); 20415 } 20416 break; 20417 } 20418 } 20419 } 20420 if (!keep) { 20421 if (DEBUG_CLEAN_APKS) { 20422 Slog.i(TAG, " Removing package " + packageName); 20423 } 20424 mHandler.post(new Runnable() { 20425 public void run() { 20426 deletePackageX(packageName, userHandle, 0); 20427 } //end run 20428 }); 20429 } 20430 } 20431 } 20432 20433 /** Called by UserManagerService */ 20434 void createNewUser(int userId) { 20435 synchronized (mInstallLock) { 20436 mSettings.createNewUserLI(this, mInstaller, userId); 20437 } 20438 synchronized (mPackages) { 20439 scheduleWritePackageRestrictionsLocked(userId); 20440 scheduleWritePackageListLocked(userId); 20441 applyFactoryDefaultBrowserLPw(userId); 20442 primeDomainVerificationsLPw(userId); 20443 } 20444 } 20445 20446 void onNewUserCreated(final int userId) { 20447 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20448 // If permission review for legacy apps is required, we represent 20449 // dagerous permissions for such apps as always granted runtime 20450 // permissions to keep per user flag state whether review is needed. 20451 // Hence, if a new user is added we have to propagate dangerous 20452 // permission grants for these legacy apps. 20453 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20454 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20455 | UPDATE_PERMISSIONS_REPLACE_ALL); 20456 } 20457 } 20458 20459 @Override 20460 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20461 mContext.enforceCallingOrSelfPermission( 20462 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20463 "Only package verification agents can read the verifier device identity"); 20464 20465 synchronized (mPackages) { 20466 return mSettings.getVerifierDeviceIdentityLPw(); 20467 } 20468 } 20469 20470 @Override 20471 public void setPermissionEnforced(String permission, boolean enforced) { 20472 // TODO: Now that we no longer change GID for storage, this should to away. 20473 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20474 "setPermissionEnforced"); 20475 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20476 synchronized (mPackages) { 20477 if (mSettings.mReadExternalStorageEnforced == null 20478 || mSettings.mReadExternalStorageEnforced != enforced) { 20479 mSettings.mReadExternalStorageEnforced = enforced; 20480 mSettings.writeLPr(); 20481 } 20482 } 20483 // kill any non-foreground processes so we restart them and 20484 // grant/revoke the GID. 20485 final IActivityManager am = ActivityManagerNative.getDefault(); 20486 if (am != null) { 20487 final long token = Binder.clearCallingIdentity(); 20488 try { 20489 am.killProcessesBelowForeground("setPermissionEnforcement"); 20490 } catch (RemoteException e) { 20491 } finally { 20492 Binder.restoreCallingIdentity(token); 20493 } 20494 } 20495 } else { 20496 throw new IllegalArgumentException("No selective enforcement for " + permission); 20497 } 20498 } 20499 20500 @Override 20501 @Deprecated 20502 public boolean isPermissionEnforced(String permission) { 20503 return true; 20504 } 20505 20506 @Override 20507 public boolean isStorageLow() { 20508 final long token = Binder.clearCallingIdentity(); 20509 try { 20510 final DeviceStorageMonitorInternal 20511 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20512 if (dsm != null) { 20513 return dsm.isMemoryLow(); 20514 } else { 20515 return false; 20516 } 20517 } finally { 20518 Binder.restoreCallingIdentity(token); 20519 } 20520 } 20521 20522 @Override 20523 public IPackageInstaller getPackageInstaller() { 20524 return mInstallerService; 20525 } 20526 20527 private boolean userNeedsBadging(int userId) { 20528 int index = mUserNeedsBadging.indexOfKey(userId); 20529 if (index < 0) { 20530 final UserInfo userInfo; 20531 final long token = Binder.clearCallingIdentity(); 20532 try { 20533 userInfo = sUserManager.getUserInfo(userId); 20534 } finally { 20535 Binder.restoreCallingIdentity(token); 20536 } 20537 final boolean b; 20538 if (userInfo != null && userInfo.isManagedProfile()) { 20539 b = true; 20540 } else { 20541 b = false; 20542 } 20543 mUserNeedsBadging.put(userId, b); 20544 return b; 20545 } 20546 return mUserNeedsBadging.valueAt(index); 20547 } 20548 20549 @Override 20550 public KeySet getKeySetByAlias(String packageName, String alias) { 20551 if (packageName == null || alias == null) { 20552 return null; 20553 } 20554 synchronized(mPackages) { 20555 final PackageParser.Package pkg = mPackages.get(packageName); 20556 if (pkg == null) { 20557 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20558 throw new IllegalArgumentException("Unknown package: " + packageName); 20559 } 20560 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20561 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20562 } 20563 } 20564 20565 @Override 20566 public KeySet getSigningKeySet(String packageName) { 20567 if (packageName == null) { 20568 return null; 20569 } 20570 synchronized(mPackages) { 20571 final PackageParser.Package pkg = mPackages.get(packageName); 20572 if (pkg == null) { 20573 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20574 throw new IllegalArgumentException("Unknown package: " + packageName); 20575 } 20576 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20577 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20578 throw new SecurityException("May not access signing KeySet of other apps."); 20579 } 20580 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20581 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20582 } 20583 } 20584 20585 @Override 20586 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20587 if (packageName == null || ks == null) { 20588 return false; 20589 } 20590 synchronized(mPackages) { 20591 final PackageParser.Package pkg = mPackages.get(packageName); 20592 if (pkg == null) { 20593 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20594 throw new IllegalArgumentException("Unknown package: " + packageName); 20595 } 20596 IBinder ksh = ks.getToken(); 20597 if (ksh instanceof KeySetHandle) { 20598 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20599 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20600 } 20601 return false; 20602 } 20603 } 20604 20605 @Override 20606 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20607 if (packageName == null || ks == null) { 20608 return false; 20609 } 20610 synchronized(mPackages) { 20611 final PackageParser.Package pkg = mPackages.get(packageName); 20612 if (pkg == null) { 20613 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20614 throw new IllegalArgumentException("Unknown package: " + packageName); 20615 } 20616 IBinder ksh = ks.getToken(); 20617 if (ksh instanceof KeySetHandle) { 20618 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20619 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20620 } 20621 return false; 20622 } 20623 } 20624 20625 private void deletePackageIfUnusedLPr(final String packageName) { 20626 PackageSetting ps = mSettings.mPackages.get(packageName); 20627 if (ps == null) { 20628 return; 20629 } 20630 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20631 // TODO Implement atomic delete if package is unused 20632 // It is currently possible that the package will be deleted even if it is installed 20633 // after this method returns. 20634 mHandler.post(new Runnable() { 20635 public void run() { 20636 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20637 } 20638 }); 20639 } 20640 } 20641 20642 /** 20643 * Check and throw if the given before/after packages would be considered a 20644 * downgrade. 20645 */ 20646 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20647 throws PackageManagerException { 20648 if (after.versionCode < before.mVersionCode) { 20649 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20650 "Update version code " + after.versionCode + " is older than current " 20651 + before.mVersionCode); 20652 } else if (after.versionCode == before.mVersionCode) { 20653 if (after.baseRevisionCode < before.baseRevisionCode) { 20654 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20655 "Update base revision code " + after.baseRevisionCode 20656 + " is older than current " + before.baseRevisionCode); 20657 } 20658 20659 if (!ArrayUtils.isEmpty(after.splitNames)) { 20660 for (int i = 0; i < after.splitNames.length; i++) { 20661 final String splitName = after.splitNames[i]; 20662 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20663 if (j != -1) { 20664 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20665 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20666 "Update split " + splitName + " revision code " 20667 + after.splitRevisionCodes[i] + " is older than current " 20668 + before.splitRevisionCodes[j]); 20669 } 20670 } 20671 } 20672 } 20673 } 20674 } 20675 20676 private static class MoveCallbacks extends Handler { 20677 private static final int MSG_CREATED = 1; 20678 private static final int MSG_STATUS_CHANGED = 2; 20679 20680 private final RemoteCallbackList<IPackageMoveObserver> 20681 mCallbacks = new RemoteCallbackList<>(); 20682 20683 private final SparseIntArray mLastStatus = new SparseIntArray(); 20684 20685 public MoveCallbacks(Looper looper) { 20686 super(looper); 20687 } 20688 20689 public void register(IPackageMoveObserver callback) { 20690 mCallbacks.register(callback); 20691 } 20692 20693 public void unregister(IPackageMoveObserver callback) { 20694 mCallbacks.unregister(callback); 20695 } 20696 20697 @Override 20698 public void handleMessage(Message msg) { 20699 final SomeArgs args = (SomeArgs) msg.obj; 20700 final int n = mCallbacks.beginBroadcast(); 20701 for (int i = 0; i < n; i++) { 20702 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20703 try { 20704 invokeCallback(callback, msg.what, args); 20705 } catch (RemoteException ignored) { 20706 } 20707 } 20708 mCallbacks.finishBroadcast(); 20709 args.recycle(); 20710 } 20711 20712 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20713 throws RemoteException { 20714 switch (what) { 20715 case MSG_CREATED: { 20716 callback.onCreated(args.argi1, (Bundle) args.arg2); 20717 break; 20718 } 20719 case MSG_STATUS_CHANGED: { 20720 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20721 break; 20722 } 20723 } 20724 } 20725 20726 private void notifyCreated(int moveId, Bundle extras) { 20727 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20728 20729 final SomeArgs args = SomeArgs.obtain(); 20730 args.argi1 = moveId; 20731 args.arg2 = extras; 20732 obtainMessage(MSG_CREATED, args).sendToTarget(); 20733 } 20734 20735 private void notifyStatusChanged(int moveId, int status) { 20736 notifyStatusChanged(moveId, status, -1); 20737 } 20738 20739 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20740 Slog.v(TAG, "Move " + moveId + " status " + status); 20741 20742 final SomeArgs args = SomeArgs.obtain(); 20743 args.argi1 = moveId; 20744 args.argi2 = status; 20745 args.arg3 = estMillis; 20746 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20747 20748 synchronized (mLastStatus) { 20749 mLastStatus.put(moveId, status); 20750 } 20751 } 20752 } 20753 20754 private final static class OnPermissionChangeListeners extends Handler { 20755 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20756 20757 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20758 new RemoteCallbackList<>(); 20759 20760 public OnPermissionChangeListeners(Looper looper) { 20761 super(looper); 20762 } 20763 20764 @Override 20765 public void handleMessage(Message msg) { 20766 switch (msg.what) { 20767 case MSG_ON_PERMISSIONS_CHANGED: { 20768 final int uid = msg.arg1; 20769 handleOnPermissionsChanged(uid); 20770 } break; 20771 } 20772 } 20773 20774 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20775 mPermissionListeners.register(listener); 20776 20777 } 20778 20779 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20780 mPermissionListeners.unregister(listener); 20781 } 20782 20783 public void onPermissionsChanged(int uid) { 20784 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20785 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20786 } 20787 } 20788 20789 private void handleOnPermissionsChanged(int uid) { 20790 final int count = mPermissionListeners.beginBroadcast(); 20791 try { 20792 for (int i = 0; i < count; i++) { 20793 IOnPermissionsChangeListener callback = mPermissionListeners 20794 .getBroadcastItem(i); 20795 try { 20796 callback.onPermissionsChanged(uid); 20797 } catch (RemoteException e) { 20798 Log.e(TAG, "Permission listener is dead", e); 20799 } 20800 } 20801 } finally { 20802 mPermissionListeners.finishBroadcast(); 20803 } 20804 } 20805 } 20806 20807 private class PackageManagerInternalImpl extends PackageManagerInternal { 20808 @Override 20809 public void setLocationPackagesProvider(PackagesProvider provider) { 20810 synchronized (mPackages) { 20811 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20812 } 20813 } 20814 20815 @Override 20816 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20817 synchronized (mPackages) { 20818 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20819 } 20820 } 20821 20822 @Override 20823 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20824 synchronized (mPackages) { 20825 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20826 } 20827 } 20828 20829 @Override 20830 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20831 synchronized (mPackages) { 20832 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20833 } 20834 } 20835 20836 @Override 20837 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20838 synchronized (mPackages) { 20839 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20840 } 20841 } 20842 20843 @Override 20844 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20845 synchronized (mPackages) { 20846 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20847 } 20848 } 20849 20850 @Override 20851 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20852 synchronized (mPackages) { 20853 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20854 packageName, userId); 20855 } 20856 } 20857 20858 @Override 20859 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20860 synchronized (mPackages) { 20861 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20862 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20863 packageName, userId); 20864 } 20865 } 20866 20867 @Override 20868 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20869 synchronized (mPackages) { 20870 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20871 packageName, userId); 20872 } 20873 } 20874 20875 @Override 20876 public void setKeepUninstalledPackages(final List<String> packageList) { 20877 Preconditions.checkNotNull(packageList); 20878 List<String> removedFromList = null; 20879 synchronized (mPackages) { 20880 if (mKeepUninstalledPackages != null) { 20881 final int packagesCount = mKeepUninstalledPackages.size(); 20882 for (int i = 0; i < packagesCount; i++) { 20883 String oldPackage = mKeepUninstalledPackages.get(i); 20884 if (packageList != null && packageList.contains(oldPackage)) { 20885 continue; 20886 } 20887 if (removedFromList == null) { 20888 removedFromList = new ArrayList<>(); 20889 } 20890 removedFromList.add(oldPackage); 20891 } 20892 } 20893 mKeepUninstalledPackages = new ArrayList<>(packageList); 20894 if (removedFromList != null) { 20895 final int removedCount = removedFromList.size(); 20896 for (int i = 0; i < removedCount; i++) { 20897 deletePackageIfUnusedLPr(removedFromList.get(i)); 20898 } 20899 } 20900 } 20901 } 20902 20903 @Override 20904 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20905 synchronized (mPackages) { 20906 // If we do not support permission review, done. 20907 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20908 return false; 20909 } 20910 20911 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20912 if (packageSetting == null) { 20913 return false; 20914 } 20915 20916 // Permission review applies only to apps not supporting the new permission model. 20917 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20918 return false; 20919 } 20920 20921 // Legacy apps have the permission and get user consent on launch. 20922 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20923 return permissionsState.isPermissionReviewRequired(userId); 20924 } 20925 } 20926 20927 @Override 20928 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20929 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20930 } 20931 20932 @Override 20933 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20934 int userId) { 20935 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20936 } 20937 20938 @Override 20939 public void setDeviceAndProfileOwnerPackages( 20940 int deviceOwnerUserId, String deviceOwnerPackage, 20941 SparseArray<String> profileOwnerPackages) { 20942 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20943 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20944 } 20945 20946 @Override 20947 public boolean isPackageDataProtected(int userId, String packageName) { 20948 return mProtectedPackages.isPackageDataProtected(userId, packageName); 20949 } 20950 } 20951 20952 @Override 20953 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20954 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20955 synchronized (mPackages) { 20956 final long identity = Binder.clearCallingIdentity(); 20957 try { 20958 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20959 packageNames, userId); 20960 } finally { 20961 Binder.restoreCallingIdentity(identity); 20962 } 20963 } 20964 } 20965 20966 private static void enforceSystemOrPhoneCaller(String tag) { 20967 int callingUid = Binder.getCallingUid(); 20968 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20969 throw new SecurityException( 20970 "Cannot call " + tag + " from UID " + callingUid); 20971 } 20972 } 20973 20974 boolean isHistoricalPackageUsageAvailable() { 20975 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20976 } 20977 20978 /** 20979 * Return a <b>copy</b> of the collection of packages known to the package manager. 20980 * @return A copy of the values of mPackages. 20981 */ 20982 Collection<PackageParser.Package> getPackages() { 20983 synchronized (mPackages) { 20984 return new ArrayList<>(mPackages.values()); 20985 } 20986 } 20987 20988 /** 20989 * Logs process start information (including base APK hash) to the security log. 20990 * @hide 20991 */ 20992 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20993 String apkFile, int pid) { 20994 if (!SecurityLog.isLoggingEnabled()) { 20995 return; 20996 } 20997 Bundle data = new Bundle(); 20998 data.putLong("startTimestamp", System.currentTimeMillis()); 20999 data.putString("processName", processName); 21000 data.putInt("uid", uid); 21001 data.putString("seinfo", seinfo); 21002 data.putString("apkFile", apkFile); 21003 data.putInt("pid", pid); 21004 Message msg = mProcessLoggingHandler.obtainMessage( 21005 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21006 msg.setData(data); 21007 mProcessLoggingHandler.sendMessage(msg); 21008 } 21009} 21010