PackageManagerService.java revision 7877b8add811aafd7f57f731c8e22c9fe6a319c8
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.Signature; 163import android.content.pm.UserInfo; 164import android.content.pm.VerifierDeviceIdentity; 165import android.content.pm.VerifierInfo; 166import android.content.res.Resources; 167import android.graphics.Bitmap; 168import android.hardware.display.DisplayManager; 169import android.net.Uri; 170import android.os.Binder; 171import android.os.Build; 172import android.os.Bundle; 173import android.os.Debug; 174import android.os.Environment; 175import android.os.Environment.UserEnvironment; 176import android.os.FileUtils; 177import android.os.Handler; 178import android.os.IBinder; 179import android.os.Looper; 180import android.os.Message; 181import android.os.Parcel; 182import android.os.ParcelFileDescriptor; 183import android.os.Process; 184import android.os.RemoteCallbackList; 185import android.os.RemoteException; 186import android.os.ResultReceiver; 187import android.os.SELinux; 188import android.os.ServiceManager; 189import android.os.SystemClock; 190import android.os.SystemProperties; 191import android.os.Trace; 192import android.os.UserHandle; 193import android.os.UserManager; 194import android.os.UserManagerInternal; 195import android.os.storage.IMountService; 196import android.os.storage.MountServiceInternal; 197import android.os.storage.StorageEventListener; 198import android.os.storage.StorageManager; 199import android.os.storage.VolumeInfo; 200import android.os.storage.VolumeRecord; 201import android.provider.Settings.Global; 202import android.security.KeyStore; 203import android.security.SystemKeyStore; 204import android.system.ErrnoException; 205import android.system.Os; 206import android.text.TextUtils; 207import android.text.format.DateUtils; 208import android.util.ArrayMap; 209import android.util.ArraySet; 210import android.util.AtomicFile; 211import android.util.DisplayMetrics; 212import android.util.EventLog; 213import android.util.ExceptionUtils; 214import android.util.Log; 215import android.util.LogPrinter; 216import android.util.MathUtils; 217import android.util.PrintStreamPrinter; 218import android.util.Slog; 219import android.util.SparseArray; 220import android.util.SparseBooleanArray; 221import android.util.SparseIntArray; 222import android.util.Xml; 223import android.util.jar.StrictJarFile; 224import android.view.Display; 225 226import com.android.internal.R; 227import com.android.internal.annotations.GuardedBy; 228import com.android.internal.app.IMediaContainerService; 229import com.android.internal.app.ResolverActivity; 230import com.android.internal.content.NativeLibraryHelper; 231import com.android.internal.content.PackageHelper; 232import com.android.internal.logging.MetricsLogger; 233import com.android.internal.os.IParcelFileDescriptorFactory; 234import com.android.internal.os.InstallerConnection.InstallerException; 235import com.android.internal.os.SomeArgs; 236import com.android.internal.os.Zygote; 237import com.android.internal.telephony.CarrierAppUtils; 238import com.android.internal.util.ArrayUtils; 239import com.android.internal.util.FastPrintWriter; 240import com.android.internal.util.FastXmlSerializer; 241import com.android.internal.util.IndentingPrintWriter; 242import com.android.internal.util.Preconditions; 243import com.android.internal.util.XmlUtils; 244import com.android.server.AttributeCache; 245import com.android.server.EventLogTags; 246import com.android.server.FgThread; 247import com.android.server.IntentResolver; 248import com.android.server.LocalServices; 249import com.android.server.ServiceThread; 250import com.android.server.SystemConfig; 251import com.android.server.Watchdog; 252import com.android.server.net.NetworkPolicyManagerInternal; 253import com.android.server.pm.PermissionsState.PermissionState; 254import com.android.server.pm.Settings.DatabaseVersion; 255import com.android.server.pm.Settings.VersionInfo; 256import com.android.server.storage.DeviceStorageMonitorInternal; 257 258import dalvik.system.CloseGuard; 259import dalvik.system.DexFile; 260import dalvik.system.VMRuntime; 261 262import libcore.io.IoUtils; 263import libcore.util.EmptyArray; 264 265import org.xmlpull.v1.XmlPullParser; 266import org.xmlpull.v1.XmlPullParserException; 267import org.xmlpull.v1.XmlSerializer; 268 269import java.io.BufferedInputStream; 270import java.io.BufferedOutputStream; 271import java.io.BufferedReader; 272import java.io.ByteArrayInputStream; 273import java.io.ByteArrayOutputStream; 274import java.io.File; 275import java.io.FileDescriptor; 276import java.io.FileInputStream; 277import java.io.FileNotFoundException; 278import java.io.FileOutputStream; 279import java.io.FileReader; 280import java.io.FilenameFilter; 281import java.io.IOException; 282import java.io.InputStream; 283import java.io.PrintWriter; 284import java.nio.charset.StandardCharsets; 285import java.security.DigestInputStream; 286import java.security.MessageDigest; 287import java.security.NoSuchAlgorithmException; 288import java.security.PublicKey; 289import java.security.cert.Certificate; 290import java.security.cert.CertificateEncodingException; 291import java.security.cert.CertificateException; 292import java.text.SimpleDateFormat; 293import java.util.ArrayList; 294import java.util.Arrays; 295import java.util.Collection; 296import java.util.Collections; 297import java.util.Comparator; 298import java.util.Date; 299import java.util.HashSet; 300import java.util.Iterator; 301import java.util.List; 302import java.util.Map; 303import java.util.Objects; 304import java.util.Set; 305import java.util.concurrent.CountDownLatch; 306import java.util.concurrent.TimeUnit; 307import java.util.concurrent.atomic.AtomicBoolean; 308import java.util.concurrent.atomic.AtomicInteger; 309import java.util.concurrent.atomic.AtomicLong; 310 311/** 312 * Keep track of all those APKs everywhere. 313 * <p> 314 * Internally there are two important locks: 315 * <ul> 316 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 317 * and other related state. It is a fine-grained lock that should only be held 318 * momentarily, as it's one of the most contended locks in the system. 319 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 320 * operations typically involve heavy lifting of application data on disk. Since 321 * {@code installd} is single-threaded, and it's operations can often be slow, 322 * this lock should never be acquired while already holding {@link #mPackages}. 323 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 324 * holding {@link #mInstallLock}. 325 * </ul> 326 * Many internal methods rely on the caller to hold the appropriate locks, and 327 * this contract is expressed through method name suffixes: 328 * <ul> 329 * <li>fooLI(): the caller must hold {@link #mInstallLock} 330 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 331 * being modified must be frozen 332 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 333 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 334 * </ul> 335 * <p> 336 * Because this class is very central to the platform's security; please run all 337 * CTS and unit tests whenever making modifications: 338 * 339 * <pre> 340 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 341 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 342 * </pre> 343 */ 344public class PackageManagerService extends IPackageManager.Stub { 345 static final String TAG = "PackageManager"; 346 static final boolean DEBUG_SETTINGS = false; 347 static final boolean DEBUG_PREFERRED = false; 348 static final boolean DEBUG_UPGRADE = false; 349 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 350 private static final boolean DEBUG_BACKUP = false; 351 private static final boolean DEBUG_INSTALL = false; 352 private static final boolean DEBUG_REMOVE = false; 353 private static final boolean DEBUG_BROADCASTS = false; 354 private static final boolean DEBUG_SHOW_INFO = false; 355 private static final boolean DEBUG_PACKAGE_INFO = false; 356 private static final boolean DEBUG_INTENT_MATCHING = false; 357 private static final boolean DEBUG_PACKAGE_SCANNING = false; 358 private static final boolean DEBUG_VERIFY = false; 359 private static final boolean DEBUG_FILTERS = false; 360 361 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 362 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 363 // user, but by default initialize to this. 364 static final boolean DEBUG_DEXOPT = false; 365 366 private static final boolean DEBUG_ABI_SELECTION = false; 367 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 368 private static final boolean DEBUG_TRIAGED_MISSING = false; 369 private static final boolean DEBUG_APP_DATA = false; 370 371 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 372 373 private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE; 374 375 private static final int RADIO_UID = Process.PHONE_UID; 376 private static final int LOG_UID = Process.LOG_UID; 377 private static final int NFC_UID = Process.NFC_UID; 378 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 379 private static final int SHELL_UID = Process.SHELL_UID; 380 381 // Cap the size of permission trees that 3rd party apps can define 382 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 383 384 // Suffix used during package installation when copying/moving 385 // package apks to install directory. 386 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 387 388 static final int SCAN_NO_DEX = 1<<1; 389 static final int SCAN_FORCE_DEX = 1<<2; 390 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 391 static final int SCAN_NEW_INSTALL = 1<<4; 392 static final int SCAN_NO_PATHS = 1<<5; 393 static final int SCAN_UPDATE_TIME = 1<<6; 394 static final int SCAN_DEFER_DEX = 1<<7; 395 static final int SCAN_BOOTING = 1<<8; 396 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 397 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 398 static final int SCAN_REPLACING = 1<<11; 399 static final int SCAN_REQUIRE_KNOWN = 1<<12; 400 static final int SCAN_MOVE = 1<<13; 401 static final int SCAN_INITIAL = 1<<14; 402 static final int SCAN_CHECK_ONLY = 1<<15; 403 static final int SCAN_DONT_KILL_APP = 1<<17; 404 static final int SCAN_IGNORE_FROZEN = 1<<18; 405 406 static final int REMOVE_CHATTY = 1<<16; 407 408 private static final int[] EMPTY_INT_ARRAY = new int[0]; 409 410 /** 411 * Timeout (in milliseconds) after which the watchdog should declare that 412 * our handler thread is wedged. The usual default for such things is one 413 * minute but we sometimes do very lengthy I/O operations on this thread, 414 * such as installing multi-gigabyte applications, so ours needs to be longer. 415 */ 416 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 417 418 /** 419 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 420 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 421 * settings entry if available, otherwise we use the hardcoded default. If it's been 422 * more than this long since the last fstrim, we force one during the boot sequence. 423 * 424 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 425 * one gets run at the next available charging+idle time. This final mandatory 426 * no-fstrim check kicks in only of the other scheduling criteria is never met. 427 */ 428 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 429 430 /** 431 * Whether verification is enabled by default. 432 */ 433 private static final boolean DEFAULT_VERIFY_ENABLE = true; 434 435 /** 436 * The default maximum time to wait for the verification agent to return in 437 * milliseconds. 438 */ 439 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 440 441 /** 442 * The default response for package verification timeout. 443 * 444 * This can be either PackageManager.VERIFICATION_ALLOW or 445 * PackageManager.VERIFICATION_REJECT. 446 */ 447 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 448 449 static final String PLATFORM_PACKAGE_NAME = "android"; 450 451 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 452 453 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 454 DEFAULT_CONTAINER_PACKAGE, 455 "com.android.defcontainer.DefaultContainerService"); 456 457 private static final String KILL_APP_REASON_GIDS_CHANGED = 458 "permission grant or revoke changed gids"; 459 460 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 461 "permissions revoked"; 462 463 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 464 465 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 466 467 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000; 468 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5; 469 470 /** Permission grant: not grant the permission. */ 471 private static final int GRANT_DENIED = 1; 472 473 /** Permission grant: grant the permission as an install permission. */ 474 private static final int GRANT_INSTALL = 2; 475 476 /** Permission grant: grant the permission as a runtime one. */ 477 private static final int GRANT_RUNTIME = 3; 478 479 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 480 private static final int GRANT_UPGRADE = 4; 481 482 /** Canonical intent used to identify what counts as a "web browser" app */ 483 private static final Intent sBrowserIntent; 484 static { 485 sBrowserIntent = new Intent(); 486 sBrowserIntent.setAction(Intent.ACTION_VIEW); 487 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 488 sBrowserIntent.setData(Uri.parse("http:")); 489 } 490 491 /** 492 * The set of all protected actions [i.e. those actions for which a high priority 493 * intent filter is disallowed]. 494 */ 495 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 496 static { 497 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 498 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 499 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 500 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 501 } 502 503 // Compilation reasons. 504 public static final int REASON_FIRST_BOOT = 0; 505 public static final int REASON_BOOT = 1; 506 public static final int REASON_INSTALL = 2; 507 public static final int REASON_BACKGROUND_DEXOPT = 3; 508 public static final int REASON_AB_OTA = 4; 509 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 510 public static final int REASON_SHARED_APK = 6; 511 public static final int REASON_FORCED_DEXOPT = 7; 512 public static final int REASON_CORE_APP = 8; 513 514 public static final int REASON_LAST = REASON_CORE_APP; 515 516 /** Special library name that skips shared libraries check during compilation. */ 517 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 518 519 final ServiceThread mHandlerThread; 520 521 final PackageHandler mHandler; 522 523 private final ProcessLoggingHandler mProcessLoggingHandler; 524 525 /** 526 * Messages for {@link #mHandler} that need to wait for system ready before 527 * being dispatched. 528 */ 529 private ArrayList<Message> mPostSystemReadyMessages; 530 531 final int mSdkVersion = Build.VERSION.SDK_INT; 532 533 final Context mContext; 534 final boolean mFactoryTest; 535 final boolean mOnlyCore; 536 final DisplayMetrics mMetrics; 537 final int mDefParseFlags; 538 final String[] mSeparateProcesses; 539 final boolean mIsUpgrade; 540 final boolean mIsPreNUpgrade; 541 542 /** The location for ASEC container files on internal storage. */ 543 final String mAsecInternalPath; 544 545 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 546 // LOCK HELD. Can be called with mInstallLock held. 547 @GuardedBy("mInstallLock") 548 final Installer mInstaller; 549 550 /** Directory where installed third-party apps stored */ 551 final File mAppInstallDir; 552 final File mEphemeralInstallDir; 553 554 /** 555 * Directory to which applications installed internally have their 556 * 32 bit native libraries copied. 557 */ 558 private File mAppLib32InstallDir; 559 560 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 561 // apps. 562 final File mDrmAppPrivateInstallDir; 563 564 // ---------------------------------------------------------------- 565 566 // Lock for state used when installing and doing other long running 567 // operations. Methods that must be called with this lock held have 568 // the suffix "LI". 569 final Object mInstallLock = new Object(); 570 571 // ---------------------------------------------------------------- 572 573 // Keys are String (package name), values are Package. This also serves 574 // as the lock for the global state. Methods that must be called with 575 // this lock held have the prefix "LP". 576 @GuardedBy("mPackages") 577 final ArrayMap<String, PackageParser.Package> mPackages = 578 new ArrayMap<String, PackageParser.Package>(); 579 580 final ArrayMap<String, Set<String>> mKnownCodebase = 581 new ArrayMap<String, Set<String>>(); 582 583 // Tracks available target package names -> overlay package paths. 584 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 585 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 586 587 /** 588 * Tracks new system packages [received in an OTA] that we expect to 589 * find updated user-installed versions. Keys are package name, values 590 * are package location. 591 */ 592 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 593 /** 594 * Tracks high priority intent filters for protected actions. During boot, certain 595 * filter actions are protected and should never be allowed to have a high priority 596 * intent filter for them. However, there is one, and only one exception -- the 597 * setup wizard. It must be able to define a high priority intent filter for these 598 * actions to ensure there are no escapes from the wizard. We need to delay processing 599 * of these during boot as we need to look at all of the system packages in order 600 * to know which component is the setup wizard. 601 */ 602 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 603 /** 604 * Whether or not processing protected filters should be deferred. 605 */ 606 private boolean mDeferProtectedFilters = true; 607 608 /** 609 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 610 */ 611 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 612 /** 613 * Whether or not system app permissions should be promoted from install to runtime. 614 */ 615 boolean mPromoteSystemApps; 616 617 @GuardedBy("mPackages") 618 final Settings mSettings; 619 620 /** 621 * Set of package names that are currently "frozen", which means active 622 * surgery is being done on the code/data for that package. The platform 623 * will refuse to launch frozen packages to avoid race conditions. 624 * 625 * @see PackageFreezer 626 */ 627 @GuardedBy("mPackages") 628 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 629 630 final ProtectedPackages mProtectedPackages; 631 632 boolean mFirstBoot; 633 634 // System configuration read by SystemConfig. 635 final int[] mGlobalGids; 636 final SparseArray<ArraySet<String>> mSystemPermissions; 637 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 638 639 // If mac_permissions.xml was found for seinfo labeling. 640 boolean mFoundPolicyFile; 641 642 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 643 644 public static final class SharedLibraryEntry { 645 public final String path; 646 public final String apk; 647 648 SharedLibraryEntry(String _path, String _apk) { 649 path = _path; 650 apk = _apk; 651 } 652 } 653 654 // Currently known shared libraries. 655 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 656 new ArrayMap<String, SharedLibraryEntry>(); 657 658 // All available activities, for your resolving pleasure. 659 final ActivityIntentResolver mActivities = 660 new ActivityIntentResolver(); 661 662 // All available receivers, for your resolving pleasure. 663 final ActivityIntentResolver mReceivers = 664 new ActivityIntentResolver(); 665 666 // All available services, for your resolving pleasure. 667 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 668 669 // All available providers, for your resolving pleasure. 670 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 671 672 // Mapping from provider base names (first directory in content URI codePath) 673 // to the provider information. 674 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 675 new ArrayMap<String, PackageParser.Provider>(); 676 677 // Mapping from instrumentation class names to info about them. 678 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 679 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 680 681 // Mapping from permission names to info about them. 682 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 683 new ArrayMap<String, PackageParser.PermissionGroup>(); 684 685 // Packages whose data we have transfered into another package, thus 686 // should no longer exist. 687 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 688 689 // Broadcast actions that are only available to the system. 690 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 691 692 /** List of packages waiting for verification. */ 693 final SparseArray<PackageVerificationState> mPendingVerification 694 = new SparseArray<PackageVerificationState>(); 695 696 /** Set of packages associated with each app op permission. */ 697 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 698 699 final PackageInstallerService mInstallerService; 700 701 private final PackageDexOptimizer mPackageDexOptimizer; 702 703 private AtomicInteger mNextMoveId = new AtomicInteger(); 704 private final MoveCallbacks mMoveCallbacks; 705 706 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 707 708 // Cache of users who need badging. 709 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 710 711 /** Token for keys in mPendingVerification. */ 712 private int mPendingVerificationToken = 0; 713 714 volatile boolean mSystemReady; 715 volatile boolean mSafeMode; 716 volatile boolean mHasSystemUidErrors; 717 718 ApplicationInfo mAndroidApplication; 719 final ActivityInfo mResolveActivity = new ActivityInfo(); 720 final ResolveInfo mResolveInfo = new ResolveInfo(); 721 ComponentName mResolveComponentName; 722 PackageParser.Package mPlatformPackage; 723 ComponentName mCustomResolverComponentName; 724 725 boolean mResolverReplaced = false; 726 727 private final @Nullable ComponentName mIntentFilterVerifierComponent; 728 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 729 730 private int mIntentFilterVerificationToken = 0; 731 732 /** Component that knows whether or not an ephemeral application exists */ 733 final ComponentName mEphemeralResolverComponent; 734 /** The service connection to the ephemeral resolver */ 735 final EphemeralResolverConnection mEphemeralResolverConnection; 736 737 /** Component used to install ephemeral applications */ 738 final ComponentName mEphemeralInstallerComponent; 739 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 740 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 741 742 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 743 = new SparseArray<IntentFilterVerificationState>(); 744 745 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 746 new DefaultPermissionGrantPolicy(this); 747 748 // List of packages names to keep cached, even if they are uninstalled for all users 749 private List<String> mKeepUninstalledPackages; 750 751 private UserManagerInternal mUserManagerInternal; 752 753 private static class IFVerificationParams { 754 PackageParser.Package pkg; 755 boolean replacing; 756 int userId; 757 int verifierUid; 758 759 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 760 int _userId, int _verifierUid) { 761 pkg = _pkg; 762 replacing = _replacing; 763 userId = _userId; 764 replacing = _replacing; 765 verifierUid = _verifierUid; 766 } 767 } 768 769 private interface IntentFilterVerifier<T extends IntentFilter> { 770 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 771 T filter, String packageName); 772 void startVerifications(int userId); 773 void receiveVerificationResponse(int verificationId); 774 } 775 776 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 777 private Context mContext; 778 private ComponentName mIntentFilterVerifierComponent; 779 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 780 781 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 782 mContext = context; 783 mIntentFilterVerifierComponent = verifierComponent; 784 } 785 786 private String getDefaultScheme() { 787 return IntentFilter.SCHEME_HTTPS; 788 } 789 790 @Override 791 public void startVerifications(int userId) { 792 // Launch verifications requests 793 int count = mCurrentIntentFilterVerifications.size(); 794 for (int n=0; n<count; n++) { 795 int verificationId = mCurrentIntentFilterVerifications.get(n); 796 final IntentFilterVerificationState ivs = 797 mIntentFilterVerificationStates.get(verificationId); 798 799 String packageName = ivs.getPackageName(); 800 801 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 802 final int filterCount = filters.size(); 803 ArraySet<String> domainsSet = new ArraySet<>(); 804 for (int m=0; m<filterCount; m++) { 805 PackageParser.ActivityIntentInfo filter = filters.get(m); 806 domainsSet.addAll(filter.getHostsList()); 807 } 808 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 809 synchronized (mPackages) { 810 if (mSettings.createIntentFilterVerificationIfNeededLPw( 811 packageName, domainsList) != null) { 812 scheduleWriteSettingsLocked(); 813 } 814 } 815 sendVerificationRequest(userId, verificationId, ivs); 816 } 817 mCurrentIntentFilterVerifications.clear(); 818 } 819 820 private void sendVerificationRequest(int userId, int verificationId, 821 IntentFilterVerificationState ivs) { 822 823 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 824 verificationIntent.putExtra( 825 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 826 verificationId); 827 verificationIntent.putExtra( 828 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 829 getDefaultScheme()); 830 verificationIntent.putExtra( 831 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 832 ivs.getHostsString()); 833 verificationIntent.putExtra( 834 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 835 ivs.getPackageName()); 836 verificationIntent.setComponent(mIntentFilterVerifierComponent); 837 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 838 839 UserHandle user = new UserHandle(userId); 840 mContext.sendBroadcastAsUser(verificationIntent, user); 841 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 842 "Sending IntentFilter verification broadcast"); 843 } 844 845 public void receiveVerificationResponse(int verificationId) { 846 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 847 848 final boolean verified = ivs.isVerified(); 849 850 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 851 final int count = filters.size(); 852 if (DEBUG_DOMAIN_VERIFICATION) { 853 Slog.i(TAG, "Received verification response " + verificationId 854 + " for " + count + " filters, verified=" + verified); 855 } 856 for (int n=0; n<count; n++) { 857 PackageParser.ActivityIntentInfo filter = filters.get(n); 858 filter.setVerified(verified); 859 860 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 861 + " verified with result:" + verified + " and hosts:" 862 + ivs.getHostsString()); 863 } 864 865 mIntentFilterVerificationStates.remove(verificationId); 866 867 final String packageName = ivs.getPackageName(); 868 IntentFilterVerificationInfo ivi = null; 869 870 synchronized (mPackages) { 871 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 872 } 873 if (ivi == null) { 874 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 875 + verificationId + " packageName:" + packageName); 876 return; 877 } 878 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 879 "Updating IntentFilterVerificationInfo for package " + packageName 880 +" verificationId:" + verificationId); 881 882 synchronized (mPackages) { 883 if (verified) { 884 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 885 } else { 886 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 887 } 888 scheduleWriteSettingsLocked(); 889 890 final int userId = ivs.getUserId(); 891 if (userId != UserHandle.USER_ALL) { 892 final int userStatus = 893 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 894 895 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 896 boolean needUpdate = false; 897 898 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 899 // already been set by the User thru the Disambiguation dialog 900 switch (userStatus) { 901 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 902 if (verified) { 903 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 904 } else { 905 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 906 } 907 needUpdate = true; 908 break; 909 910 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 911 if (verified) { 912 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 913 needUpdate = true; 914 } 915 break; 916 917 default: 918 // Nothing to do 919 } 920 921 if (needUpdate) { 922 mSettings.updateIntentFilterVerificationStatusLPw( 923 packageName, updatedStatus, userId); 924 scheduleWritePackageRestrictionsLocked(userId); 925 } 926 } 927 } 928 } 929 930 @Override 931 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 932 ActivityIntentInfo filter, String packageName) { 933 if (!hasValidDomains(filter)) { 934 return false; 935 } 936 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 937 if (ivs == null) { 938 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 939 packageName); 940 } 941 if (DEBUG_DOMAIN_VERIFICATION) { 942 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 943 } 944 ivs.addFilter(filter); 945 return true; 946 } 947 948 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 949 int userId, int verificationId, String packageName) { 950 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 951 verifierUid, userId, packageName); 952 ivs.setPendingState(); 953 synchronized (mPackages) { 954 mIntentFilterVerificationStates.append(verificationId, ivs); 955 mCurrentIntentFilterVerifications.add(verificationId); 956 } 957 return ivs; 958 } 959 } 960 961 private static boolean hasValidDomains(ActivityIntentInfo filter) { 962 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 963 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 964 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 965 } 966 967 // Set of pending broadcasts for aggregating enable/disable of components. 968 static class PendingPackageBroadcasts { 969 // for each user id, a map of <package name -> components within that package> 970 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 971 972 public PendingPackageBroadcasts() { 973 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 974 } 975 976 public ArrayList<String> get(int userId, String packageName) { 977 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 978 return packages.get(packageName); 979 } 980 981 public void put(int userId, String packageName, ArrayList<String> components) { 982 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 983 packages.put(packageName, components); 984 } 985 986 public void remove(int userId, String packageName) { 987 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 988 if (packages != null) { 989 packages.remove(packageName); 990 } 991 } 992 993 public void remove(int userId) { 994 mUidMap.remove(userId); 995 } 996 997 public int userIdCount() { 998 return mUidMap.size(); 999 } 1000 1001 public int userIdAt(int n) { 1002 return mUidMap.keyAt(n); 1003 } 1004 1005 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1006 return mUidMap.get(userId); 1007 } 1008 1009 public int size() { 1010 // total number of pending broadcast entries across all userIds 1011 int num = 0; 1012 for (int i = 0; i< mUidMap.size(); i++) { 1013 num += mUidMap.valueAt(i).size(); 1014 } 1015 return num; 1016 } 1017 1018 public void clear() { 1019 mUidMap.clear(); 1020 } 1021 1022 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1023 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1024 if (map == null) { 1025 map = new ArrayMap<String, ArrayList<String>>(); 1026 mUidMap.put(userId, map); 1027 } 1028 return map; 1029 } 1030 } 1031 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1032 1033 // Service Connection to remote media container service to copy 1034 // package uri's from external media onto secure containers 1035 // or internal storage. 1036 private IMediaContainerService mContainerService = null; 1037 1038 static final int SEND_PENDING_BROADCAST = 1; 1039 static final int MCS_BOUND = 3; 1040 static final int END_COPY = 4; 1041 static final int INIT_COPY = 5; 1042 static final int MCS_UNBIND = 6; 1043 static final int START_CLEANING_PACKAGE = 7; 1044 static final int FIND_INSTALL_LOC = 8; 1045 static final int POST_INSTALL = 9; 1046 static final int MCS_RECONNECT = 10; 1047 static final int MCS_GIVE_UP = 11; 1048 static final int UPDATED_MEDIA_STATUS = 12; 1049 static final int WRITE_SETTINGS = 13; 1050 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1051 static final int PACKAGE_VERIFIED = 15; 1052 static final int CHECK_PENDING_VERIFICATION = 16; 1053 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1054 static final int INTENT_FILTER_VERIFIED = 18; 1055 static final int WRITE_PACKAGE_LIST = 19; 1056 1057 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1058 1059 // Delay time in millisecs 1060 static final int BROADCAST_DELAY = 10 * 1000; 1061 1062 static UserManagerService sUserManager; 1063 1064 // Stores a list of users whose package restrictions file needs to be updated 1065 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1066 1067 final private DefaultContainerConnection mDefContainerConn = 1068 new DefaultContainerConnection(); 1069 class DefaultContainerConnection implements ServiceConnection { 1070 public void onServiceConnected(ComponentName name, IBinder service) { 1071 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1072 IMediaContainerService imcs = 1073 IMediaContainerService.Stub.asInterface(service); 1074 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1075 } 1076 1077 public void onServiceDisconnected(ComponentName name) { 1078 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1079 } 1080 } 1081 1082 // Recordkeeping of restore-after-install operations that are currently in flight 1083 // between the Package Manager and the Backup Manager 1084 static class PostInstallData { 1085 public InstallArgs args; 1086 public PackageInstalledInfo res; 1087 1088 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1089 args = _a; 1090 res = _r; 1091 } 1092 } 1093 1094 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1095 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1096 1097 // XML tags for backup/restore of various bits of state 1098 private static final String TAG_PREFERRED_BACKUP = "pa"; 1099 private static final String TAG_DEFAULT_APPS = "da"; 1100 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1101 1102 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1103 private static final String TAG_ALL_GRANTS = "rt-grants"; 1104 private static final String TAG_GRANT = "grant"; 1105 private static final String ATTR_PACKAGE_NAME = "pkg"; 1106 1107 private static final String TAG_PERMISSION = "perm"; 1108 private static final String ATTR_PERMISSION_NAME = "name"; 1109 private static final String ATTR_IS_GRANTED = "g"; 1110 private static final String ATTR_USER_SET = "set"; 1111 private static final String ATTR_USER_FIXED = "fixed"; 1112 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1113 1114 // System/policy permission grants are not backed up 1115 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1116 FLAG_PERMISSION_POLICY_FIXED 1117 | FLAG_PERMISSION_SYSTEM_FIXED 1118 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1119 1120 // And we back up these user-adjusted states 1121 private static final int USER_RUNTIME_GRANT_MASK = 1122 FLAG_PERMISSION_USER_SET 1123 | FLAG_PERMISSION_USER_FIXED 1124 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1125 1126 final @Nullable String mRequiredVerifierPackage; 1127 final @NonNull String mRequiredInstallerPackage; 1128 final @Nullable String mSetupWizardPackage; 1129 final @NonNull String mServicesSystemSharedLibraryPackageName; 1130 final @NonNull String mSharedSystemSharedLibraryPackageName; 1131 1132 private final PackageUsage mPackageUsage = new PackageUsage(); 1133 1134 private class PackageUsage { 1135 private static final int WRITE_INTERVAL 1136 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1137 1138 private final Object mFileLock = new Object(); 1139 private final AtomicLong mLastWritten = new AtomicLong(0); 1140 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1141 1142 private boolean mIsHistoricalPackageUsageAvailable = true; 1143 1144 boolean isHistoricalPackageUsageAvailable() { 1145 return mIsHistoricalPackageUsageAvailable; 1146 } 1147 1148 void write(boolean force) { 1149 if (force) { 1150 writeInternal(); 1151 return; 1152 } 1153 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1154 && !DEBUG_DEXOPT) { 1155 return; 1156 } 1157 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1158 new Thread("PackageUsage_DiskWriter") { 1159 @Override 1160 public void run() { 1161 try { 1162 writeInternal(); 1163 } finally { 1164 mBackgroundWriteRunning.set(false); 1165 } 1166 } 1167 }.start(); 1168 } 1169 } 1170 1171 private void writeInternal() { 1172 synchronized (mPackages) { 1173 synchronized (mFileLock) { 1174 AtomicFile file = getFile(); 1175 FileOutputStream f = null; 1176 try { 1177 f = file.startWrite(); 1178 BufferedOutputStream out = new BufferedOutputStream(f); 1179 FileUtils.setPermissions(file.getBaseFile().getPath(), 1180 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1181 StringBuilder sb = new StringBuilder(); 1182 1183 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1184 sb.append('\n'); 1185 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1186 1187 for (PackageParser.Package pkg : mPackages.values()) { 1188 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1189 continue; 1190 } 1191 sb.setLength(0); 1192 sb.append(pkg.packageName); 1193 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1194 sb.append(' '); 1195 sb.append(usageTimeInMillis); 1196 } 1197 sb.append('\n'); 1198 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1199 } 1200 out.flush(); 1201 file.finishWrite(f); 1202 } catch (IOException e) { 1203 if (f != null) { 1204 file.failWrite(f); 1205 } 1206 Log.e(TAG, "Failed to write package usage times", e); 1207 } 1208 } 1209 } 1210 mLastWritten.set(SystemClock.elapsedRealtime()); 1211 } 1212 1213 void readLP() { 1214 synchronized (mFileLock) { 1215 AtomicFile file = getFile(); 1216 BufferedInputStream in = null; 1217 try { 1218 in = new BufferedInputStream(file.openRead()); 1219 StringBuffer sb = new StringBuffer(); 1220 1221 String firstLine = readLine(in, sb); 1222 if (firstLine == null) { 1223 // Empty file. Do nothing. 1224 } else if (USAGE_FILE_MAGIC_VERSION_1.equals(firstLine)) { 1225 readVersion1LP(in, sb); 1226 } else { 1227 readVersion0LP(in, sb, firstLine); 1228 } 1229 } catch (FileNotFoundException expected) { 1230 mIsHistoricalPackageUsageAvailable = false; 1231 } catch (IOException e) { 1232 Log.w(TAG, "Failed to read package usage times", e); 1233 } finally { 1234 IoUtils.closeQuietly(in); 1235 } 1236 } 1237 mLastWritten.set(SystemClock.elapsedRealtime()); 1238 } 1239 1240 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1241 throws IOException { 1242 // Initial version of the file had no version number and stored one 1243 // package-timestamp pair per line. 1244 // Note that the first line has already been read from the InputStream. 1245 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1246 String[] tokens = line.split(" "); 1247 if (tokens.length != 2) { 1248 throw new IOException("Failed to parse " + line + 1249 " as package-timestamp pair."); 1250 } 1251 1252 String packageName = tokens[0]; 1253 PackageParser.Package pkg = mPackages.get(packageName); 1254 if (pkg == null) { 1255 continue; 1256 } 1257 1258 long timestamp = parseAsLong(tokens[1]); 1259 for (int reason = 0; 1260 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1261 reason++) { 1262 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1263 } 1264 } 1265 } 1266 1267 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1268 // Version 1 of the file started with the corresponding version 1269 // number and then stored a package name and eight timestamps per line. 1270 String line; 1271 while ((line = readLine(in, sb)) != null) { 1272 String[] tokens = line.split(" "); 1273 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1274 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1275 } 1276 1277 String packageName = tokens[0]; 1278 PackageParser.Package pkg = mPackages.get(packageName); 1279 if (pkg == null) { 1280 continue; 1281 } 1282 1283 for (int reason = 0; 1284 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1285 reason++) { 1286 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1287 } 1288 } 1289 } 1290 1291 private long parseAsLong(String token) throws IOException { 1292 try { 1293 return Long.parseLong(token); 1294 } catch (NumberFormatException e) { 1295 throw new IOException("Failed to parse " + token + " as a long.", e); 1296 } 1297 } 1298 1299 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1300 return readToken(in, sb, '\n'); 1301 } 1302 1303 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1304 throws IOException { 1305 sb.setLength(0); 1306 while (true) { 1307 int ch = in.read(); 1308 if (ch == -1) { 1309 if (sb.length() == 0) { 1310 return null; 1311 } 1312 throw new IOException("Unexpected EOF"); 1313 } 1314 if (ch == endOfToken) { 1315 return sb.toString(); 1316 } 1317 sb.append((char)ch); 1318 } 1319 } 1320 1321 private AtomicFile getFile() { 1322 File dataDir = Environment.getDataDirectory(); 1323 File systemDir = new File(dataDir, "system"); 1324 File fname = new File(systemDir, "package-usage.list"); 1325 return new AtomicFile(fname); 1326 } 1327 1328 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1329 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1330 } 1331 1332 class PackageHandler extends Handler { 1333 private boolean mBound = false; 1334 final ArrayList<HandlerParams> mPendingInstalls = 1335 new ArrayList<HandlerParams>(); 1336 1337 private boolean connectToService() { 1338 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1339 " DefaultContainerService"); 1340 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1341 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1342 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1343 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1344 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1345 mBound = true; 1346 return true; 1347 } 1348 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1349 return false; 1350 } 1351 1352 private void disconnectService() { 1353 mContainerService = null; 1354 mBound = false; 1355 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1356 mContext.unbindService(mDefContainerConn); 1357 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1358 } 1359 1360 PackageHandler(Looper looper) { 1361 super(looper); 1362 } 1363 1364 public void handleMessage(Message msg) { 1365 try { 1366 doHandleMessage(msg); 1367 } finally { 1368 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1369 } 1370 } 1371 1372 void doHandleMessage(Message msg) { 1373 switch (msg.what) { 1374 case INIT_COPY: { 1375 HandlerParams params = (HandlerParams) msg.obj; 1376 int idx = mPendingInstalls.size(); 1377 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1378 // If a bind was already initiated we dont really 1379 // need to do anything. The pending install 1380 // will be processed later on. 1381 if (!mBound) { 1382 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1383 System.identityHashCode(mHandler)); 1384 // If this is the only one pending we might 1385 // have to bind to the service again. 1386 if (!connectToService()) { 1387 Slog.e(TAG, "Failed to bind to media container service"); 1388 params.serviceError(); 1389 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1390 System.identityHashCode(mHandler)); 1391 if (params.traceMethod != null) { 1392 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1393 params.traceCookie); 1394 } 1395 return; 1396 } else { 1397 // Once we bind to the service, the first 1398 // pending request will be processed. 1399 mPendingInstalls.add(idx, params); 1400 } 1401 } else { 1402 mPendingInstalls.add(idx, params); 1403 // Already bound to the service. Just make 1404 // sure we trigger off processing the first request. 1405 if (idx == 0) { 1406 mHandler.sendEmptyMessage(MCS_BOUND); 1407 } 1408 } 1409 break; 1410 } 1411 case MCS_BOUND: { 1412 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1413 if (msg.obj != null) { 1414 mContainerService = (IMediaContainerService) msg.obj; 1415 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1416 System.identityHashCode(mHandler)); 1417 } 1418 if (mContainerService == null) { 1419 if (!mBound) { 1420 // Something seriously wrong since we are not bound and we are not 1421 // waiting for connection. Bail out. 1422 Slog.e(TAG, "Cannot bind to media container service"); 1423 for (HandlerParams params : mPendingInstalls) { 1424 // Indicate service bind error 1425 params.serviceError(); 1426 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1427 System.identityHashCode(params)); 1428 if (params.traceMethod != null) { 1429 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1430 params.traceMethod, params.traceCookie); 1431 } 1432 return; 1433 } 1434 mPendingInstalls.clear(); 1435 } else { 1436 Slog.w(TAG, "Waiting to connect to media container service"); 1437 } 1438 } else if (mPendingInstalls.size() > 0) { 1439 HandlerParams params = mPendingInstalls.get(0); 1440 if (params != null) { 1441 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1442 System.identityHashCode(params)); 1443 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1444 if (params.startCopy()) { 1445 // We are done... look for more work or to 1446 // go idle. 1447 if (DEBUG_SD_INSTALL) Log.i(TAG, 1448 "Checking for more work or unbind..."); 1449 // Delete pending install 1450 if (mPendingInstalls.size() > 0) { 1451 mPendingInstalls.remove(0); 1452 } 1453 if (mPendingInstalls.size() == 0) { 1454 if (mBound) { 1455 if (DEBUG_SD_INSTALL) Log.i(TAG, 1456 "Posting delayed MCS_UNBIND"); 1457 removeMessages(MCS_UNBIND); 1458 Message ubmsg = obtainMessage(MCS_UNBIND); 1459 // Unbind after a little delay, to avoid 1460 // continual thrashing. 1461 sendMessageDelayed(ubmsg, 10000); 1462 } 1463 } else { 1464 // There are more pending requests in queue. 1465 // Just post MCS_BOUND message to trigger processing 1466 // of next pending install. 1467 if (DEBUG_SD_INSTALL) Log.i(TAG, 1468 "Posting MCS_BOUND for next work"); 1469 mHandler.sendEmptyMessage(MCS_BOUND); 1470 } 1471 } 1472 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1473 } 1474 } else { 1475 // Should never happen ideally. 1476 Slog.w(TAG, "Empty queue"); 1477 } 1478 break; 1479 } 1480 case MCS_RECONNECT: { 1481 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1482 if (mPendingInstalls.size() > 0) { 1483 if (mBound) { 1484 disconnectService(); 1485 } 1486 if (!connectToService()) { 1487 Slog.e(TAG, "Failed to bind to media container service"); 1488 for (HandlerParams params : mPendingInstalls) { 1489 // Indicate service bind error 1490 params.serviceError(); 1491 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1492 System.identityHashCode(params)); 1493 } 1494 mPendingInstalls.clear(); 1495 } 1496 } 1497 break; 1498 } 1499 case MCS_UNBIND: { 1500 // If there is no actual work left, then time to unbind. 1501 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1502 1503 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1504 if (mBound) { 1505 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1506 1507 disconnectService(); 1508 } 1509 } else if (mPendingInstalls.size() > 0) { 1510 // There are more pending requests in queue. 1511 // Just post MCS_BOUND message to trigger processing 1512 // of next pending install. 1513 mHandler.sendEmptyMessage(MCS_BOUND); 1514 } 1515 1516 break; 1517 } 1518 case MCS_GIVE_UP: { 1519 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1520 HandlerParams params = mPendingInstalls.remove(0); 1521 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1522 System.identityHashCode(params)); 1523 break; 1524 } 1525 case SEND_PENDING_BROADCAST: { 1526 String packages[]; 1527 ArrayList<String> components[]; 1528 int size = 0; 1529 int uids[]; 1530 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1531 synchronized (mPackages) { 1532 if (mPendingBroadcasts == null) { 1533 return; 1534 } 1535 size = mPendingBroadcasts.size(); 1536 if (size <= 0) { 1537 // Nothing to be done. Just return 1538 return; 1539 } 1540 packages = new String[size]; 1541 components = new ArrayList[size]; 1542 uids = new int[size]; 1543 int i = 0; // filling out the above arrays 1544 1545 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1546 int packageUserId = mPendingBroadcasts.userIdAt(n); 1547 Iterator<Map.Entry<String, ArrayList<String>>> it 1548 = mPendingBroadcasts.packagesForUserId(packageUserId) 1549 .entrySet().iterator(); 1550 while (it.hasNext() && i < size) { 1551 Map.Entry<String, ArrayList<String>> ent = it.next(); 1552 packages[i] = ent.getKey(); 1553 components[i] = ent.getValue(); 1554 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1555 uids[i] = (ps != null) 1556 ? UserHandle.getUid(packageUserId, ps.appId) 1557 : -1; 1558 i++; 1559 } 1560 } 1561 size = i; 1562 mPendingBroadcasts.clear(); 1563 } 1564 // Send broadcasts 1565 for (int i = 0; i < size; i++) { 1566 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1567 } 1568 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1569 break; 1570 } 1571 case START_CLEANING_PACKAGE: { 1572 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1573 final String packageName = (String)msg.obj; 1574 final int userId = msg.arg1; 1575 final boolean andCode = msg.arg2 != 0; 1576 synchronized (mPackages) { 1577 if (userId == UserHandle.USER_ALL) { 1578 int[] users = sUserManager.getUserIds(); 1579 for (int user : users) { 1580 mSettings.addPackageToCleanLPw( 1581 new PackageCleanItem(user, packageName, andCode)); 1582 } 1583 } else { 1584 mSettings.addPackageToCleanLPw( 1585 new PackageCleanItem(userId, packageName, andCode)); 1586 } 1587 } 1588 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1589 startCleaningPackages(); 1590 } break; 1591 case POST_INSTALL: { 1592 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1593 1594 PostInstallData data = mRunningInstalls.get(msg.arg1); 1595 final boolean didRestore = (msg.arg2 != 0); 1596 mRunningInstalls.delete(msg.arg1); 1597 1598 if (data != null) { 1599 InstallArgs args = data.args; 1600 PackageInstalledInfo parentRes = data.res; 1601 1602 final boolean grantPermissions = (args.installFlags 1603 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1604 final boolean killApp = (args.installFlags 1605 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1606 final String[] grantedPermissions = args.installGrantPermissions; 1607 1608 // Handle the parent package 1609 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1610 grantedPermissions, didRestore, args.installerPackageName, 1611 args.observer); 1612 1613 // Handle the child packages 1614 final int childCount = (parentRes.addedChildPackages != null) 1615 ? parentRes.addedChildPackages.size() : 0; 1616 for (int i = 0; i < childCount; i++) { 1617 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1618 handlePackagePostInstall(childRes, grantPermissions, killApp, 1619 grantedPermissions, false, args.installerPackageName, 1620 args.observer); 1621 } 1622 1623 // Log tracing if needed 1624 if (args.traceMethod != null) { 1625 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1626 args.traceCookie); 1627 } 1628 } else { 1629 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1630 } 1631 1632 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1633 } break; 1634 case UPDATED_MEDIA_STATUS: { 1635 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1636 boolean reportStatus = msg.arg1 == 1; 1637 boolean doGc = msg.arg2 == 1; 1638 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1639 if (doGc) { 1640 // Force a gc to clear up stale containers. 1641 Runtime.getRuntime().gc(); 1642 } 1643 if (msg.obj != null) { 1644 @SuppressWarnings("unchecked") 1645 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1646 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1647 // Unload containers 1648 unloadAllContainers(args); 1649 } 1650 if (reportStatus) { 1651 try { 1652 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1653 PackageHelper.getMountService().finishMediaUpdate(); 1654 } catch (RemoteException e) { 1655 Log.e(TAG, "MountService not running?"); 1656 } 1657 } 1658 } break; 1659 case WRITE_SETTINGS: { 1660 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1661 synchronized (mPackages) { 1662 removeMessages(WRITE_SETTINGS); 1663 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1664 mSettings.writeLPr(); 1665 mDirtyUsers.clear(); 1666 } 1667 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1668 } break; 1669 case WRITE_PACKAGE_RESTRICTIONS: { 1670 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1671 synchronized (mPackages) { 1672 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1673 for (int userId : mDirtyUsers) { 1674 mSettings.writePackageRestrictionsLPr(userId); 1675 } 1676 mDirtyUsers.clear(); 1677 } 1678 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1679 } break; 1680 case WRITE_PACKAGE_LIST: { 1681 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1682 synchronized (mPackages) { 1683 removeMessages(WRITE_PACKAGE_LIST); 1684 mSettings.writePackageListLPr(msg.arg1); 1685 } 1686 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1687 } break; 1688 case CHECK_PENDING_VERIFICATION: { 1689 final int verificationId = msg.arg1; 1690 final PackageVerificationState state = mPendingVerification.get(verificationId); 1691 1692 if ((state != null) && !state.timeoutExtended()) { 1693 final InstallArgs args = state.getInstallArgs(); 1694 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1695 1696 Slog.i(TAG, "Verification timed out for " + originUri); 1697 mPendingVerification.remove(verificationId); 1698 1699 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1700 1701 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1702 Slog.i(TAG, "Continuing with installation of " + originUri); 1703 state.setVerifierResponse(Binder.getCallingUid(), 1704 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1705 broadcastPackageVerified(verificationId, originUri, 1706 PackageManager.VERIFICATION_ALLOW, 1707 state.getInstallArgs().getUser()); 1708 try { 1709 ret = args.copyApk(mContainerService, true); 1710 } catch (RemoteException e) { 1711 Slog.e(TAG, "Could not contact the ContainerService"); 1712 } 1713 } else { 1714 broadcastPackageVerified(verificationId, originUri, 1715 PackageManager.VERIFICATION_REJECT, 1716 state.getInstallArgs().getUser()); 1717 } 1718 1719 Trace.asyncTraceEnd( 1720 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1721 1722 processPendingInstall(args, ret); 1723 mHandler.sendEmptyMessage(MCS_UNBIND); 1724 } 1725 break; 1726 } 1727 case PACKAGE_VERIFIED: { 1728 final int verificationId = msg.arg1; 1729 1730 final PackageVerificationState state = mPendingVerification.get(verificationId); 1731 if (state == null) { 1732 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1733 break; 1734 } 1735 1736 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1737 1738 state.setVerifierResponse(response.callerUid, response.code); 1739 1740 if (state.isVerificationComplete()) { 1741 mPendingVerification.remove(verificationId); 1742 1743 final InstallArgs args = state.getInstallArgs(); 1744 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1745 1746 int ret; 1747 if (state.isInstallAllowed()) { 1748 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1749 broadcastPackageVerified(verificationId, originUri, 1750 response.code, state.getInstallArgs().getUser()); 1751 try { 1752 ret = args.copyApk(mContainerService, true); 1753 } catch (RemoteException e) { 1754 Slog.e(TAG, "Could not contact the ContainerService"); 1755 } 1756 } else { 1757 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1758 } 1759 1760 Trace.asyncTraceEnd( 1761 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1762 1763 processPendingInstall(args, ret); 1764 mHandler.sendEmptyMessage(MCS_UNBIND); 1765 } 1766 1767 break; 1768 } 1769 case START_INTENT_FILTER_VERIFICATIONS: { 1770 IFVerificationParams params = (IFVerificationParams) msg.obj; 1771 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1772 params.replacing, params.pkg); 1773 break; 1774 } 1775 case INTENT_FILTER_VERIFIED: { 1776 final int verificationId = msg.arg1; 1777 1778 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1779 verificationId); 1780 if (state == null) { 1781 Slog.w(TAG, "Invalid IntentFilter verification token " 1782 + verificationId + " received"); 1783 break; 1784 } 1785 1786 final int userId = state.getUserId(); 1787 1788 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1789 "Processing IntentFilter verification with token:" 1790 + verificationId + " and userId:" + userId); 1791 1792 final IntentFilterVerificationResponse response = 1793 (IntentFilterVerificationResponse) msg.obj; 1794 1795 state.setVerifierResponse(response.callerUid, response.code); 1796 1797 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1798 "IntentFilter verification with token:" + verificationId 1799 + " and userId:" + userId 1800 + " is settings verifier response with response code:" 1801 + response.code); 1802 1803 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1804 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1805 + response.getFailedDomainsString()); 1806 } 1807 1808 if (state.isVerificationComplete()) { 1809 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1810 } else { 1811 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1812 "IntentFilter verification with token:" + verificationId 1813 + " was not said to be complete"); 1814 } 1815 1816 break; 1817 } 1818 } 1819 } 1820 } 1821 1822 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1823 boolean killApp, String[] grantedPermissions, 1824 boolean launchedForRestore, String installerPackage, 1825 IPackageInstallObserver2 installObserver) { 1826 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1827 // Send the removed broadcasts 1828 if (res.removedInfo != null) { 1829 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1830 } 1831 1832 // Now that we successfully installed the package, grant runtime 1833 // permissions if requested before broadcasting the install. 1834 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1835 >= Build.VERSION_CODES.M) { 1836 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1837 } 1838 1839 final boolean update = res.removedInfo != null 1840 && res.removedInfo.removedPackage != null; 1841 1842 // If this is the first time we have child packages for a disabled privileged 1843 // app that had no children, we grant requested runtime permissions to the new 1844 // children if the parent on the system image had them already granted. 1845 if (res.pkg.parentPackage != null) { 1846 synchronized (mPackages) { 1847 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1848 } 1849 } 1850 1851 synchronized (mPackages) { 1852 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1853 } 1854 1855 final String packageName = res.pkg.applicationInfo.packageName; 1856 Bundle extras = new Bundle(1); 1857 extras.putInt(Intent.EXTRA_UID, res.uid); 1858 1859 // Determine the set of users who are adding this package for 1860 // the first time vs. those who are seeing an update. 1861 int[] firstUsers = EMPTY_INT_ARRAY; 1862 int[] updateUsers = EMPTY_INT_ARRAY; 1863 if (res.origUsers == null || res.origUsers.length == 0) { 1864 firstUsers = res.newUsers; 1865 } else { 1866 for (int newUser : res.newUsers) { 1867 boolean isNew = true; 1868 for (int origUser : res.origUsers) { 1869 if (origUser == newUser) { 1870 isNew = false; 1871 break; 1872 } 1873 } 1874 if (isNew) { 1875 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1876 } else { 1877 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1878 } 1879 } 1880 } 1881 1882 // Send installed broadcasts if the install/update is not ephemeral 1883 if (!isEphemeral(res.pkg)) { 1884 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1885 1886 // Send added for users that see the package for the first time 1887 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1888 extras, 0 /*flags*/, null /*targetPackage*/, 1889 null /*finishedReceiver*/, firstUsers); 1890 1891 // Send added for users that don't see the package for the first time 1892 if (update) { 1893 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1894 } 1895 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1896 extras, 0 /*flags*/, null /*targetPackage*/, 1897 null /*finishedReceiver*/, updateUsers); 1898 1899 // Send replaced for users that don't see the package for the first time 1900 if (update) { 1901 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1902 packageName, extras, 0 /*flags*/, 1903 null /*targetPackage*/, null /*finishedReceiver*/, 1904 updateUsers); 1905 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1906 null /*package*/, null /*extras*/, 0 /*flags*/, 1907 packageName /*targetPackage*/, 1908 null /*finishedReceiver*/, updateUsers); 1909 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1910 // First-install and we did a restore, so we're responsible for the 1911 // first-launch broadcast. 1912 if (DEBUG_BACKUP) { 1913 Slog.i(TAG, "Post-restore of " + packageName 1914 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1915 } 1916 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1917 } 1918 1919 // Send broadcast package appeared if forward locked/external for all users 1920 // treat asec-hosted packages like removable media on upgrade 1921 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1922 if (DEBUG_INSTALL) { 1923 Slog.i(TAG, "upgrading pkg " + res.pkg 1924 + " is ASEC-hosted -> AVAILABLE"); 1925 } 1926 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1927 ArrayList<String> pkgList = new ArrayList<>(1); 1928 pkgList.add(packageName); 1929 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1930 } 1931 } 1932 1933 // Work that needs to happen on first install within each user 1934 if (firstUsers != null && firstUsers.length > 0) { 1935 synchronized (mPackages) { 1936 for (int userId : firstUsers) { 1937 // If this app is a browser and it's newly-installed for some 1938 // users, clear any default-browser state in those users. The 1939 // app's nature doesn't depend on the user, so we can just check 1940 // its browser nature in any user and generalize. 1941 if (packageIsBrowser(packageName, userId)) { 1942 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1943 } 1944 1945 // We may also need to apply pending (restored) runtime 1946 // permission grants within these users. 1947 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1948 } 1949 } 1950 } 1951 1952 // Log current value of "unknown sources" setting 1953 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1954 getUnknownSourcesSettings()); 1955 1956 // Force a gc to clear up things 1957 Runtime.getRuntime().gc(); 1958 1959 // Remove the replaced package's older resources safely now 1960 // We delete after a gc for applications on sdcard. 1961 if (res.removedInfo != null && res.removedInfo.args != null) { 1962 synchronized (mInstallLock) { 1963 res.removedInfo.args.doPostDeleteLI(true); 1964 } 1965 } 1966 } 1967 1968 // If someone is watching installs - notify them 1969 if (installObserver != null) { 1970 try { 1971 Bundle extras = extrasForInstallResult(res); 1972 installObserver.onPackageInstalled(res.name, res.returnCode, 1973 res.returnMsg, extras); 1974 } catch (RemoteException e) { 1975 Slog.i(TAG, "Observer no longer exists."); 1976 } 1977 } 1978 } 1979 1980 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1981 PackageParser.Package pkg) { 1982 if (pkg.parentPackage == null) { 1983 return; 1984 } 1985 if (pkg.requestedPermissions == null) { 1986 return; 1987 } 1988 final PackageSetting disabledSysParentPs = mSettings 1989 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1990 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1991 || !disabledSysParentPs.isPrivileged() 1992 || (disabledSysParentPs.childPackageNames != null 1993 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1994 return; 1995 } 1996 final int[] allUserIds = sUserManager.getUserIds(); 1997 final int permCount = pkg.requestedPermissions.size(); 1998 for (int i = 0; i < permCount; i++) { 1999 String permission = pkg.requestedPermissions.get(i); 2000 BasePermission bp = mSettings.mPermissions.get(permission); 2001 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 2002 continue; 2003 } 2004 for (int userId : allUserIds) { 2005 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 2006 permission, userId)) { 2007 grantRuntimePermission(pkg.packageName, permission, userId); 2008 } 2009 } 2010 } 2011 } 2012 2013 private StorageEventListener mStorageListener = new StorageEventListener() { 2014 @Override 2015 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2016 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2017 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2018 final String volumeUuid = vol.getFsUuid(); 2019 2020 // Clean up any users or apps that were removed or recreated 2021 // while this volume was missing 2022 reconcileUsers(volumeUuid); 2023 reconcileApps(volumeUuid); 2024 2025 // Clean up any install sessions that expired or were 2026 // cancelled while this volume was missing 2027 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2028 2029 loadPrivatePackages(vol); 2030 2031 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2032 unloadPrivatePackages(vol); 2033 } 2034 } 2035 2036 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2037 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2038 updateExternalMediaStatus(true, false); 2039 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2040 updateExternalMediaStatus(false, false); 2041 } 2042 } 2043 } 2044 2045 @Override 2046 public void onVolumeForgotten(String fsUuid) { 2047 if (TextUtils.isEmpty(fsUuid)) { 2048 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2049 return; 2050 } 2051 2052 // Remove any apps installed on the forgotten volume 2053 synchronized (mPackages) { 2054 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2055 for (PackageSetting ps : packages) { 2056 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2057 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2058 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2059 } 2060 2061 mSettings.onVolumeForgotten(fsUuid); 2062 mSettings.writeLPr(); 2063 } 2064 } 2065 }; 2066 2067 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2068 String[] grantedPermissions) { 2069 for (int userId : userIds) { 2070 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2071 } 2072 2073 // We could have touched GID membership, so flush out packages.list 2074 synchronized (mPackages) { 2075 mSettings.writePackageListLPr(); 2076 } 2077 } 2078 2079 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2080 String[] grantedPermissions) { 2081 SettingBase sb = (SettingBase) pkg.mExtras; 2082 if (sb == null) { 2083 return; 2084 } 2085 2086 PermissionsState permissionsState = sb.getPermissionsState(); 2087 2088 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2089 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2090 2091 for (String permission : pkg.requestedPermissions) { 2092 final BasePermission bp; 2093 synchronized (mPackages) { 2094 bp = mSettings.mPermissions.get(permission); 2095 } 2096 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2097 && (grantedPermissions == null 2098 || ArrayUtils.contains(grantedPermissions, permission))) { 2099 final int flags = permissionsState.getPermissionFlags(permission, userId); 2100 // Installer cannot change immutable permissions. 2101 if ((flags & immutableFlags) == 0) { 2102 grantRuntimePermission(pkg.packageName, permission, userId); 2103 } 2104 } 2105 } 2106 } 2107 2108 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2109 Bundle extras = null; 2110 switch (res.returnCode) { 2111 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2112 extras = new Bundle(); 2113 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2114 res.origPermission); 2115 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2116 res.origPackage); 2117 break; 2118 } 2119 case PackageManager.INSTALL_SUCCEEDED: { 2120 extras = new Bundle(); 2121 extras.putBoolean(Intent.EXTRA_REPLACING, 2122 res.removedInfo != null && res.removedInfo.removedPackage != null); 2123 break; 2124 } 2125 } 2126 return extras; 2127 } 2128 2129 void scheduleWriteSettingsLocked() { 2130 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2131 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2132 } 2133 } 2134 2135 void scheduleWritePackageListLocked(int userId) { 2136 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2137 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2138 msg.arg1 = userId; 2139 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2140 } 2141 } 2142 2143 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2144 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2145 scheduleWritePackageRestrictionsLocked(userId); 2146 } 2147 2148 void scheduleWritePackageRestrictionsLocked(int userId) { 2149 final int[] userIds = (userId == UserHandle.USER_ALL) 2150 ? sUserManager.getUserIds() : new int[]{userId}; 2151 for (int nextUserId : userIds) { 2152 if (!sUserManager.exists(nextUserId)) return; 2153 mDirtyUsers.add(nextUserId); 2154 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2155 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2156 } 2157 } 2158 } 2159 2160 public static PackageManagerService main(Context context, Installer installer, 2161 boolean factoryTest, boolean onlyCore) { 2162 // Self-check for initial settings. 2163 PackageManagerServiceCompilerMapping.checkProperties(); 2164 2165 PackageManagerService m = new PackageManagerService(context, installer, 2166 factoryTest, onlyCore); 2167 m.enableSystemUserPackages(); 2168 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2169 // disabled after already being started. 2170 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2171 UserHandle.USER_SYSTEM); 2172 ServiceManager.addService("package", m); 2173 return m; 2174 } 2175 2176 private void enableSystemUserPackages() { 2177 if (!UserManager.isSplitSystemUser()) { 2178 return; 2179 } 2180 // For system user, enable apps based on the following conditions: 2181 // - app is whitelisted or belong to one of these groups: 2182 // -- system app which has no launcher icons 2183 // -- system app which has INTERACT_ACROSS_USERS permission 2184 // -- system IME app 2185 // - app is not in the blacklist 2186 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2187 Set<String> enableApps = new ArraySet<>(); 2188 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2189 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2190 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2191 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2192 enableApps.addAll(wlApps); 2193 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2194 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2195 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2196 enableApps.removeAll(blApps); 2197 Log.i(TAG, "Applications installed for system user: " + enableApps); 2198 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2199 UserHandle.SYSTEM); 2200 final int allAppsSize = allAps.size(); 2201 synchronized (mPackages) { 2202 for (int i = 0; i < allAppsSize; i++) { 2203 String pName = allAps.get(i); 2204 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2205 // Should not happen, but we shouldn't be failing if it does 2206 if (pkgSetting == null) { 2207 continue; 2208 } 2209 boolean install = enableApps.contains(pName); 2210 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2211 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2212 + " for system user"); 2213 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2214 } 2215 } 2216 } 2217 } 2218 2219 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2220 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2221 Context.DISPLAY_SERVICE); 2222 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2223 } 2224 2225 /** 2226 * Requests that files preopted on a secondary system partition be copied to the data partition 2227 * if possible. Note that the actual copying of the files is accomplished by init for security 2228 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2229 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2230 */ 2231 private static void requestCopyPreoptedFiles() { 2232 final int WAIT_TIME_MS = 100; 2233 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2234 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2235 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2236 // We will wait for up to 100 seconds. 2237 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2238 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2239 try { 2240 Thread.sleep(WAIT_TIME_MS); 2241 } catch (InterruptedException e) { 2242 // Do nothing 2243 } 2244 if (SystemClock.uptimeMillis() > timeEnd) { 2245 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2246 Slog.wtf(TAG, "cppreopt did not finish!"); 2247 break; 2248 } 2249 } 2250 } 2251 } 2252 2253 public PackageManagerService(Context context, Installer installer, 2254 boolean factoryTest, boolean onlyCore) { 2255 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2256 SystemClock.uptimeMillis()); 2257 2258 if (mSdkVersion <= 0) { 2259 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2260 } 2261 2262 mContext = context; 2263 mFactoryTest = factoryTest; 2264 mOnlyCore = onlyCore; 2265 mMetrics = new DisplayMetrics(); 2266 mSettings = new Settings(mPackages); 2267 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2268 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2269 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2270 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2271 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2272 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2273 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2274 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2275 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2276 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2277 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2278 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2279 2280 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2281 if (separateProcesses != null && separateProcesses.length() > 0) { 2282 if ("*".equals(separateProcesses)) { 2283 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2284 mSeparateProcesses = null; 2285 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2286 } else { 2287 mDefParseFlags = 0; 2288 mSeparateProcesses = separateProcesses.split(","); 2289 Slog.w(TAG, "Running with debug.separate_processes: " 2290 + separateProcesses); 2291 } 2292 } else { 2293 mDefParseFlags = 0; 2294 mSeparateProcesses = null; 2295 } 2296 2297 mInstaller = installer; 2298 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2299 "*dexopt*"); 2300 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2301 2302 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2303 FgThread.get().getLooper()); 2304 2305 getDefaultDisplayMetrics(context, mMetrics); 2306 2307 SystemConfig systemConfig = SystemConfig.getInstance(); 2308 mGlobalGids = systemConfig.getGlobalGids(); 2309 mSystemPermissions = systemConfig.getSystemPermissions(); 2310 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2311 2312 mProtectedPackages = new ProtectedPackages(mContext); 2313 2314 synchronized (mInstallLock) { 2315 // writer 2316 synchronized (mPackages) { 2317 mHandlerThread = new ServiceThread(TAG, 2318 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2319 mHandlerThread.start(); 2320 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2321 mProcessLoggingHandler = new ProcessLoggingHandler(); 2322 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2323 2324 File dataDir = Environment.getDataDirectory(); 2325 mAppInstallDir = new File(dataDir, "app"); 2326 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2327 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2328 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2329 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2330 2331 sUserManager = new UserManagerService(context, this, mPackages); 2332 2333 // Propagate permission configuration in to package manager. 2334 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2335 = systemConfig.getPermissions(); 2336 for (int i=0; i<permConfig.size(); i++) { 2337 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2338 BasePermission bp = mSettings.mPermissions.get(perm.name); 2339 if (bp == null) { 2340 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2341 mSettings.mPermissions.put(perm.name, bp); 2342 } 2343 if (perm.gids != null) { 2344 bp.setGids(perm.gids, perm.perUser); 2345 } 2346 } 2347 2348 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2349 for (int i=0; i<libConfig.size(); i++) { 2350 mSharedLibraries.put(libConfig.keyAt(i), 2351 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2352 } 2353 2354 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2355 2356 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2357 2358 if (mFirstBoot) { 2359 requestCopyPreoptedFiles(); 2360 } 2361 2362 String customResolverActivity = Resources.getSystem().getString( 2363 R.string.config_customResolverActivity); 2364 if (TextUtils.isEmpty(customResolverActivity)) { 2365 customResolverActivity = null; 2366 } else { 2367 mCustomResolverComponentName = ComponentName.unflattenFromString( 2368 customResolverActivity); 2369 } 2370 2371 long startTime = SystemClock.uptimeMillis(); 2372 2373 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2374 startTime); 2375 2376 // Set flag to monitor and not change apk file paths when 2377 // scanning install directories. 2378 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2379 2380 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2381 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2382 2383 if (bootClassPath == null) { 2384 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2385 } 2386 2387 if (systemServerClassPath == null) { 2388 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2389 } 2390 2391 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2392 final String[] dexCodeInstructionSets = 2393 getDexCodeInstructionSets( 2394 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2395 2396 /** 2397 * Ensure all external libraries have had dexopt run on them. 2398 */ 2399 if (mSharedLibraries.size() > 0) { 2400 // NOTE: For now, we're compiling these system "shared libraries" 2401 // (and framework jars) into all available architectures. It's possible 2402 // to compile them only when we come across an app that uses them (there's 2403 // already logic for that in scanPackageLI) but that adds some complexity. 2404 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2405 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2406 final String lib = libEntry.path; 2407 if (lib == null) { 2408 continue; 2409 } 2410 2411 try { 2412 // Shared libraries do not have profiles so we perform a full 2413 // AOT compilation (if needed). 2414 int dexoptNeeded = DexFile.getDexOptNeeded( 2415 lib, dexCodeInstructionSet, 2416 getCompilerFilterForReason(REASON_SHARED_APK), 2417 false /* newProfile */); 2418 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2419 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2420 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2421 getCompilerFilterForReason(REASON_SHARED_APK), 2422 StorageManager.UUID_PRIVATE_INTERNAL, 2423 SKIP_SHARED_LIBRARY_CHECK); 2424 } 2425 } catch (FileNotFoundException e) { 2426 Slog.w(TAG, "Library not found: " + lib); 2427 } catch (IOException | InstallerException e) { 2428 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2429 + e.getMessage()); 2430 } 2431 } 2432 } 2433 } 2434 2435 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2436 2437 final VersionInfo ver = mSettings.getInternalVersion(); 2438 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2439 2440 // when upgrading from pre-M, promote system app permissions from install to runtime 2441 mPromoteSystemApps = 2442 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2443 2444 // When upgrading from pre-N, we need to handle package extraction like first boot, 2445 // as there is no profiling data available. 2446 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2447 2448 // save off the names of pre-existing system packages prior to scanning; we don't 2449 // want to automatically grant runtime permissions for new system apps 2450 if (mPromoteSystemApps) { 2451 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2452 while (pkgSettingIter.hasNext()) { 2453 PackageSetting ps = pkgSettingIter.next(); 2454 if (isSystemApp(ps)) { 2455 mExistingSystemPackages.add(ps.name); 2456 } 2457 } 2458 } 2459 2460 // Collect vendor overlay packages. 2461 // (Do this before scanning any apps.) 2462 // For security and version matching reason, only consider 2463 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2464 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2465 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2466 | PackageParser.PARSE_IS_SYSTEM 2467 | PackageParser.PARSE_IS_SYSTEM_DIR 2468 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2469 2470 // Find base frameworks (resource packages without code). 2471 scanDirTracedLI(frameworkDir, mDefParseFlags 2472 | PackageParser.PARSE_IS_SYSTEM 2473 | PackageParser.PARSE_IS_SYSTEM_DIR 2474 | PackageParser.PARSE_IS_PRIVILEGED, 2475 scanFlags | SCAN_NO_DEX, 0); 2476 2477 // Collected privileged system packages. 2478 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2479 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2480 | PackageParser.PARSE_IS_SYSTEM 2481 | PackageParser.PARSE_IS_SYSTEM_DIR 2482 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2483 2484 // Collect ordinary system packages. 2485 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2486 scanDirTracedLI(systemAppDir, mDefParseFlags 2487 | PackageParser.PARSE_IS_SYSTEM 2488 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2489 2490 // Collect all vendor packages. 2491 File vendorAppDir = new File("/vendor/app"); 2492 try { 2493 vendorAppDir = vendorAppDir.getCanonicalFile(); 2494 } catch (IOException e) { 2495 // failed to look up canonical path, continue with original one 2496 } 2497 scanDirTracedLI(vendorAppDir, mDefParseFlags 2498 | PackageParser.PARSE_IS_SYSTEM 2499 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2500 2501 // Collect all OEM packages. 2502 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2503 scanDirTracedLI(oemAppDir, mDefParseFlags 2504 | PackageParser.PARSE_IS_SYSTEM 2505 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2506 2507 // Prune any system packages that no longer exist. 2508 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2509 if (!mOnlyCore) { 2510 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2511 while (psit.hasNext()) { 2512 PackageSetting ps = psit.next(); 2513 2514 /* 2515 * If this is not a system app, it can't be a 2516 * disable system app. 2517 */ 2518 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2519 continue; 2520 } 2521 2522 /* 2523 * If the package is scanned, it's not erased. 2524 */ 2525 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2526 if (scannedPkg != null) { 2527 /* 2528 * If the system app is both scanned and in the 2529 * disabled packages list, then it must have been 2530 * added via OTA. Remove it from the currently 2531 * scanned package so the previously user-installed 2532 * application can be scanned. 2533 */ 2534 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2535 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2536 + ps.name + "; removing system app. Last known codePath=" 2537 + ps.codePathString + ", installStatus=" + ps.installStatus 2538 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2539 + scannedPkg.mVersionCode); 2540 removePackageLI(scannedPkg, true); 2541 mExpectingBetter.put(ps.name, ps.codePath); 2542 } 2543 2544 continue; 2545 } 2546 2547 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2548 psit.remove(); 2549 logCriticalInfo(Log.WARN, "System package " + ps.name 2550 + " no longer exists; it's data will be wiped"); 2551 // Actual deletion of code and data will be handled by later 2552 // reconciliation step 2553 } else { 2554 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2555 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2556 possiblyDeletedUpdatedSystemApps.add(ps.name); 2557 } 2558 } 2559 } 2560 } 2561 2562 //look for any incomplete package installations 2563 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2564 for (int i = 0; i < deletePkgsList.size(); i++) { 2565 // Actual deletion of code and data will be handled by later 2566 // reconciliation step 2567 final String packageName = deletePkgsList.get(i).name; 2568 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2569 synchronized (mPackages) { 2570 mSettings.removePackageLPw(packageName); 2571 } 2572 } 2573 2574 //delete tmp files 2575 deleteTempPackageFiles(); 2576 2577 // Remove any shared userIDs that have no associated packages 2578 mSettings.pruneSharedUsersLPw(); 2579 2580 if (!mOnlyCore) { 2581 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2582 SystemClock.uptimeMillis()); 2583 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2584 2585 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2586 | PackageParser.PARSE_FORWARD_LOCK, 2587 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2588 2589 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2590 | PackageParser.PARSE_IS_EPHEMERAL, 2591 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2592 2593 /** 2594 * Remove disable package settings for any updated system 2595 * apps that were removed via an OTA. If they're not a 2596 * previously-updated app, remove them completely. 2597 * Otherwise, just revoke their system-level permissions. 2598 */ 2599 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2600 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2601 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2602 2603 String msg; 2604 if (deletedPkg == null) { 2605 msg = "Updated system package " + deletedAppName 2606 + " no longer exists; it's data will be wiped"; 2607 // Actual deletion of code and data will be handled by later 2608 // reconciliation step 2609 } else { 2610 msg = "Updated system app + " + deletedAppName 2611 + " no longer present; removing system privileges for " 2612 + deletedAppName; 2613 2614 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2615 2616 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2617 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2618 } 2619 logCriticalInfo(Log.WARN, msg); 2620 } 2621 2622 /** 2623 * Make sure all system apps that we expected to appear on 2624 * the userdata partition actually showed up. If they never 2625 * appeared, crawl back and revive the system version. 2626 */ 2627 for (int i = 0; i < mExpectingBetter.size(); i++) { 2628 final String packageName = mExpectingBetter.keyAt(i); 2629 if (!mPackages.containsKey(packageName)) { 2630 final File scanFile = mExpectingBetter.valueAt(i); 2631 2632 logCriticalInfo(Log.WARN, "Expected better " + packageName 2633 + " but never showed up; reverting to system"); 2634 2635 int reparseFlags = mDefParseFlags; 2636 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2637 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2638 | PackageParser.PARSE_IS_SYSTEM_DIR 2639 | PackageParser.PARSE_IS_PRIVILEGED; 2640 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2641 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2642 | PackageParser.PARSE_IS_SYSTEM_DIR; 2643 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2644 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2645 | PackageParser.PARSE_IS_SYSTEM_DIR; 2646 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2647 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2648 | PackageParser.PARSE_IS_SYSTEM_DIR; 2649 } else { 2650 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2651 continue; 2652 } 2653 2654 mSettings.enableSystemPackageLPw(packageName); 2655 2656 try { 2657 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2658 } catch (PackageManagerException e) { 2659 Slog.e(TAG, "Failed to parse original system package: " 2660 + e.getMessage()); 2661 } 2662 } 2663 } 2664 } 2665 mExpectingBetter.clear(); 2666 2667 // Resolve protected action filters. Only the setup wizard is allowed to 2668 // have a high priority filter for these actions. 2669 mSetupWizardPackage = getSetupWizardPackageName(); 2670 if (mProtectedFilters.size() > 0) { 2671 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2672 Slog.i(TAG, "No setup wizard;" 2673 + " All protected intents capped to priority 0"); 2674 } 2675 for (ActivityIntentInfo filter : mProtectedFilters) { 2676 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2677 if (DEBUG_FILTERS) { 2678 Slog.i(TAG, "Found setup wizard;" 2679 + " allow priority " + filter.getPriority() + ";" 2680 + " package: " + filter.activity.info.packageName 2681 + " activity: " + filter.activity.className 2682 + " priority: " + filter.getPriority()); 2683 } 2684 // skip setup wizard; allow it to keep the high priority filter 2685 continue; 2686 } 2687 Slog.w(TAG, "Protected action; cap priority to 0;" 2688 + " package: " + filter.activity.info.packageName 2689 + " activity: " + filter.activity.className 2690 + " origPrio: " + filter.getPriority()); 2691 filter.setPriority(0); 2692 } 2693 } 2694 mDeferProtectedFilters = false; 2695 mProtectedFilters.clear(); 2696 2697 // Now that we know all of the shared libraries, update all clients to have 2698 // the correct library paths. 2699 updateAllSharedLibrariesLPw(); 2700 2701 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2702 // NOTE: We ignore potential failures here during a system scan (like 2703 // the rest of the commands above) because there's precious little we 2704 // can do about it. A settings error is reported, though. 2705 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2706 false /* boot complete */); 2707 } 2708 2709 // Now that we know all the packages we are keeping, 2710 // read and update their last usage times. 2711 mPackageUsage.readLP(); 2712 2713 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2714 SystemClock.uptimeMillis()); 2715 Slog.i(TAG, "Time to scan packages: " 2716 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2717 + " seconds"); 2718 2719 // If the platform SDK has changed since the last time we booted, 2720 // we need to re-grant app permission to catch any new ones that 2721 // appear. This is really a hack, and means that apps can in some 2722 // cases get permissions that the user didn't initially explicitly 2723 // allow... it would be nice to have some better way to handle 2724 // this situation. 2725 int updateFlags = UPDATE_PERMISSIONS_ALL; 2726 if (ver.sdkVersion != mSdkVersion) { 2727 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2728 + mSdkVersion + "; regranting permissions for internal storage"); 2729 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2730 } 2731 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2732 ver.sdkVersion = mSdkVersion; 2733 2734 // If this is the first boot or an update from pre-M, and it is a normal 2735 // boot, then we need to initialize the default preferred apps across 2736 // all defined users. 2737 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2738 for (UserInfo user : sUserManager.getUsers(true)) { 2739 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2740 applyFactoryDefaultBrowserLPw(user.id); 2741 primeDomainVerificationsLPw(user.id); 2742 } 2743 } 2744 2745 // Prepare storage for system user really early during boot, 2746 // since core system apps like SettingsProvider and SystemUI 2747 // can't wait for user to start 2748 final int storageFlags; 2749 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2750 storageFlags = StorageManager.FLAG_STORAGE_DE; 2751 } else { 2752 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2753 } 2754 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2755 storageFlags); 2756 2757 // If this is first boot after an OTA, and a normal boot, then 2758 // we need to clear code cache directories. 2759 // Note that we do *not* clear the application profiles. These remain valid 2760 // across OTAs and are used to drive profile verification (post OTA) and 2761 // profile compilation (without waiting to collect a fresh set of profiles). 2762 if (mIsUpgrade && !onlyCore) { 2763 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2764 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2765 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2766 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2767 // No apps are running this early, so no need to freeze 2768 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2769 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2770 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2771 } 2772 } 2773 ver.fingerprint = Build.FINGERPRINT; 2774 } 2775 2776 checkDefaultBrowser(); 2777 2778 // clear only after permissions and other defaults have been updated 2779 mExistingSystemPackages.clear(); 2780 mPromoteSystemApps = false; 2781 2782 // All the changes are done during package scanning. 2783 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2784 2785 // can downgrade to reader 2786 mSettings.writeLPr(); 2787 2788 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2789 // early on (before the package manager declares itself as early) because other 2790 // components in the system server might ask for package contexts for these apps. 2791 // 2792 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2793 // (i.e, that the data partition is unavailable). 2794 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2795 long start = System.nanoTime(); 2796 List<PackageParser.Package> coreApps = new ArrayList<>(); 2797 for (PackageParser.Package pkg : mPackages.values()) { 2798 if (pkg.coreApp) { 2799 coreApps.add(pkg); 2800 } 2801 } 2802 2803 int[] stats = performDexOpt(coreApps, false, 2804 getCompilerFilterForReason(REASON_CORE_APP)); 2805 2806 final int elapsedTimeSeconds = 2807 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2808 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2809 2810 if (DEBUG_DEXOPT) { 2811 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2812 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2813 } 2814 2815 2816 // TODO: Should we log these stats to tron too ? 2817 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2818 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2819 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2820 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2821 } 2822 2823 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2824 SystemClock.uptimeMillis()); 2825 2826 if (!mOnlyCore) { 2827 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2828 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2829 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2830 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2831 mIntentFilterVerifierComponent); 2832 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2833 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2834 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2835 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2836 } else { 2837 mRequiredVerifierPackage = null; 2838 mRequiredInstallerPackage = null; 2839 mIntentFilterVerifierComponent = null; 2840 mIntentFilterVerifier = null; 2841 mServicesSystemSharedLibraryPackageName = null; 2842 mSharedSystemSharedLibraryPackageName = null; 2843 } 2844 2845 mInstallerService = new PackageInstallerService(context, this); 2846 2847 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2848 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2849 // both the installer and resolver must be present to enable ephemeral 2850 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2851 if (DEBUG_EPHEMERAL) { 2852 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2853 + " installer:" + ephemeralInstallerComponent); 2854 } 2855 mEphemeralResolverComponent = ephemeralResolverComponent; 2856 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2857 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2858 mEphemeralResolverConnection = 2859 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2860 } else { 2861 if (DEBUG_EPHEMERAL) { 2862 final String missingComponent = 2863 (ephemeralResolverComponent == null) 2864 ? (ephemeralInstallerComponent == null) 2865 ? "resolver and installer" 2866 : "resolver" 2867 : "installer"; 2868 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2869 } 2870 mEphemeralResolverComponent = null; 2871 mEphemeralInstallerComponent = null; 2872 mEphemeralResolverConnection = null; 2873 } 2874 2875 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2876 } // synchronized (mPackages) 2877 } // synchronized (mInstallLock) 2878 2879 // Now after opening every single application zip, make sure they 2880 // are all flushed. Not really needed, but keeps things nice and 2881 // tidy. 2882 Runtime.getRuntime().gc(); 2883 2884 // The initial scanning above does many calls into installd while 2885 // holding the mPackages lock, but we're mostly interested in yelling 2886 // once we have a booted system. 2887 mInstaller.setWarnIfHeld(mPackages); 2888 2889 // Expose private service for system components to use. 2890 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2891 } 2892 2893 @Override 2894 public boolean isFirstBoot() { 2895 return mFirstBoot; 2896 } 2897 2898 @Override 2899 public boolean isOnlyCoreApps() { 2900 return mOnlyCore; 2901 } 2902 2903 @Override 2904 public boolean isUpgrade() { 2905 return mIsUpgrade; 2906 } 2907 2908 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2909 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2910 2911 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2912 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2913 UserHandle.USER_SYSTEM); 2914 if (matches.size() == 1) { 2915 return matches.get(0).getComponentInfo().packageName; 2916 } else { 2917 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2918 return null; 2919 } 2920 } 2921 2922 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2923 synchronized (mPackages) { 2924 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2925 if (libraryEntry == null) { 2926 throw new IllegalStateException("Missing required shared library:" + libraryName); 2927 } 2928 return libraryEntry.apk; 2929 } 2930 } 2931 2932 private @NonNull String getRequiredInstallerLPr() { 2933 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2934 intent.addCategory(Intent.CATEGORY_DEFAULT); 2935 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2936 2937 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2938 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2939 UserHandle.USER_SYSTEM); 2940 if (matches.size() == 1) { 2941 ResolveInfo resolveInfo = matches.get(0); 2942 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2943 throw new RuntimeException("The installer must be a privileged app"); 2944 } 2945 return matches.get(0).getComponentInfo().packageName; 2946 } else { 2947 throw new RuntimeException("There must be exactly one installer; found " + matches); 2948 } 2949 } 2950 2951 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2952 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2953 2954 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2955 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2956 UserHandle.USER_SYSTEM); 2957 ResolveInfo best = null; 2958 final int N = matches.size(); 2959 for (int i = 0; i < N; i++) { 2960 final ResolveInfo cur = matches.get(i); 2961 final String packageName = cur.getComponentInfo().packageName; 2962 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2963 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2964 continue; 2965 } 2966 2967 if (best == null || cur.priority > best.priority) { 2968 best = cur; 2969 } 2970 } 2971 2972 if (best != null) { 2973 return best.getComponentInfo().getComponentName(); 2974 } else { 2975 throw new RuntimeException("There must be at least one intent filter verifier"); 2976 } 2977 } 2978 2979 private @Nullable ComponentName getEphemeralResolverLPr() { 2980 final String[] packageArray = 2981 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2982 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2983 if (DEBUG_EPHEMERAL) { 2984 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2985 } 2986 return null; 2987 } 2988 2989 final int resolveFlags = 2990 MATCH_DIRECT_BOOT_AWARE 2991 | MATCH_DIRECT_BOOT_UNAWARE 2992 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2993 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2994 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2995 resolveFlags, UserHandle.USER_SYSTEM); 2996 2997 final int N = resolvers.size(); 2998 if (N == 0) { 2999 if (DEBUG_EPHEMERAL) { 3000 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3001 } 3002 return null; 3003 } 3004 3005 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3006 for (int i = 0; i < N; i++) { 3007 final ResolveInfo info = resolvers.get(i); 3008 3009 if (info.serviceInfo == null) { 3010 continue; 3011 } 3012 3013 final String packageName = info.serviceInfo.packageName; 3014 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3015 if (DEBUG_EPHEMERAL) { 3016 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3017 + " pkg: " + packageName + ", info:" + info); 3018 } 3019 continue; 3020 } 3021 3022 if (DEBUG_EPHEMERAL) { 3023 Slog.v(TAG, "Ephemeral resolver found;" 3024 + " pkg: " + packageName + ", info:" + info); 3025 } 3026 return new ComponentName(packageName, info.serviceInfo.name); 3027 } 3028 if (DEBUG_EPHEMERAL) { 3029 Slog.v(TAG, "Ephemeral resolver NOT found"); 3030 } 3031 return null; 3032 } 3033 3034 private @Nullable ComponentName getEphemeralInstallerLPr() { 3035 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3036 intent.addCategory(Intent.CATEGORY_DEFAULT); 3037 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3038 3039 final int resolveFlags = 3040 MATCH_DIRECT_BOOT_AWARE 3041 | MATCH_DIRECT_BOOT_UNAWARE 3042 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3043 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3044 resolveFlags, UserHandle.USER_SYSTEM); 3045 if (matches.size() == 0) { 3046 return null; 3047 } else if (matches.size() == 1) { 3048 return matches.get(0).getComponentInfo().getComponentName(); 3049 } else { 3050 throw new RuntimeException( 3051 "There must be at most one ephemeral installer; found " + matches); 3052 } 3053 } 3054 3055 private void primeDomainVerificationsLPw(int userId) { 3056 if (DEBUG_DOMAIN_VERIFICATION) { 3057 Slog.d(TAG, "Priming domain verifications in user " + userId); 3058 } 3059 3060 SystemConfig systemConfig = SystemConfig.getInstance(); 3061 ArraySet<String> packages = systemConfig.getLinkedApps(); 3062 ArraySet<String> domains = new ArraySet<String>(); 3063 3064 for (String packageName : packages) { 3065 PackageParser.Package pkg = mPackages.get(packageName); 3066 if (pkg != null) { 3067 if (!pkg.isSystemApp()) { 3068 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3069 continue; 3070 } 3071 3072 domains.clear(); 3073 for (PackageParser.Activity a : pkg.activities) { 3074 for (ActivityIntentInfo filter : a.intents) { 3075 if (hasValidDomains(filter)) { 3076 domains.addAll(filter.getHostsList()); 3077 } 3078 } 3079 } 3080 3081 if (domains.size() > 0) { 3082 if (DEBUG_DOMAIN_VERIFICATION) { 3083 Slog.v(TAG, " + " + packageName); 3084 } 3085 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3086 // state w.r.t. the formal app-linkage "no verification attempted" state; 3087 // and then 'always' in the per-user state actually used for intent resolution. 3088 final IntentFilterVerificationInfo ivi; 3089 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 3090 new ArrayList<String>(domains)); 3091 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3092 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3093 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3094 } else { 3095 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3096 + "' does not handle web links"); 3097 } 3098 } else { 3099 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3100 } 3101 } 3102 3103 scheduleWritePackageRestrictionsLocked(userId); 3104 scheduleWriteSettingsLocked(); 3105 } 3106 3107 private void applyFactoryDefaultBrowserLPw(int userId) { 3108 // The default browser app's package name is stored in a string resource, 3109 // with a product-specific overlay used for vendor customization. 3110 String browserPkg = mContext.getResources().getString( 3111 com.android.internal.R.string.default_browser); 3112 if (!TextUtils.isEmpty(browserPkg)) { 3113 // non-empty string => required to be a known package 3114 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3115 if (ps == null) { 3116 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3117 browserPkg = null; 3118 } else { 3119 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3120 } 3121 } 3122 3123 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3124 // default. If there's more than one, just leave everything alone. 3125 if (browserPkg == null) { 3126 calculateDefaultBrowserLPw(userId); 3127 } 3128 } 3129 3130 private void calculateDefaultBrowserLPw(int userId) { 3131 List<String> allBrowsers = resolveAllBrowserApps(userId); 3132 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3133 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3134 } 3135 3136 private List<String> resolveAllBrowserApps(int userId) { 3137 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3138 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3139 PackageManager.MATCH_ALL, userId); 3140 3141 final int count = list.size(); 3142 List<String> result = new ArrayList<String>(count); 3143 for (int i=0; i<count; i++) { 3144 ResolveInfo info = list.get(i); 3145 if (info.activityInfo == null 3146 || !info.handleAllWebDataURI 3147 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3148 || result.contains(info.activityInfo.packageName)) { 3149 continue; 3150 } 3151 result.add(info.activityInfo.packageName); 3152 } 3153 3154 return result; 3155 } 3156 3157 private boolean packageIsBrowser(String packageName, int userId) { 3158 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3159 PackageManager.MATCH_ALL, userId); 3160 final int N = list.size(); 3161 for (int i = 0; i < N; i++) { 3162 ResolveInfo info = list.get(i); 3163 if (packageName.equals(info.activityInfo.packageName)) { 3164 return true; 3165 } 3166 } 3167 return false; 3168 } 3169 3170 private void checkDefaultBrowser() { 3171 final int myUserId = UserHandle.myUserId(); 3172 final String packageName = getDefaultBrowserPackageName(myUserId); 3173 if (packageName != null) { 3174 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3175 if (info == null) { 3176 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3177 synchronized (mPackages) { 3178 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3179 } 3180 } 3181 } 3182 } 3183 3184 @Override 3185 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3186 throws RemoteException { 3187 try { 3188 return super.onTransact(code, data, reply, flags); 3189 } catch (RuntimeException e) { 3190 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3191 Slog.wtf(TAG, "Package Manager Crash", e); 3192 } 3193 throw e; 3194 } 3195 } 3196 3197 static int[] appendInts(int[] cur, int[] add) { 3198 if (add == null) return cur; 3199 if (cur == null) return add; 3200 final int N = add.length; 3201 for (int i=0; i<N; i++) { 3202 cur = appendInt(cur, add[i]); 3203 } 3204 return cur; 3205 } 3206 3207 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3208 if (!sUserManager.exists(userId)) return null; 3209 if (ps == null) { 3210 return null; 3211 } 3212 final PackageParser.Package p = ps.pkg; 3213 if (p == null) { 3214 return null; 3215 } 3216 3217 final PermissionsState permissionsState = ps.getPermissionsState(); 3218 3219 // Compute GIDs only if requested 3220 final int[] gids = (flags & PackageManager.GET_GIDS) != 0 3221 ? permissionsState.computeGids(userId) : EMPTY_INT_ARRAY; 3222 // TODO b/29879962 Calculate granted permissions only if needed in generatePackageInfo 3223 final Set<String> permissions = permissionsState.getPermissions(userId); 3224 final PackageUserState state = ps.readUserState(userId); 3225 3226 return PackageParser.generatePackageInfo(p, gids, flags, 3227 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3228 } 3229 3230 @Override 3231 public void checkPackageStartable(String packageName, int userId) { 3232 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3233 3234 synchronized (mPackages) { 3235 final PackageSetting ps = mSettings.mPackages.get(packageName); 3236 if (ps == null) { 3237 throw new SecurityException("Package " + packageName + " was not found!"); 3238 } 3239 3240 if (!ps.getInstalled(userId)) { 3241 throw new SecurityException( 3242 "Package " + packageName + " was not installed for user " + userId + "!"); 3243 } 3244 3245 if (mSafeMode && !ps.isSystem()) { 3246 throw new SecurityException("Package " + packageName + " not a system app!"); 3247 } 3248 3249 if (mFrozenPackages.contains(packageName)) { 3250 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3251 } 3252 3253 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3254 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3255 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3256 } 3257 } 3258 } 3259 3260 @Override 3261 public boolean isPackageAvailable(String packageName, int userId) { 3262 if (!sUserManager.exists(userId)) return false; 3263 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3264 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3265 synchronized (mPackages) { 3266 PackageParser.Package p = mPackages.get(packageName); 3267 if (p != null) { 3268 final PackageSetting ps = (PackageSetting) p.mExtras; 3269 if (ps != null) { 3270 final PackageUserState state = ps.readUserState(userId); 3271 if (state != null) { 3272 return PackageParser.isAvailable(state); 3273 } 3274 } 3275 } 3276 } 3277 return false; 3278 } 3279 3280 @Override 3281 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3282 if (!sUserManager.exists(userId)) return null; 3283 flags = updateFlagsForPackage(flags, userId, packageName); 3284 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3285 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3286 // reader 3287 synchronized (mPackages) { 3288 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3289 PackageParser.Package p = null; 3290 if (matchFactoryOnly) { 3291 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3292 if (ps != null) { 3293 return generatePackageInfo(ps, flags, userId); 3294 } 3295 } 3296 if (p == null) { 3297 p = mPackages.get(packageName); 3298 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3299 return null; 3300 } 3301 } 3302 if (DEBUG_PACKAGE_INFO) 3303 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3304 if (p != null) { 3305 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3306 } 3307 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3308 final PackageSetting ps = mSettings.mPackages.get(packageName); 3309 return generatePackageInfo(ps, flags, userId); 3310 } 3311 } 3312 return null; 3313 } 3314 3315 @Override 3316 public String[] currentToCanonicalPackageNames(String[] names) { 3317 String[] out = new String[names.length]; 3318 // reader 3319 synchronized (mPackages) { 3320 for (int i=names.length-1; i>=0; i--) { 3321 PackageSetting ps = mSettings.mPackages.get(names[i]); 3322 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3323 } 3324 } 3325 return out; 3326 } 3327 3328 @Override 3329 public String[] canonicalToCurrentPackageNames(String[] names) { 3330 String[] out = new String[names.length]; 3331 // reader 3332 synchronized (mPackages) { 3333 for (int i=names.length-1; i>=0; i--) { 3334 String cur = mSettings.mRenamedPackages.get(names[i]); 3335 out[i] = cur != null ? cur : names[i]; 3336 } 3337 } 3338 return out; 3339 } 3340 3341 @Override 3342 public int getPackageUid(String packageName, int flags, int userId) { 3343 if (!sUserManager.exists(userId)) return -1; 3344 flags = updateFlagsForPackage(flags, userId, packageName); 3345 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3346 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3347 3348 // reader 3349 synchronized (mPackages) { 3350 final PackageParser.Package p = mPackages.get(packageName); 3351 if (p != null && p.isMatch(flags)) { 3352 return UserHandle.getUid(userId, p.applicationInfo.uid); 3353 } 3354 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3355 final PackageSetting ps = mSettings.mPackages.get(packageName); 3356 if (ps != null && ps.isMatch(flags)) { 3357 return UserHandle.getUid(userId, ps.appId); 3358 } 3359 } 3360 } 3361 3362 return -1; 3363 } 3364 3365 @Override 3366 public int[] getPackageGids(String packageName, int flags, int userId) { 3367 if (!sUserManager.exists(userId)) return null; 3368 flags = updateFlagsForPackage(flags, userId, packageName); 3369 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3370 false /* requireFullPermission */, false /* checkShell */, 3371 "getPackageGids"); 3372 3373 // reader 3374 synchronized (mPackages) { 3375 final PackageParser.Package p = mPackages.get(packageName); 3376 if (p != null && p.isMatch(flags)) { 3377 PackageSetting ps = (PackageSetting) p.mExtras; 3378 return ps.getPermissionsState().computeGids(userId); 3379 } 3380 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3381 final PackageSetting ps = mSettings.mPackages.get(packageName); 3382 if (ps != null && ps.isMatch(flags)) { 3383 return ps.getPermissionsState().computeGids(userId); 3384 } 3385 } 3386 } 3387 3388 return null; 3389 } 3390 3391 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3392 if (bp.perm != null) { 3393 return PackageParser.generatePermissionInfo(bp.perm, flags); 3394 } 3395 PermissionInfo pi = new PermissionInfo(); 3396 pi.name = bp.name; 3397 pi.packageName = bp.sourcePackage; 3398 pi.nonLocalizedLabel = bp.name; 3399 pi.protectionLevel = bp.protectionLevel; 3400 return pi; 3401 } 3402 3403 @Override 3404 public PermissionInfo getPermissionInfo(String name, int flags) { 3405 // reader 3406 synchronized (mPackages) { 3407 final BasePermission p = mSettings.mPermissions.get(name); 3408 if (p != null) { 3409 return generatePermissionInfo(p, flags); 3410 } 3411 return null; 3412 } 3413 } 3414 3415 @Override 3416 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3417 int flags) { 3418 // reader 3419 synchronized (mPackages) { 3420 if (group != null && !mPermissionGroups.containsKey(group)) { 3421 // This is thrown as NameNotFoundException 3422 return null; 3423 } 3424 3425 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3426 for (BasePermission p : mSettings.mPermissions.values()) { 3427 if (group == null) { 3428 if (p.perm == null || p.perm.info.group == null) { 3429 out.add(generatePermissionInfo(p, flags)); 3430 } 3431 } else { 3432 if (p.perm != null && group.equals(p.perm.info.group)) { 3433 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3434 } 3435 } 3436 } 3437 return new ParceledListSlice<>(out); 3438 } 3439 } 3440 3441 @Override 3442 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3443 // reader 3444 synchronized (mPackages) { 3445 return PackageParser.generatePermissionGroupInfo( 3446 mPermissionGroups.get(name), flags); 3447 } 3448 } 3449 3450 @Override 3451 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3452 // reader 3453 synchronized (mPackages) { 3454 final int N = mPermissionGroups.size(); 3455 ArrayList<PermissionGroupInfo> out 3456 = new ArrayList<PermissionGroupInfo>(N); 3457 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3458 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3459 } 3460 return new ParceledListSlice<>(out); 3461 } 3462 } 3463 3464 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3465 int userId) { 3466 if (!sUserManager.exists(userId)) return null; 3467 PackageSetting ps = mSettings.mPackages.get(packageName); 3468 if (ps != null) { 3469 if (ps.pkg == null) { 3470 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3471 if (pInfo != null) { 3472 return pInfo.applicationInfo; 3473 } 3474 return null; 3475 } 3476 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3477 ps.readUserState(userId), userId); 3478 } 3479 return null; 3480 } 3481 3482 @Override 3483 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3484 if (!sUserManager.exists(userId)) return null; 3485 flags = updateFlagsForApplication(flags, userId, packageName); 3486 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3487 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3488 // writer 3489 synchronized (mPackages) { 3490 PackageParser.Package p = mPackages.get(packageName); 3491 if (DEBUG_PACKAGE_INFO) Log.v( 3492 TAG, "getApplicationInfo " + packageName 3493 + ": " + p); 3494 if (p != null) { 3495 PackageSetting ps = mSettings.mPackages.get(packageName); 3496 if (ps == null) return null; 3497 // Note: isEnabledLP() does not apply here - always return info 3498 return PackageParser.generateApplicationInfo( 3499 p, flags, ps.readUserState(userId), userId); 3500 } 3501 if ("android".equals(packageName)||"system".equals(packageName)) { 3502 return mAndroidApplication; 3503 } 3504 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3505 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3506 } 3507 } 3508 return null; 3509 } 3510 3511 @Override 3512 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3513 final IPackageDataObserver observer) { 3514 mContext.enforceCallingOrSelfPermission( 3515 android.Manifest.permission.CLEAR_APP_CACHE, null); 3516 // Queue up an async operation since clearing cache may take a little while. 3517 mHandler.post(new Runnable() { 3518 public void run() { 3519 mHandler.removeCallbacks(this); 3520 boolean success = true; 3521 synchronized (mInstallLock) { 3522 try { 3523 mInstaller.freeCache(volumeUuid, freeStorageSize); 3524 } catch (InstallerException e) { 3525 Slog.w(TAG, "Couldn't clear application caches: " + e); 3526 success = false; 3527 } 3528 } 3529 if (observer != null) { 3530 try { 3531 observer.onRemoveCompleted(null, success); 3532 } catch (RemoteException e) { 3533 Slog.w(TAG, "RemoveException when invoking call back"); 3534 } 3535 } 3536 } 3537 }); 3538 } 3539 3540 @Override 3541 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3542 final IntentSender pi) { 3543 mContext.enforceCallingOrSelfPermission( 3544 android.Manifest.permission.CLEAR_APP_CACHE, null); 3545 // Queue up an async operation since clearing cache may take a little while. 3546 mHandler.post(new Runnable() { 3547 public void run() { 3548 mHandler.removeCallbacks(this); 3549 boolean success = true; 3550 synchronized (mInstallLock) { 3551 try { 3552 mInstaller.freeCache(volumeUuid, freeStorageSize); 3553 } catch (InstallerException e) { 3554 Slog.w(TAG, "Couldn't clear application caches: " + e); 3555 success = false; 3556 } 3557 } 3558 if(pi != null) { 3559 try { 3560 // Callback via pending intent 3561 int code = success ? 1 : 0; 3562 pi.sendIntent(null, code, null, 3563 null, null); 3564 } catch (SendIntentException e1) { 3565 Slog.i(TAG, "Failed to send pending intent"); 3566 } 3567 } 3568 } 3569 }); 3570 } 3571 3572 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3573 synchronized (mInstallLock) { 3574 try { 3575 mInstaller.freeCache(volumeUuid, freeStorageSize); 3576 } catch (InstallerException e) { 3577 throw new IOException("Failed to free enough space", e); 3578 } 3579 } 3580 } 3581 3582 /** 3583 * Update given flags based on encryption status of current user. 3584 */ 3585 private int updateFlags(int flags, int userId) { 3586 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3587 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3588 // Caller expressed an explicit opinion about what encryption 3589 // aware/unaware components they want to see, so fall through and 3590 // give them what they want 3591 } else { 3592 // Caller expressed no opinion, so match based on user state 3593 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3594 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3595 } else { 3596 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3597 } 3598 } 3599 return flags; 3600 } 3601 3602 private UserManagerInternal getUserManagerInternal() { 3603 if (mUserManagerInternal == null) { 3604 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3605 } 3606 return mUserManagerInternal; 3607 } 3608 3609 /** 3610 * Update given flags when being used to request {@link PackageInfo}. 3611 */ 3612 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3613 boolean triaged = true; 3614 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3615 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3616 // Caller is asking for component details, so they'd better be 3617 // asking for specific encryption matching behavior, or be triaged 3618 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3619 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3620 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3621 triaged = false; 3622 } 3623 } 3624 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3625 | PackageManager.MATCH_SYSTEM_ONLY 3626 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3627 triaged = false; 3628 } 3629 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3630 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3631 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3632 } 3633 return updateFlags(flags, userId); 3634 } 3635 3636 /** 3637 * Update given flags when being used to request {@link ApplicationInfo}. 3638 */ 3639 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3640 return updateFlagsForPackage(flags, userId, cookie); 3641 } 3642 3643 /** 3644 * Update given flags when being used to request {@link ComponentInfo}. 3645 */ 3646 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3647 if (cookie instanceof Intent) { 3648 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3649 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3650 } 3651 } 3652 3653 boolean triaged = true; 3654 // Caller is asking for component details, so they'd better be 3655 // asking for specific encryption matching behavior, or be triaged 3656 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3657 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3658 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3659 triaged = false; 3660 } 3661 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3662 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3663 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3664 } 3665 3666 return updateFlags(flags, userId); 3667 } 3668 3669 /** 3670 * Update given flags when being used to request {@link ResolveInfo}. 3671 */ 3672 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3673 // Safe mode means we shouldn't match any third-party components 3674 if (mSafeMode) { 3675 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3676 } 3677 3678 return updateFlagsForComponent(flags, userId, cookie); 3679 } 3680 3681 @Override 3682 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3683 if (!sUserManager.exists(userId)) return null; 3684 flags = updateFlagsForComponent(flags, userId, component); 3685 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3686 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3687 synchronized (mPackages) { 3688 PackageParser.Activity a = mActivities.mActivities.get(component); 3689 3690 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3691 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3692 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3693 if (ps == null) return null; 3694 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3695 userId); 3696 } 3697 if (mResolveComponentName.equals(component)) { 3698 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3699 new PackageUserState(), userId); 3700 } 3701 } 3702 return null; 3703 } 3704 3705 @Override 3706 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3707 String resolvedType) { 3708 synchronized (mPackages) { 3709 if (component.equals(mResolveComponentName)) { 3710 // The resolver supports EVERYTHING! 3711 return true; 3712 } 3713 PackageParser.Activity a = mActivities.mActivities.get(component); 3714 if (a == null) { 3715 return false; 3716 } 3717 for (int i=0; i<a.intents.size(); i++) { 3718 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3719 intent.getData(), intent.getCategories(), TAG) >= 0) { 3720 return true; 3721 } 3722 } 3723 return false; 3724 } 3725 } 3726 3727 @Override 3728 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3729 if (!sUserManager.exists(userId)) return null; 3730 flags = updateFlagsForComponent(flags, userId, component); 3731 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3732 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3733 synchronized (mPackages) { 3734 PackageParser.Activity a = mReceivers.mActivities.get(component); 3735 if (DEBUG_PACKAGE_INFO) Log.v( 3736 TAG, "getReceiverInfo " + component + ": " + a); 3737 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3738 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3739 if (ps == null) return null; 3740 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3741 userId); 3742 } 3743 } 3744 return null; 3745 } 3746 3747 @Override 3748 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3749 if (!sUserManager.exists(userId)) return null; 3750 flags = updateFlagsForComponent(flags, userId, component); 3751 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3752 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3753 synchronized (mPackages) { 3754 PackageParser.Service s = mServices.mServices.get(component); 3755 if (DEBUG_PACKAGE_INFO) Log.v( 3756 TAG, "getServiceInfo " + component + ": " + s); 3757 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3758 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3759 if (ps == null) return null; 3760 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3761 userId); 3762 } 3763 } 3764 return null; 3765 } 3766 3767 @Override 3768 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3769 if (!sUserManager.exists(userId)) return null; 3770 flags = updateFlagsForComponent(flags, userId, component); 3771 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3772 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3773 synchronized (mPackages) { 3774 PackageParser.Provider p = mProviders.mProviders.get(component); 3775 if (DEBUG_PACKAGE_INFO) Log.v( 3776 TAG, "getProviderInfo " + component + ": " + p); 3777 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3778 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3779 if (ps == null) return null; 3780 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3781 userId); 3782 } 3783 } 3784 return null; 3785 } 3786 3787 @Override 3788 public String[] getSystemSharedLibraryNames() { 3789 Set<String> libSet; 3790 synchronized (mPackages) { 3791 libSet = mSharedLibraries.keySet(); 3792 int size = libSet.size(); 3793 if (size > 0) { 3794 String[] libs = new String[size]; 3795 libSet.toArray(libs); 3796 return libs; 3797 } 3798 } 3799 return null; 3800 } 3801 3802 @Override 3803 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3804 synchronized (mPackages) { 3805 return mServicesSystemSharedLibraryPackageName; 3806 } 3807 } 3808 3809 @Override 3810 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3811 synchronized (mPackages) { 3812 return mSharedSystemSharedLibraryPackageName; 3813 } 3814 } 3815 3816 @Override 3817 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3818 synchronized (mPackages) { 3819 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3820 3821 final FeatureInfo fi = new FeatureInfo(); 3822 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3823 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3824 res.add(fi); 3825 3826 return new ParceledListSlice<>(res); 3827 } 3828 } 3829 3830 @Override 3831 public boolean hasSystemFeature(String name, int version) { 3832 synchronized (mPackages) { 3833 final FeatureInfo feat = mAvailableFeatures.get(name); 3834 if (feat == null) { 3835 return false; 3836 } else { 3837 return feat.version >= version; 3838 } 3839 } 3840 } 3841 3842 @Override 3843 public int checkPermission(String permName, String pkgName, int userId) { 3844 if (!sUserManager.exists(userId)) { 3845 return PackageManager.PERMISSION_DENIED; 3846 } 3847 3848 synchronized (mPackages) { 3849 final PackageParser.Package p = mPackages.get(pkgName); 3850 if (p != null && p.mExtras != null) { 3851 final PackageSetting ps = (PackageSetting) p.mExtras; 3852 final PermissionsState permissionsState = ps.getPermissionsState(); 3853 if (permissionsState.hasPermission(permName, userId)) { 3854 return PackageManager.PERMISSION_GRANTED; 3855 } 3856 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3857 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3858 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3859 return PackageManager.PERMISSION_GRANTED; 3860 } 3861 } 3862 } 3863 3864 return PackageManager.PERMISSION_DENIED; 3865 } 3866 3867 @Override 3868 public int checkUidPermission(String permName, int uid) { 3869 final int userId = UserHandle.getUserId(uid); 3870 3871 if (!sUserManager.exists(userId)) { 3872 return PackageManager.PERMISSION_DENIED; 3873 } 3874 3875 synchronized (mPackages) { 3876 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3877 if (obj != null) { 3878 final SettingBase ps = (SettingBase) obj; 3879 final PermissionsState permissionsState = ps.getPermissionsState(); 3880 if (permissionsState.hasPermission(permName, userId)) { 3881 return PackageManager.PERMISSION_GRANTED; 3882 } 3883 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3884 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3885 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3886 return PackageManager.PERMISSION_GRANTED; 3887 } 3888 } else { 3889 ArraySet<String> perms = mSystemPermissions.get(uid); 3890 if (perms != null) { 3891 if (perms.contains(permName)) { 3892 return PackageManager.PERMISSION_GRANTED; 3893 } 3894 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3895 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3896 return PackageManager.PERMISSION_GRANTED; 3897 } 3898 } 3899 } 3900 } 3901 3902 return PackageManager.PERMISSION_DENIED; 3903 } 3904 3905 @Override 3906 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3907 if (UserHandle.getCallingUserId() != userId) { 3908 mContext.enforceCallingPermission( 3909 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3910 "isPermissionRevokedByPolicy for user " + userId); 3911 } 3912 3913 if (checkPermission(permission, packageName, userId) 3914 == PackageManager.PERMISSION_GRANTED) { 3915 return false; 3916 } 3917 3918 final long identity = Binder.clearCallingIdentity(); 3919 try { 3920 final int flags = getPermissionFlags(permission, packageName, userId); 3921 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3922 } finally { 3923 Binder.restoreCallingIdentity(identity); 3924 } 3925 } 3926 3927 @Override 3928 public String getPermissionControllerPackageName() { 3929 synchronized (mPackages) { 3930 return mRequiredInstallerPackage; 3931 } 3932 } 3933 3934 /** 3935 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3936 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3937 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3938 * @param message the message to log on security exception 3939 */ 3940 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3941 boolean checkShell, String message) { 3942 if (userId < 0) { 3943 throw new IllegalArgumentException("Invalid userId " + userId); 3944 } 3945 if (checkShell) { 3946 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3947 } 3948 if (userId == UserHandle.getUserId(callingUid)) return; 3949 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3950 if (requireFullPermission) { 3951 mContext.enforceCallingOrSelfPermission( 3952 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3953 } else { 3954 try { 3955 mContext.enforceCallingOrSelfPermission( 3956 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3957 } catch (SecurityException se) { 3958 mContext.enforceCallingOrSelfPermission( 3959 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3960 } 3961 } 3962 } 3963 } 3964 3965 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3966 if (callingUid == Process.SHELL_UID) { 3967 if (userHandle >= 0 3968 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3969 throw new SecurityException("Shell does not have permission to access user " 3970 + userHandle); 3971 } else if (userHandle < 0) { 3972 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3973 + Debug.getCallers(3)); 3974 } 3975 } 3976 } 3977 3978 private BasePermission findPermissionTreeLP(String permName) { 3979 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3980 if (permName.startsWith(bp.name) && 3981 permName.length() > bp.name.length() && 3982 permName.charAt(bp.name.length()) == '.') { 3983 return bp; 3984 } 3985 } 3986 return null; 3987 } 3988 3989 private BasePermission checkPermissionTreeLP(String permName) { 3990 if (permName != null) { 3991 BasePermission bp = findPermissionTreeLP(permName); 3992 if (bp != null) { 3993 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3994 return bp; 3995 } 3996 throw new SecurityException("Calling uid " 3997 + Binder.getCallingUid() 3998 + " is not allowed to add to permission tree " 3999 + bp.name + " owned by uid " + bp.uid); 4000 } 4001 } 4002 throw new SecurityException("No permission tree found for " + permName); 4003 } 4004 4005 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4006 if (s1 == null) { 4007 return s2 == null; 4008 } 4009 if (s2 == null) { 4010 return false; 4011 } 4012 if (s1.getClass() != s2.getClass()) { 4013 return false; 4014 } 4015 return s1.equals(s2); 4016 } 4017 4018 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4019 if (pi1.icon != pi2.icon) return false; 4020 if (pi1.logo != pi2.logo) return false; 4021 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4022 if (!compareStrings(pi1.name, pi2.name)) return false; 4023 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4024 // We'll take care of setting this one. 4025 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4026 // These are not currently stored in settings. 4027 //if (!compareStrings(pi1.group, pi2.group)) return false; 4028 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4029 //if (pi1.labelRes != pi2.labelRes) return false; 4030 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4031 return true; 4032 } 4033 4034 int permissionInfoFootprint(PermissionInfo info) { 4035 int size = info.name.length(); 4036 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4037 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4038 return size; 4039 } 4040 4041 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4042 int size = 0; 4043 for (BasePermission perm : mSettings.mPermissions.values()) { 4044 if (perm.uid == tree.uid) { 4045 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4046 } 4047 } 4048 return size; 4049 } 4050 4051 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4052 // We calculate the max size of permissions defined by this uid and throw 4053 // if that plus the size of 'info' would exceed our stated maximum. 4054 if (tree.uid != Process.SYSTEM_UID) { 4055 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4056 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4057 throw new SecurityException("Permission tree size cap exceeded"); 4058 } 4059 } 4060 } 4061 4062 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4063 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4064 throw new SecurityException("Label must be specified in permission"); 4065 } 4066 BasePermission tree = checkPermissionTreeLP(info.name); 4067 BasePermission bp = mSettings.mPermissions.get(info.name); 4068 boolean added = bp == null; 4069 boolean changed = true; 4070 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4071 if (added) { 4072 enforcePermissionCapLocked(info, tree); 4073 bp = new BasePermission(info.name, tree.sourcePackage, 4074 BasePermission.TYPE_DYNAMIC); 4075 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4076 throw new SecurityException( 4077 "Not allowed to modify non-dynamic permission " 4078 + info.name); 4079 } else { 4080 if (bp.protectionLevel == fixedLevel 4081 && bp.perm.owner.equals(tree.perm.owner) 4082 && bp.uid == tree.uid 4083 && comparePermissionInfos(bp.perm.info, info)) { 4084 changed = false; 4085 } 4086 } 4087 bp.protectionLevel = fixedLevel; 4088 info = new PermissionInfo(info); 4089 info.protectionLevel = fixedLevel; 4090 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4091 bp.perm.info.packageName = tree.perm.info.packageName; 4092 bp.uid = tree.uid; 4093 if (added) { 4094 mSettings.mPermissions.put(info.name, bp); 4095 } 4096 if (changed) { 4097 if (!async) { 4098 mSettings.writeLPr(); 4099 } else { 4100 scheduleWriteSettingsLocked(); 4101 } 4102 } 4103 return added; 4104 } 4105 4106 @Override 4107 public boolean addPermission(PermissionInfo info) { 4108 synchronized (mPackages) { 4109 return addPermissionLocked(info, false); 4110 } 4111 } 4112 4113 @Override 4114 public boolean addPermissionAsync(PermissionInfo info) { 4115 synchronized (mPackages) { 4116 return addPermissionLocked(info, true); 4117 } 4118 } 4119 4120 @Override 4121 public void removePermission(String name) { 4122 synchronized (mPackages) { 4123 checkPermissionTreeLP(name); 4124 BasePermission bp = mSettings.mPermissions.get(name); 4125 if (bp != null) { 4126 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4127 throw new SecurityException( 4128 "Not allowed to modify non-dynamic permission " 4129 + name); 4130 } 4131 mSettings.mPermissions.remove(name); 4132 mSettings.writeLPr(); 4133 } 4134 } 4135 } 4136 4137 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4138 BasePermission bp) { 4139 int index = pkg.requestedPermissions.indexOf(bp.name); 4140 if (index == -1) { 4141 throw new SecurityException("Package " + pkg.packageName 4142 + " has not requested permission " + bp.name); 4143 } 4144 if (!bp.isRuntime() && !bp.isDevelopment()) { 4145 throw new SecurityException("Permission " + bp.name 4146 + " is not a changeable permission type"); 4147 } 4148 } 4149 4150 @Override 4151 public void grantRuntimePermission(String packageName, String name, final int userId) { 4152 if (!sUserManager.exists(userId)) { 4153 Log.e(TAG, "No such user:" + userId); 4154 return; 4155 } 4156 4157 mContext.enforceCallingOrSelfPermission( 4158 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4159 "grantRuntimePermission"); 4160 4161 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4162 true /* requireFullPermission */, true /* checkShell */, 4163 "grantRuntimePermission"); 4164 4165 final int uid; 4166 final SettingBase sb; 4167 4168 synchronized (mPackages) { 4169 final PackageParser.Package pkg = mPackages.get(packageName); 4170 if (pkg == null) { 4171 throw new IllegalArgumentException("Unknown package: " + packageName); 4172 } 4173 4174 final BasePermission bp = mSettings.mPermissions.get(name); 4175 if (bp == null) { 4176 throw new IllegalArgumentException("Unknown permission: " + name); 4177 } 4178 4179 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4180 4181 // If a permission review is required for legacy apps we represent 4182 // their permissions as always granted runtime ones since we need 4183 // to keep the review required permission flag per user while an 4184 // install permission's state is shared across all users. 4185 if (Build.PERMISSIONS_REVIEW_REQUIRED 4186 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4187 && bp.isRuntime()) { 4188 return; 4189 } 4190 4191 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4192 sb = (SettingBase) pkg.mExtras; 4193 if (sb == null) { 4194 throw new IllegalArgumentException("Unknown package: " + packageName); 4195 } 4196 4197 final PermissionsState permissionsState = sb.getPermissionsState(); 4198 4199 final int flags = permissionsState.getPermissionFlags(name, userId); 4200 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4201 throw new SecurityException("Cannot grant system fixed permission " 4202 + name + " for package " + packageName); 4203 } 4204 4205 if (bp.isDevelopment()) { 4206 // Development permissions must be handled specially, since they are not 4207 // normal runtime permissions. For now they apply to all users. 4208 if (permissionsState.grantInstallPermission(bp) != 4209 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4210 scheduleWriteSettingsLocked(); 4211 } 4212 return; 4213 } 4214 4215 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4216 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4217 return; 4218 } 4219 4220 final int result = permissionsState.grantRuntimePermission(bp, userId); 4221 switch (result) { 4222 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4223 return; 4224 } 4225 4226 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4227 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4228 mHandler.post(new Runnable() { 4229 @Override 4230 public void run() { 4231 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4232 } 4233 }); 4234 } 4235 break; 4236 } 4237 4238 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4239 4240 // Not critical if that is lost - app has to request again. 4241 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4242 } 4243 4244 // Only need to do this if user is initialized. Otherwise it's a new user 4245 // and there are no processes running as the user yet and there's no need 4246 // to make an expensive call to remount processes for the changed permissions. 4247 if (READ_EXTERNAL_STORAGE.equals(name) 4248 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4249 final long token = Binder.clearCallingIdentity(); 4250 try { 4251 if (sUserManager.isInitialized(userId)) { 4252 MountServiceInternal mountServiceInternal = LocalServices.getService( 4253 MountServiceInternal.class); 4254 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4255 } 4256 } finally { 4257 Binder.restoreCallingIdentity(token); 4258 } 4259 } 4260 } 4261 4262 @Override 4263 public void revokeRuntimePermission(String packageName, String name, int userId) { 4264 if (!sUserManager.exists(userId)) { 4265 Log.e(TAG, "No such user:" + userId); 4266 return; 4267 } 4268 4269 mContext.enforceCallingOrSelfPermission( 4270 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4271 "revokeRuntimePermission"); 4272 4273 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4274 true /* requireFullPermission */, true /* checkShell */, 4275 "revokeRuntimePermission"); 4276 4277 final int appId; 4278 4279 synchronized (mPackages) { 4280 final PackageParser.Package pkg = mPackages.get(packageName); 4281 if (pkg == null) { 4282 throw new IllegalArgumentException("Unknown package: " + packageName); 4283 } 4284 4285 final BasePermission bp = mSettings.mPermissions.get(name); 4286 if (bp == null) { 4287 throw new IllegalArgumentException("Unknown permission: " + name); 4288 } 4289 4290 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4291 4292 // If a permission review is required for legacy apps we represent 4293 // their permissions as always granted runtime ones since we need 4294 // to keep the review required permission flag per user while an 4295 // install permission's state is shared across all users. 4296 if (Build.PERMISSIONS_REVIEW_REQUIRED 4297 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4298 && bp.isRuntime()) { 4299 return; 4300 } 4301 4302 SettingBase sb = (SettingBase) pkg.mExtras; 4303 if (sb == null) { 4304 throw new IllegalArgumentException("Unknown package: " + packageName); 4305 } 4306 4307 final PermissionsState permissionsState = sb.getPermissionsState(); 4308 4309 final int flags = permissionsState.getPermissionFlags(name, userId); 4310 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4311 throw new SecurityException("Cannot revoke system fixed permission " 4312 + name + " for package " + packageName); 4313 } 4314 4315 if (bp.isDevelopment()) { 4316 // Development permissions must be handled specially, since they are not 4317 // normal runtime permissions. For now they apply to all users. 4318 if (permissionsState.revokeInstallPermission(bp) != 4319 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4320 scheduleWriteSettingsLocked(); 4321 } 4322 return; 4323 } 4324 4325 if (permissionsState.revokeRuntimePermission(bp, userId) == 4326 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4327 return; 4328 } 4329 4330 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4331 4332 // Critical, after this call app should never have the permission. 4333 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4334 4335 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4336 } 4337 4338 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4339 } 4340 4341 @Override 4342 public void resetRuntimePermissions() { 4343 mContext.enforceCallingOrSelfPermission( 4344 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4345 "revokeRuntimePermission"); 4346 4347 int callingUid = Binder.getCallingUid(); 4348 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4349 mContext.enforceCallingOrSelfPermission( 4350 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4351 "resetRuntimePermissions"); 4352 } 4353 4354 synchronized (mPackages) { 4355 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4356 for (int userId : UserManagerService.getInstance().getUserIds()) { 4357 final int packageCount = mPackages.size(); 4358 for (int i = 0; i < packageCount; i++) { 4359 PackageParser.Package pkg = mPackages.valueAt(i); 4360 if (!(pkg.mExtras instanceof PackageSetting)) { 4361 continue; 4362 } 4363 PackageSetting ps = (PackageSetting) pkg.mExtras; 4364 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4365 } 4366 } 4367 } 4368 } 4369 4370 @Override 4371 public int getPermissionFlags(String name, String packageName, int userId) { 4372 if (!sUserManager.exists(userId)) { 4373 return 0; 4374 } 4375 4376 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4377 4378 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4379 true /* requireFullPermission */, false /* checkShell */, 4380 "getPermissionFlags"); 4381 4382 synchronized (mPackages) { 4383 final PackageParser.Package pkg = mPackages.get(packageName); 4384 if (pkg == null) { 4385 return 0; 4386 } 4387 4388 final BasePermission bp = mSettings.mPermissions.get(name); 4389 if (bp == null) { 4390 return 0; 4391 } 4392 4393 SettingBase sb = (SettingBase) pkg.mExtras; 4394 if (sb == null) { 4395 return 0; 4396 } 4397 4398 PermissionsState permissionsState = sb.getPermissionsState(); 4399 return permissionsState.getPermissionFlags(name, userId); 4400 } 4401 } 4402 4403 @Override 4404 public void updatePermissionFlags(String name, String packageName, int flagMask, 4405 int flagValues, int userId) { 4406 if (!sUserManager.exists(userId)) { 4407 return; 4408 } 4409 4410 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4411 4412 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4413 true /* requireFullPermission */, true /* checkShell */, 4414 "updatePermissionFlags"); 4415 4416 // Only the system can change these flags and nothing else. 4417 if (getCallingUid() != Process.SYSTEM_UID) { 4418 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4419 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4420 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4421 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4422 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4423 } 4424 4425 synchronized (mPackages) { 4426 final PackageParser.Package pkg = mPackages.get(packageName); 4427 if (pkg == null) { 4428 throw new IllegalArgumentException("Unknown package: " + packageName); 4429 } 4430 4431 final BasePermission bp = mSettings.mPermissions.get(name); 4432 if (bp == null) { 4433 throw new IllegalArgumentException("Unknown permission: " + name); 4434 } 4435 4436 SettingBase sb = (SettingBase) pkg.mExtras; 4437 if (sb == null) { 4438 throw new IllegalArgumentException("Unknown package: " + packageName); 4439 } 4440 4441 PermissionsState permissionsState = sb.getPermissionsState(); 4442 4443 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4444 4445 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4446 // Install and runtime permissions are stored in different places, 4447 // so figure out what permission changed and persist the change. 4448 if (permissionsState.getInstallPermissionState(name) != null) { 4449 scheduleWriteSettingsLocked(); 4450 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4451 || hadState) { 4452 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4453 } 4454 } 4455 } 4456 } 4457 4458 /** 4459 * Update the permission flags for all packages and runtime permissions of a user in order 4460 * to allow device or profile owner to remove POLICY_FIXED. 4461 */ 4462 @Override 4463 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4464 if (!sUserManager.exists(userId)) { 4465 return; 4466 } 4467 4468 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4469 4470 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4471 true /* requireFullPermission */, true /* checkShell */, 4472 "updatePermissionFlagsForAllApps"); 4473 4474 // Only the system can change system fixed flags. 4475 if (getCallingUid() != Process.SYSTEM_UID) { 4476 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4477 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4478 } 4479 4480 synchronized (mPackages) { 4481 boolean changed = false; 4482 final int packageCount = mPackages.size(); 4483 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4484 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4485 SettingBase sb = (SettingBase) pkg.mExtras; 4486 if (sb == null) { 4487 continue; 4488 } 4489 PermissionsState permissionsState = sb.getPermissionsState(); 4490 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4491 userId, flagMask, flagValues); 4492 } 4493 if (changed) { 4494 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4495 } 4496 } 4497 } 4498 4499 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4500 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4501 != PackageManager.PERMISSION_GRANTED 4502 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4503 != PackageManager.PERMISSION_GRANTED) { 4504 throw new SecurityException(message + " requires " 4505 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4506 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4507 } 4508 } 4509 4510 @Override 4511 public boolean shouldShowRequestPermissionRationale(String permissionName, 4512 String packageName, int userId) { 4513 if (UserHandle.getCallingUserId() != userId) { 4514 mContext.enforceCallingPermission( 4515 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4516 "canShowRequestPermissionRationale for user " + userId); 4517 } 4518 4519 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4520 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4521 return false; 4522 } 4523 4524 if (checkPermission(permissionName, packageName, userId) 4525 == PackageManager.PERMISSION_GRANTED) { 4526 return false; 4527 } 4528 4529 final int flags; 4530 4531 final long identity = Binder.clearCallingIdentity(); 4532 try { 4533 flags = getPermissionFlags(permissionName, 4534 packageName, userId); 4535 } finally { 4536 Binder.restoreCallingIdentity(identity); 4537 } 4538 4539 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4540 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4541 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4542 4543 if ((flags & fixedFlags) != 0) { 4544 return false; 4545 } 4546 4547 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4548 } 4549 4550 @Override 4551 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4552 mContext.enforceCallingOrSelfPermission( 4553 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4554 "addOnPermissionsChangeListener"); 4555 4556 synchronized (mPackages) { 4557 mOnPermissionChangeListeners.addListenerLocked(listener); 4558 } 4559 } 4560 4561 @Override 4562 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4563 synchronized (mPackages) { 4564 mOnPermissionChangeListeners.removeListenerLocked(listener); 4565 } 4566 } 4567 4568 @Override 4569 public boolean isProtectedBroadcast(String actionName) { 4570 synchronized (mPackages) { 4571 if (mProtectedBroadcasts.contains(actionName)) { 4572 return true; 4573 } else if (actionName != null) { 4574 // TODO: remove these terrible hacks 4575 if (actionName.startsWith("android.net.netmon.lingerExpired") 4576 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4577 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4578 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4579 return true; 4580 } 4581 } 4582 } 4583 return false; 4584 } 4585 4586 @Override 4587 public int checkSignatures(String pkg1, String pkg2) { 4588 synchronized (mPackages) { 4589 final PackageParser.Package p1 = mPackages.get(pkg1); 4590 final PackageParser.Package p2 = mPackages.get(pkg2); 4591 if (p1 == null || p1.mExtras == null 4592 || p2 == null || p2.mExtras == null) { 4593 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4594 } 4595 return compareSignatures(p1.mSignatures, p2.mSignatures); 4596 } 4597 } 4598 4599 @Override 4600 public int checkUidSignatures(int uid1, int uid2) { 4601 // Map to base uids. 4602 uid1 = UserHandle.getAppId(uid1); 4603 uid2 = UserHandle.getAppId(uid2); 4604 // reader 4605 synchronized (mPackages) { 4606 Signature[] s1; 4607 Signature[] s2; 4608 Object obj = mSettings.getUserIdLPr(uid1); 4609 if (obj != null) { 4610 if (obj instanceof SharedUserSetting) { 4611 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4612 } else if (obj instanceof PackageSetting) { 4613 s1 = ((PackageSetting)obj).signatures.mSignatures; 4614 } else { 4615 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4616 } 4617 } else { 4618 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4619 } 4620 obj = mSettings.getUserIdLPr(uid2); 4621 if (obj != null) { 4622 if (obj instanceof SharedUserSetting) { 4623 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4624 } else if (obj instanceof PackageSetting) { 4625 s2 = ((PackageSetting)obj).signatures.mSignatures; 4626 } else { 4627 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4628 } 4629 } else { 4630 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4631 } 4632 return compareSignatures(s1, s2); 4633 } 4634 } 4635 4636 /** 4637 * This method should typically only be used when granting or revoking 4638 * permissions, since the app may immediately restart after this call. 4639 * <p> 4640 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4641 * guard your work against the app being relaunched. 4642 */ 4643 private void killUid(int appId, int userId, String reason) { 4644 final long identity = Binder.clearCallingIdentity(); 4645 try { 4646 IActivityManager am = ActivityManagerNative.getDefault(); 4647 if (am != null) { 4648 try { 4649 am.killUid(appId, userId, reason); 4650 } catch (RemoteException e) { 4651 /* ignore - same process */ 4652 } 4653 } 4654 } finally { 4655 Binder.restoreCallingIdentity(identity); 4656 } 4657 } 4658 4659 /** 4660 * Compares two sets of signatures. Returns: 4661 * <br /> 4662 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4663 * <br /> 4664 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4665 * <br /> 4666 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4667 * <br /> 4668 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4669 * <br /> 4670 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4671 */ 4672 static int compareSignatures(Signature[] s1, Signature[] s2) { 4673 if (s1 == null) { 4674 return s2 == null 4675 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4676 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4677 } 4678 4679 if (s2 == null) { 4680 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4681 } 4682 4683 if (s1.length != s2.length) { 4684 return PackageManager.SIGNATURE_NO_MATCH; 4685 } 4686 4687 // Since both signature sets are of size 1, we can compare without HashSets. 4688 if (s1.length == 1) { 4689 return s1[0].equals(s2[0]) ? 4690 PackageManager.SIGNATURE_MATCH : 4691 PackageManager.SIGNATURE_NO_MATCH; 4692 } 4693 4694 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4695 for (Signature sig : s1) { 4696 set1.add(sig); 4697 } 4698 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4699 for (Signature sig : s2) { 4700 set2.add(sig); 4701 } 4702 // Make sure s2 contains all signatures in s1. 4703 if (set1.equals(set2)) { 4704 return PackageManager.SIGNATURE_MATCH; 4705 } 4706 return PackageManager.SIGNATURE_NO_MATCH; 4707 } 4708 4709 /** 4710 * If the database version for this type of package (internal storage or 4711 * external storage) is less than the version where package signatures 4712 * were updated, return true. 4713 */ 4714 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4715 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4716 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4717 } 4718 4719 /** 4720 * Used for backward compatibility to make sure any packages with 4721 * certificate chains get upgraded to the new style. {@code existingSigs} 4722 * will be in the old format (since they were stored on disk from before the 4723 * system upgrade) and {@code scannedSigs} will be in the newer format. 4724 */ 4725 private int compareSignaturesCompat(PackageSignatures existingSigs, 4726 PackageParser.Package scannedPkg) { 4727 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4728 return PackageManager.SIGNATURE_NO_MATCH; 4729 } 4730 4731 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4732 for (Signature sig : existingSigs.mSignatures) { 4733 existingSet.add(sig); 4734 } 4735 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4736 for (Signature sig : scannedPkg.mSignatures) { 4737 try { 4738 Signature[] chainSignatures = sig.getChainSignatures(); 4739 for (Signature chainSig : chainSignatures) { 4740 scannedCompatSet.add(chainSig); 4741 } 4742 } catch (CertificateEncodingException e) { 4743 scannedCompatSet.add(sig); 4744 } 4745 } 4746 /* 4747 * Make sure the expanded scanned set contains all signatures in the 4748 * existing one. 4749 */ 4750 if (scannedCompatSet.equals(existingSet)) { 4751 // Migrate the old signatures to the new scheme. 4752 existingSigs.assignSignatures(scannedPkg.mSignatures); 4753 // The new KeySets will be re-added later in the scanning process. 4754 synchronized (mPackages) { 4755 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4756 } 4757 return PackageManager.SIGNATURE_MATCH; 4758 } 4759 return PackageManager.SIGNATURE_NO_MATCH; 4760 } 4761 4762 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4763 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4764 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4765 } 4766 4767 private int compareSignaturesRecover(PackageSignatures existingSigs, 4768 PackageParser.Package scannedPkg) { 4769 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4770 return PackageManager.SIGNATURE_NO_MATCH; 4771 } 4772 4773 String msg = null; 4774 try { 4775 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4776 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4777 + scannedPkg.packageName); 4778 return PackageManager.SIGNATURE_MATCH; 4779 } 4780 } catch (CertificateException e) { 4781 msg = e.getMessage(); 4782 } 4783 4784 logCriticalInfo(Log.INFO, 4785 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4786 return PackageManager.SIGNATURE_NO_MATCH; 4787 } 4788 4789 @Override 4790 public List<String> getAllPackages() { 4791 synchronized (mPackages) { 4792 return new ArrayList<String>(mPackages.keySet()); 4793 } 4794 } 4795 4796 @Override 4797 public String[] getPackagesForUid(int uid) { 4798 uid = UserHandle.getAppId(uid); 4799 // reader 4800 synchronized (mPackages) { 4801 Object obj = mSettings.getUserIdLPr(uid); 4802 if (obj instanceof SharedUserSetting) { 4803 final SharedUserSetting sus = (SharedUserSetting) obj; 4804 final int N = sus.packages.size(); 4805 final String[] res = new String[N]; 4806 for (int i = 0; i < N; i++) { 4807 res[i] = sus.packages.valueAt(i).name; 4808 } 4809 return res; 4810 } else if (obj instanceof PackageSetting) { 4811 final PackageSetting ps = (PackageSetting) obj; 4812 return new String[] { ps.name }; 4813 } 4814 } 4815 return null; 4816 } 4817 4818 @Override 4819 public String getNameForUid(int uid) { 4820 // reader 4821 synchronized (mPackages) { 4822 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4823 if (obj instanceof SharedUserSetting) { 4824 final SharedUserSetting sus = (SharedUserSetting) obj; 4825 return sus.name + ":" + sus.userId; 4826 } else if (obj instanceof PackageSetting) { 4827 final PackageSetting ps = (PackageSetting) obj; 4828 return ps.name; 4829 } 4830 } 4831 return null; 4832 } 4833 4834 @Override 4835 public int getUidForSharedUser(String sharedUserName) { 4836 if(sharedUserName == null) { 4837 return -1; 4838 } 4839 // reader 4840 synchronized (mPackages) { 4841 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4842 if (suid == null) { 4843 return -1; 4844 } 4845 return suid.userId; 4846 } 4847 } 4848 4849 @Override 4850 public int getFlagsForUid(int uid) { 4851 synchronized (mPackages) { 4852 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4853 if (obj instanceof SharedUserSetting) { 4854 final SharedUserSetting sus = (SharedUserSetting) obj; 4855 return sus.pkgFlags; 4856 } else if (obj instanceof PackageSetting) { 4857 final PackageSetting ps = (PackageSetting) obj; 4858 return ps.pkgFlags; 4859 } 4860 } 4861 return 0; 4862 } 4863 4864 @Override 4865 public int getPrivateFlagsForUid(int uid) { 4866 synchronized (mPackages) { 4867 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4868 if (obj instanceof SharedUserSetting) { 4869 final SharedUserSetting sus = (SharedUserSetting) obj; 4870 return sus.pkgPrivateFlags; 4871 } else if (obj instanceof PackageSetting) { 4872 final PackageSetting ps = (PackageSetting) obj; 4873 return ps.pkgPrivateFlags; 4874 } 4875 } 4876 return 0; 4877 } 4878 4879 @Override 4880 public boolean isUidPrivileged(int uid) { 4881 uid = UserHandle.getAppId(uid); 4882 // reader 4883 synchronized (mPackages) { 4884 Object obj = mSettings.getUserIdLPr(uid); 4885 if (obj instanceof SharedUserSetting) { 4886 final SharedUserSetting sus = (SharedUserSetting) obj; 4887 final Iterator<PackageSetting> it = sus.packages.iterator(); 4888 while (it.hasNext()) { 4889 if (it.next().isPrivileged()) { 4890 return true; 4891 } 4892 } 4893 } else if (obj instanceof PackageSetting) { 4894 final PackageSetting ps = (PackageSetting) obj; 4895 return ps.isPrivileged(); 4896 } 4897 } 4898 return false; 4899 } 4900 4901 @Override 4902 public String[] getAppOpPermissionPackages(String permissionName) { 4903 synchronized (mPackages) { 4904 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4905 if (pkgs == null) { 4906 return null; 4907 } 4908 return pkgs.toArray(new String[pkgs.size()]); 4909 } 4910 } 4911 4912 @Override 4913 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4914 int flags, int userId) { 4915 try { 4916 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4917 4918 if (!sUserManager.exists(userId)) return null; 4919 flags = updateFlagsForResolve(flags, userId, intent); 4920 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4921 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4922 4923 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4924 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4925 flags, userId); 4926 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4927 4928 final ResolveInfo bestChoice = 4929 chooseBestActivity(intent, resolvedType, flags, query, userId); 4930 4931 if (isEphemeralAllowed(intent, query, userId)) { 4932 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4933 final EphemeralResolveInfo ai = 4934 getEphemeralResolveInfo(intent, resolvedType, userId); 4935 if (ai != null) { 4936 if (DEBUG_EPHEMERAL) { 4937 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4938 } 4939 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4940 bestChoice.ephemeralResolveInfo = ai; 4941 } 4942 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4943 } 4944 return bestChoice; 4945 } finally { 4946 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4947 } 4948 } 4949 4950 @Override 4951 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4952 IntentFilter filter, int match, ComponentName activity) { 4953 final int userId = UserHandle.getCallingUserId(); 4954 if (DEBUG_PREFERRED) { 4955 Log.v(TAG, "setLastChosenActivity intent=" + intent 4956 + " resolvedType=" + resolvedType 4957 + " flags=" + flags 4958 + " filter=" + filter 4959 + " match=" + match 4960 + " activity=" + activity); 4961 filter.dump(new PrintStreamPrinter(System.out), " "); 4962 } 4963 intent.setComponent(null); 4964 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4965 userId); 4966 // Find any earlier preferred or last chosen entries and nuke them 4967 findPreferredActivity(intent, resolvedType, 4968 flags, query, 0, false, true, false, userId); 4969 // Add the new activity as the last chosen for this filter 4970 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4971 "Setting last chosen"); 4972 } 4973 4974 @Override 4975 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4976 final int userId = UserHandle.getCallingUserId(); 4977 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4978 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4979 userId); 4980 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4981 false, false, false, userId); 4982 } 4983 4984 4985 private boolean isEphemeralAllowed( 4986 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4987 // Short circuit and return early if possible. 4988 if (DISABLE_EPHEMERAL_APPS) { 4989 return false; 4990 } 4991 final int callingUser = UserHandle.getCallingUserId(); 4992 if (callingUser != UserHandle.USER_SYSTEM) { 4993 return false; 4994 } 4995 if (mEphemeralResolverConnection == null) { 4996 return false; 4997 } 4998 if (intent.getComponent() != null) { 4999 return false; 5000 } 5001 if (intent.getPackage() != null) { 5002 return false; 5003 } 5004 final boolean isWebUri = hasWebURI(intent); 5005 if (!isWebUri) { 5006 return false; 5007 } 5008 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5009 synchronized (mPackages) { 5010 final int count = resolvedActivites.size(); 5011 for (int n = 0; n < count; n++) { 5012 ResolveInfo info = resolvedActivites.get(n); 5013 String packageName = info.activityInfo.packageName; 5014 PackageSetting ps = mSettings.mPackages.get(packageName); 5015 if (ps != null) { 5016 // Try to get the status from User settings first 5017 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5018 int status = (int) (packedStatus >> 32); 5019 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5020 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5021 if (DEBUG_EPHEMERAL) { 5022 Slog.v(TAG, "DENY ephemeral apps;" 5023 + " pkg: " + packageName + ", status: " + status); 5024 } 5025 return false; 5026 } 5027 } 5028 } 5029 } 5030 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5031 return true; 5032 } 5033 5034 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 5035 int userId) { 5036 final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(), 5037 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 5038 final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(), 5039 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 5040 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 5041 ephemeralPrefixCount); 5042 final int[] shaPrefix = digest.getDigestPrefix(); 5043 final byte[][] digestBytes = digest.getDigestBytes(); 5044 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 5045 mEphemeralResolverConnection.getEphemeralResolveInfoList( 5046 shaPrefix, ephemeralPrefixMask); 5047 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 5048 // No hash prefix match; there are no ephemeral apps for this domain. 5049 return null; 5050 } 5051 5052 // Go in reverse order so we match the narrowest scope first. 5053 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 5054 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 5055 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 5056 continue; 5057 } 5058 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 5059 // No filters; this should never happen. 5060 if (filters.isEmpty()) { 5061 continue; 5062 } 5063 // We have a domain match; resolve the filters to see if anything matches. 5064 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 5065 for (int j = filters.size() - 1; j >= 0; --j) { 5066 final EphemeralResolveIntentInfo intentInfo = 5067 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 5068 ephemeralResolver.addFilter(intentInfo); 5069 } 5070 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 5071 intent, resolvedType, false /*defaultOnly*/, userId); 5072 if (!matchedResolveInfoList.isEmpty()) { 5073 return matchedResolveInfoList.get(0); 5074 } 5075 } 5076 } 5077 // Hash or filter mis-match; no ephemeral apps for this domain. 5078 return null; 5079 } 5080 5081 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5082 int flags, List<ResolveInfo> query, int userId) { 5083 if (query != null) { 5084 final int N = query.size(); 5085 if (N == 1) { 5086 return query.get(0); 5087 } else if (N > 1) { 5088 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5089 // If there is more than one activity with the same priority, 5090 // then let the user decide between them. 5091 ResolveInfo r0 = query.get(0); 5092 ResolveInfo r1 = query.get(1); 5093 if (DEBUG_INTENT_MATCHING || debug) { 5094 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5095 + r1.activityInfo.name + "=" + r1.priority); 5096 } 5097 // If the first activity has a higher priority, or a different 5098 // default, then it is always desirable to pick it. 5099 if (r0.priority != r1.priority 5100 || r0.preferredOrder != r1.preferredOrder 5101 || r0.isDefault != r1.isDefault) { 5102 return query.get(0); 5103 } 5104 // If we have saved a preference for a preferred activity for 5105 // this Intent, use that. 5106 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5107 flags, query, r0.priority, true, false, debug, userId); 5108 if (ri != null) { 5109 return ri; 5110 } 5111 ri = new ResolveInfo(mResolveInfo); 5112 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5113 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5114 // If all of the options come from the same package, show the application's 5115 // label and icon instead of the generic resolver's. 5116 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5117 // and then throw away the ResolveInfo itself, meaning that the caller loses 5118 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5119 // a fallback for this case; we only set the target package's resources on 5120 // the ResolveInfo, not the ActivityInfo. 5121 final String intentPackage = intent.getPackage(); 5122 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5123 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5124 ri.resolvePackageName = intentPackage; 5125 if (userNeedsBadging(userId)) { 5126 ri.noResourceId = true; 5127 } else { 5128 ri.icon = appi.icon; 5129 } 5130 ri.iconResourceId = appi.icon; 5131 ri.labelRes = appi.labelRes; 5132 } 5133 ri.activityInfo.applicationInfo = new ApplicationInfo( 5134 ri.activityInfo.applicationInfo); 5135 if (userId != 0) { 5136 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5137 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5138 } 5139 // Make sure that the resolver is displayable in car mode 5140 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5141 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5142 return ri; 5143 } 5144 } 5145 return null; 5146 } 5147 5148 /** 5149 * Return true if the given list is not empty and all of its contents have 5150 * an activityInfo with the given package name. 5151 */ 5152 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5153 if (ArrayUtils.isEmpty(list)) { 5154 return false; 5155 } 5156 for (int i = 0, N = list.size(); i < N; i++) { 5157 final ResolveInfo ri = list.get(i); 5158 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5159 if (ai == null || !packageName.equals(ai.packageName)) { 5160 return false; 5161 } 5162 } 5163 return true; 5164 } 5165 5166 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5167 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5168 final int N = query.size(); 5169 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5170 .get(userId); 5171 // Get the list of persistent preferred activities that handle the intent 5172 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5173 List<PersistentPreferredActivity> pprefs = ppir != null 5174 ? ppir.queryIntent(intent, resolvedType, 5175 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5176 : null; 5177 if (pprefs != null && pprefs.size() > 0) { 5178 final int M = pprefs.size(); 5179 for (int i=0; i<M; i++) { 5180 final PersistentPreferredActivity ppa = pprefs.get(i); 5181 if (DEBUG_PREFERRED || debug) { 5182 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5183 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5184 + "\n component=" + ppa.mComponent); 5185 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5186 } 5187 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5188 flags | MATCH_DISABLED_COMPONENTS, userId); 5189 if (DEBUG_PREFERRED || debug) { 5190 Slog.v(TAG, "Found persistent preferred activity:"); 5191 if (ai != null) { 5192 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5193 } else { 5194 Slog.v(TAG, " null"); 5195 } 5196 } 5197 if (ai == null) { 5198 // This previously registered persistent preferred activity 5199 // component is no longer known. Ignore it and do NOT remove it. 5200 continue; 5201 } 5202 for (int j=0; j<N; j++) { 5203 final ResolveInfo ri = query.get(j); 5204 if (!ri.activityInfo.applicationInfo.packageName 5205 .equals(ai.applicationInfo.packageName)) { 5206 continue; 5207 } 5208 if (!ri.activityInfo.name.equals(ai.name)) { 5209 continue; 5210 } 5211 // Found a persistent preference that can handle the intent. 5212 if (DEBUG_PREFERRED || debug) { 5213 Slog.v(TAG, "Returning persistent preferred activity: " + 5214 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5215 } 5216 return ri; 5217 } 5218 } 5219 } 5220 return null; 5221 } 5222 5223 // TODO: handle preferred activities missing while user has amnesia 5224 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5225 List<ResolveInfo> query, int priority, boolean always, 5226 boolean removeMatches, boolean debug, int userId) { 5227 if (!sUserManager.exists(userId)) return null; 5228 flags = updateFlagsForResolve(flags, userId, intent); 5229 // writer 5230 synchronized (mPackages) { 5231 if (intent.getSelector() != null) { 5232 intent = intent.getSelector(); 5233 } 5234 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5235 5236 // Try to find a matching persistent preferred activity. 5237 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5238 debug, userId); 5239 5240 // If a persistent preferred activity matched, use it. 5241 if (pri != null) { 5242 return pri; 5243 } 5244 5245 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5246 // Get the list of preferred activities that handle the intent 5247 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5248 List<PreferredActivity> prefs = pir != null 5249 ? pir.queryIntent(intent, resolvedType, 5250 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5251 : null; 5252 if (prefs != null && prefs.size() > 0) { 5253 boolean changed = false; 5254 try { 5255 // First figure out how good the original match set is. 5256 // We will only allow preferred activities that came 5257 // from the same match quality. 5258 int match = 0; 5259 5260 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5261 5262 final int N = query.size(); 5263 for (int j=0; j<N; j++) { 5264 final ResolveInfo ri = query.get(j); 5265 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5266 + ": 0x" + Integer.toHexString(match)); 5267 if (ri.match > match) { 5268 match = ri.match; 5269 } 5270 } 5271 5272 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5273 + Integer.toHexString(match)); 5274 5275 match &= IntentFilter.MATCH_CATEGORY_MASK; 5276 final int M = prefs.size(); 5277 for (int i=0; i<M; i++) { 5278 final PreferredActivity pa = prefs.get(i); 5279 if (DEBUG_PREFERRED || debug) { 5280 Slog.v(TAG, "Checking PreferredActivity ds=" 5281 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5282 + "\n component=" + pa.mPref.mComponent); 5283 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5284 } 5285 if (pa.mPref.mMatch != match) { 5286 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5287 + Integer.toHexString(pa.mPref.mMatch)); 5288 continue; 5289 } 5290 // If it's not an "always" type preferred activity and that's what we're 5291 // looking for, skip it. 5292 if (always && !pa.mPref.mAlways) { 5293 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5294 continue; 5295 } 5296 final ActivityInfo ai = getActivityInfo( 5297 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5298 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5299 userId); 5300 if (DEBUG_PREFERRED || debug) { 5301 Slog.v(TAG, "Found preferred activity:"); 5302 if (ai != null) { 5303 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5304 } else { 5305 Slog.v(TAG, " null"); 5306 } 5307 } 5308 if (ai == null) { 5309 // This previously registered preferred activity 5310 // component is no longer known. Most likely an update 5311 // to the app was installed and in the new version this 5312 // component no longer exists. Clean it up by removing 5313 // it from the preferred activities list, and skip it. 5314 Slog.w(TAG, "Removing dangling preferred activity: " 5315 + pa.mPref.mComponent); 5316 pir.removeFilter(pa); 5317 changed = true; 5318 continue; 5319 } 5320 for (int j=0; j<N; j++) { 5321 final ResolveInfo ri = query.get(j); 5322 if (!ri.activityInfo.applicationInfo.packageName 5323 .equals(ai.applicationInfo.packageName)) { 5324 continue; 5325 } 5326 if (!ri.activityInfo.name.equals(ai.name)) { 5327 continue; 5328 } 5329 5330 if (removeMatches) { 5331 pir.removeFilter(pa); 5332 changed = true; 5333 if (DEBUG_PREFERRED) { 5334 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5335 } 5336 break; 5337 } 5338 5339 // Okay we found a previously set preferred or last chosen app. 5340 // If the result set is different from when this 5341 // was created, we need to clear it and re-ask the 5342 // user their preference, if we're looking for an "always" type entry. 5343 if (always && !pa.mPref.sameSet(query)) { 5344 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5345 + intent + " type " + resolvedType); 5346 if (DEBUG_PREFERRED) { 5347 Slog.v(TAG, "Removing preferred activity since set changed " 5348 + pa.mPref.mComponent); 5349 } 5350 pir.removeFilter(pa); 5351 // Re-add the filter as a "last chosen" entry (!always) 5352 PreferredActivity lastChosen = new PreferredActivity( 5353 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5354 pir.addFilter(lastChosen); 5355 changed = true; 5356 return null; 5357 } 5358 5359 // Yay! Either the set matched or we're looking for the last chosen 5360 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5361 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5362 return ri; 5363 } 5364 } 5365 } finally { 5366 if (changed) { 5367 if (DEBUG_PREFERRED) { 5368 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5369 } 5370 scheduleWritePackageRestrictionsLocked(userId); 5371 } 5372 } 5373 } 5374 } 5375 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5376 return null; 5377 } 5378 5379 /* 5380 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5381 */ 5382 @Override 5383 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5384 int targetUserId) { 5385 mContext.enforceCallingOrSelfPermission( 5386 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5387 List<CrossProfileIntentFilter> matches = 5388 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5389 if (matches != null) { 5390 int size = matches.size(); 5391 for (int i = 0; i < size; i++) { 5392 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5393 } 5394 } 5395 if (hasWebURI(intent)) { 5396 // cross-profile app linking works only towards the parent. 5397 final UserInfo parent = getProfileParent(sourceUserId); 5398 synchronized(mPackages) { 5399 int flags = updateFlagsForResolve(0, parent.id, intent); 5400 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5401 intent, resolvedType, flags, sourceUserId, parent.id); 5402 return xpDomainInfo != null; 5403 } 5404 } 5405 return false; 5406 } 5407 5408 private UserInfo getProfileParent(int userId) { 5409 final long identity = Binder.clearCallingIdentity(); 5410 try { 5411 return sUserManager.getProfileParent(userId); 5412 } finally { 5413 Binder.restoreCallingIdentity(identity); 5414 } 5415 } 5416 5417 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5418 String resolvedType, int userId) { 5419 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5420 if (resolver != null) { 5421 return resolver.queryIntent(intent, resolvedType, false, userId); 5422 } 5423 return null; 5424 } 5425 5426 @Override 5427 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5428 String resolvedType, int flags, int userId) { 5429 try { 5430 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5431 5432 return new ParceledListSlice<>( 5433 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5434 } finally { 5435 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5436 } 5437 } 5438 5439 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5440 String resolvedType, int flags, int userId) { 5441 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5442 flags = updateFlagsForResolve(flags, userId, intent); 5443 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5444 false /* requireFullPermission */, false /* checkShell */, 5445 "query intent activities"); 5446 ComponentName comp = intent.getComponent(); 5447 if (comp == null) { 5448 if (intent.getSelector() != null) { 5449 intent = intent.getSelector(); 5450 comp = intent.getComponent(); 5451 } 5452 } 5453 5454 if (comp != null) { 5455 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5456 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5457 if (ai != null) { 5458 final ResolveInfo ri = new ResolveInfo(); 5459 ri.activityInfo = ai; 5460 list.add(ri); 5461 } 5462 return list; 5463 } 5464 5465 // reader 5466 synchronized (mPackages) { 5467 final String pkgName = intent.getPackage(); 5468 if (pkgName == null) { 5469 List<CrossProfileIntentFilter> matchingFilters = 5470 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5471 // Check for results that need to skip the current profile. 5472 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5473 resolvedType, flags, userId); 5474 if (xpResolveInfo != null) { 5475 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5476 result.add(xpResolveInfo); 5477 return filterIfNotSystemUser(result, userId); 5478 } 5479 5480 // Check for results in the current profile. 5481 List<ResolveInfo> result = mActivities.queryIntent( 5482 intent, resolvedType, flags, userId); 5483 result = filterIfNotSystemUser(result, userId); 5484 5485 // Check for cross profile results. 5486 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5487 xpResolveInfo = queryCrossProfileIntents( 5488 matchingFilters, intent, resolvedType, flags, userId, 5489 hasNonNegativePriorityResult); 5490 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5491 boolean isVisibleToUser = filterIfNotSystemUser( 5492 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5493 if (isVisibleToUser) { 5494 result.add(xpResolveInfo); 5495 Collections.sort(result, mResolvePrioritySorter); 5496 } 5497 } 5498 if (hasWebURI(intent)) { 5499 CrossProfileDomainInfo xpDomainInfo = null; 5500 final UserInfo parent = getProfileParent(userId); 5501 if (parent != null) { 5502 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5503 flags, userId, parent.id); 5504 } 5505 if (xpDomainInfo != null) { 5506 if (xpResolveInfo != null) { 5507 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5508 // in the result. 5509 result.remove(xpResolveInfo); 5510 } 5511 if (result.size() == 0) { 5512 result.add(xpDomainInfo.resolveInfo); 5513 return result; 5514 } 5515 } else if (result.size() <= 1) { 5516 return result; 5517 } 5518 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5519 xpDomainInfo, userId); 5520 Collections.sort(result, mResolvePrioritySorter); 5521 } 5522 return result; 5523 } 5524 final PackageParser.Package pkg = mPackages.get(pkgName); 5525 if (pkg != null) { 5526 return filterIfNotSystemUser( 5527 mActivities.queryIntentForPackage( 5528 intent, resolvedType, flags, pkg.activities, userId), 5529 userId); 5530 } 5531 return new ArrayList<ResolveInfo>(); 5532 } 5533 } 5534 5535 private static class CrossProfileDomainInfo { 5536 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5537 ResolveInfo resolveInfo; 5538 /* Best domain verification status of the activities found in the other profile */ 5539 int bestDomainVerificationStatus; 5540 } 5541 5542 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5543 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5544 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5545 sourceUserId)) { 5546 return null; 5547 } 5548 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5549 resolvedType, flags, parentUserId); 5550 5551 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5552 return null; 5553 } 5554 CrossProfileDomainInfo result = null; 5555 int size = resultTargetUser.size(); 5556 for (int i = 0; i < size; i++) { 5557 ResolveInfo riTargetUser = resultTargetUser.get(i); 5558 // Intent filter verification is only for filters that specify a host. So don't return 5559 // those that handle all web uris. 5560 if (riTargetUser.handleAllWebDataURI) { 5561 continue; 5562 } 5563 String packageName = riTargetUser.activityInfo.packageName; 5564 PackageSetting ps = mSettings.mPackages.get(packageName); 5565 if (ps == null) { 5566 continue; 5567 } 5568 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5569 int status = (int)(verificationState >> 32); 5570 if (result == null) { 5571 result = new CrossProfileDomainInfo(); 5572 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5573 sourceUserId, parentUserId); 5574 result.bestDomainVerificationStatus = status; 5575 } else { 5576 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5577 result.bestDomainVerificationStatus); 5578 } 5579 } 5580 // Don't consider matches with status NEVER across profiles. 5581 if (result != null && result.bestDomainVerificationStatus 5582 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5583 return null; 5584 } 5585 return result; 5586 } 5587 5588 /** 5589 * Verification statuses are ordered from the worse to the best, except for 5590 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5591 */ 5592 private int bestDomainVerificationStatus(int status1, int status2) { 5593 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5594 return status2; 5595 } 5596 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5597 return status1; 5598 } 5599 return (int) MathUtils.max(status1, status2); 5600 } 5601 5602 private boolean isUserEnabled(int userId) { 5603 long callingId = Binder.clearCallingIdentity(); 5604 try { 5605 UserInfo userInfo = sUserManager.getUserInfo(userId); 5606 return userInfo != null && userInfo.isEnabled(); 5607 } finally { 5608 Binder.restoreCallingIdentity(callingId); 5609 } 5610 } 5611 5612 /** 5613 * Filter out activities with systemUserOnly flag set, when current user is not System. 5614 * 5615 * @return filtered list 5616 */ 5617 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5618 if (userId == UserHandle.USER_SYSTEM) { 5619 return resolveInfos; 5620 } 5621 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5622 ResolveInfo info = resolveInfos.get(i); 5623 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5624 resolveInfos.remove(i); 5625 } 5626 } 5627 return resolveInfos; 5628 } 5629 5630 /** 5631 * @param resolveInfos list of resolve infos in descending priority order 5632 * @return if the list contains a resolve info with non-negative priority 5633 */ 5634 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5635 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5636 } 5637 5638 private static boolean hasWebURI(Intent intent) { 5639 if (intent.getData() == null) { 5640 return false; 5641 } 5642 final String scheme = intent.getScheme(); 5643 if (TextUtils.isEmpty(scheme)) { 5644 return false; 5645 } 5646 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5647 } 5648 5649 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5650 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5651 int userId) { 5652 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5653 5654 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5655 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5656 candidates.size()); 5657 } 5658 5659 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5660 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5661 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5662 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5663 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5664 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5665 5666 synchronized (mPackages) { 5667 final int count = candidates.size(); 5668 // First, try to use linked apps. Partition the candidates into four lists: 5669 // one for the final results, one for the "do not use ever", one for "undefined status" 5670 // and finally one for "browser app type". 5671 for (int n=0; n<count; n++) { 5672 ResolveInfo info = candidates.get(n); 5673 String packageName = info.activityInfo.packageName; 5674 PackageSetting ps = mSettings.mPackages.get(packageName); 5675 if (ps != null) { 5676 // Add to the special match all list (Browser use case) 5677 if (info.handleAllWebDataURI) { 5678 matchAllList.add(info); 5679 continue; 5680 } 5681 // Try to get the status from User settings first 5682 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5683 int status = (int)(packedStatus >> 32); 5684 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5685 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5686 if (DEBUG_DOMAIN_VERIFICATION) { 5687 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5688 + " : linkgen=" + linkGeneration); 5689 } 5690 // Use link-enabled generation as preferredOrder, i.e. 5691 // prefer newly-enabled over earlier-enabled. 5692 info.preferredOrder = linkGeneration; 5693 alwaysList.add(info); 5694 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5695 if (DEBUG_DOMAIN_VERIFICATION) { 5696 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5697 } 5698 neverList.add(info); 5699 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5700 if (DEBUG_DOMAIN_VERIFICATION) { 5701 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5702 } 5703 alwaysAskList.add(info); 5704 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5705 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5706 if (DEBUG_DOMAIN_VERIFICATION) { 5707 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5708 } 5709 undefinedList.add(info); 5710 } 5711 } 5712 } 5713 5714 // We'll want to include browser possibilities in a few cases 5715 boolean includeBrowser = false; 5716 5717 // First try to add the "always" resolution(s) for the current user, if any 5718 if (alwaysList.size() > 0) { 5719 result.addAll(alwaysList); 5720 } else { 5721 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5722 result.addAll(undefinedList); 5723 // Maybe add one for the other profile. 5724 if (xpDomainInfo != null && ( 5725 xpDomainInfo.bestDomainVerificationStatus 5726 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5727 result.add(xpDomainInfo.resolveInfo); 5728 } 5729 includeBrowser = true; 5730 } 5731 5732 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5733 // If there were 'always' entries their preferred order has been set, so we also 5734 // back that off to make the alternatives equivalent 5735 if (alwaysAskList.size() > 0) { 5736 for (ResolveInfo i : result) { 5737 i.preferredOrder = 0; 5738 } 5739 result.addAll(alwaysAskList); 5740 includeBrowser = true; 5741 } 5742 5743 if (includeBrowser) { 5744 // Also add browsers (all of them or only the default one) 5745 if (DEBUG_DOMAIN_VERIFICATION) { 5746 Slog.v(TAG, " ...including browsers in candidate set"); 5747 } 5748 if ((matchFlags & MATCH_ALL) != 0) { 5749 result.addAll(matchAllList); 5750 } else { 5751 // Browser/generic handling case. If there's a default browser, go straight 5752 // to that (but only if there is no other higher-priority match). 5753 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5754 int maxMatchPrio = 0; 5755 ResolveInfo defaultBrowserMatch = null; 5756 final int numCandidates = matchAllList.size(); 5757 for (int n = 0; n < numCandidates; n++) { 5758 ResolveInfo info = matchAllList.get(n); 5759 // track the highest overall match priority... 5760 if (info.priority > maxMatchPrio) { 5761 maxMatchPrio = info.priority; 5762 } 5763 // ...and the highest-priority default browser match 5764 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5765 if (defaultBrowserMatch == null 5766 || (defaultBrowserMatch.priority < info.priority)) { 5767 if (debug) { 5768 Slog.v(TAG, "Considering default browser match " + info); 5769 } 5770 defaultBrowserMatch = info; 5771 } 5772 } 5773 } 5774 if (defaultBrowserMatch != null 5775 && defaultBrowserMatch.priority >= maxMatchPrio 5776 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5777 { 5778 if (debug) { 5779 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5780 } 5781 result.add(defaultBrowserMatch); 5782 } else { 5783 result.addAll(matchAllList); 5784 } 5785 } 5786 5787 // If there is nothing selected, add all candidates and remove the ones that the user 5788 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5789 if (result.size() == 0) { 5790 result.addAll(candidates); 5791 result.removeAll(neverList); 5792 } 5793 } 5794 } 5795 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5796 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5797 result.size()); 5798 for (ResolveInfo info : result) { 5799 Slog.v(TAG, " + " + info.activityInfo); 5800 } 5801 } 5802 return result; 5803 } 5804 5805 // Returns a packed value as a long: 5806 // 5807 // high 'int'-sized word: link status: undefined/ask/never/always. 5808 // low 'int'-sized word: relative priority among 'always' results. 5809 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5810 long result = ps.getDomainVerificationStatusForUser(userId); 5811 // if none available, get the master status 5812 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5813 if (ps.getIntentFilterVerificationInfo() != null) { 5814 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5815 } 5816 } 5817 return result; 5818 } 5819 5820 private ResolveInfo querySkipCurrentProfileIntents( 5821 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5822 int flags, int sourceUserId) { 5823 if (matchingFilters != null) { 5824 int size = matchingFilters.size(); 5825 for (int i = 0; i < size; i ++) { 5826 CrossProfileIntentFilter filter = matchingFilters.get(i); 5827 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5828 // Checking if there are activities in the target user that can handle the 5829 // intent. 5830 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5831 resolvedType, flags, sourceUserId); 5832 if (resolveInfo != null) { 5833 return resolveInfo; 5834 } 5835 } 5836 } 5837 } 5838 return null; 5839 } 5840 5841 // Return matching ResolveInfo in target user if any. 5842 private ResolveInfo queryCrossProfileIntents( 5843 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5844 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5845 if (matchingFilters != null) { 5846 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5847 // match the same intent. For performance reasons, it is better not to 5848 // run queryIntent twice for the same userId 5849 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5850 int size = matchingFilters.size(); 5851 for (int i = 0; i < size; i++) { 5852 CrossProfileIntentFilter filter = matchingFilters.get(i); 5853 int targetUserId = filter.getTargetUserId(); 5854 boolean skipCurrentProfile = 5855 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5856 boolean skipCurrentProfileIfNoMatchFound = 5857 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5858 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5859 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5860 // Checking if there are activities in the target user that can handle the 5861 // intent. 5862 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5863 resolvedType, flags, sourceUserId); 5864 if (resolveInfo != null) return resolveInfo; 5865 alreadyTriedUserIds.put(targetUserId, true); 5866 } 5867 } 5868 } 5869 return null; 5870 } 5871 5872 /** 5873 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5874 * will forward the intent to the filter's target user. 5875 * Otherwise, returns null. 5876 */ 5877 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5878 String resolvedType, int flags, int sourceUserId) { 5879 int targetUserId = filter.getTargetUserId(); 5880 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5881 resolvedType, flags, targetUserId); 5882 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5883 // If all the matches in the target profile are suspended, return null. 5884 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5885 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5886 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5887 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5888 targetUserId); 5889 } 5890 } 5891 } 5892 return null; 5893 } 5894 5895 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5896 int sourceUserId, int targetUserId) { 5897 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5898 long ident = Binder.clearCallingIdentity(); 5899 boolean targetIsProfile; 5900 try { 5901 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5902 } finally { 5903 Binder.restoreCallingIdentity(ident); 5904 } 5905 String className; 5906 if (targetIsProfile) { 5907 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5908 } else { 5909 className = FORWARD_INTENT_TO_PARENT; 5910 } 5911 ComponentName forwardingActivityComponentName = new ComponentName( 5912 mAndroidApplication.packageName, className); 5913 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5914 sourceUserId); 5915 if (!targetIsProfile) { 5916 forwardingActivityInfo.showUserIcon = targetUserId; 5917 forwardingResolveInfo.noResourceId = true; 5918 } 5919 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5920 forwardingResolveInfo.priority = 0; 5921 forwardingResolveInfo.preferredOrder = 0; 5922 forwardingResolveInfo.match = 0; 5923 forwardingResolveInfo.isDefault = true; 5924 forwardingResolveInfo.filter = filter; 5925 forwardingResolveInfo.targetUserId = targetUserId; 5926 return forwardingResolveInfo; 5927 } 5928 5929 @Override 5930 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5931 Intent[] specifics, String[] specificTypes, Intent intent, 5932 String resolvedType, int flags, int userId) { 5933 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5934 specificTypes, intent, resolvedType, flags, userId)); 5935 } 5936 5937 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5938 Intent[] specifics, String[] specificTypes, Intent intent, 5939 String resolvedType, int flags, int userId) { 5940 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5941 flags = updateFlagsForResolve(flags, userId, intent); 5942 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5943 false /* requireFullPermission */, false /* checkShell */, 5944 "query intent activity options"); 5945 final String resultsAction = intent.getAction(); 5946 5947 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5948 | PackageManager.GET_RESOLVED_FILTER, userId); 5949 5950 if (DEBUG_INTENT_MATCHING) { 5951 Log.v(TAG, "Query " + intent + ": " + results); 5952 } 5953 5954 int specificsPos = 0; 5955 int N; 5956 5957 // todo: note that the algorithm used here is O(N^2). This 5958 // isn't a problem in our current environment, but if we start running 5959 // into situations where we have more than 5 or 10 matches then this 5960 // should probably be changed to something smarter... 5961 5962 // First we go through and resolve each of the specific items 5963 // that were supplied, taking care of removing any corresponding 5964 // duplicate items in the generic resolve list. 5965 if (specifics != null) { 5966 for (int i=0; i<specifics.length; i++) { 5967 final Intent sintent = specifics[i]; 5968 if (sintent == null) { 5969 continue; 5970 } 5971 5972 if (DEBUG_INTENT_MATCHING) { 5973 Log.v(TAG, "Specific #" + i + ": " + sintent); 5974 } 5975 5976 String action = sintent.getAction(); 5977 if (resultsAction != null && resultsAction.equals(action)) { 5978 // If this action was explicitly requested, then don't 5979 // remove things that have it. 5980 action = null; 5981 } 5982 5983 ResolveInfo ri = null; 5984 ActivityInfo ai = null; 5985 5986 ComponentName comp = sintent.getComponent(); 5987 if (comp == null) { 5988 ri = resolveIntent( 5989 sintent, 5990 specificTypes != null ? specificTypes[i] : null, 5991 flags, userId); 5992 if (ri == null) { 5993 continue; 5994 } 5995 if (ri == mResolveInfo) { 5996 // ACK! Must do something better with this. 5997 } 5998 ai = ri.activityInfo; 5999 comp = new ComponentName(ai.applicationInfo.packageName, 6000 ai.name); 6001 } else { 6002 ai = getActivityInfo(comp, flags, userId); 6003 if (ai == null) { 6004 continue; 6005 } 6006 } 6007 6008 // Look for any generic query activities that are duplicates 6009 // of this specific one, and remove them from the results. 6010 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6011 N = results.size(); 6012 int j; 6013 for (j=specificsPos; j<N; j++) { 6014 ResolveInfo sri = results.get(j); 6015 if ((sri.activityInfo.name.equals(comp.getClassName()) 6016 && sri.activityInfo.applicationInfo.packageName.equals( 6017 comp.getPackageName())) 6018 || (action != null && sri.filter.matchAction(action))) { 6019 results.remove(j); 6020 if (DEBUG_INTENT_MATCHING) Log.v( 6021 TAG, "Removing duplicate item from " + j 6022 + " due to specific " + specificsPos); 6023 if (ri == null) { 6024 ri = sri; 6025 } 6026 j--; 6027 N--; 6028 } 6029 } 6030 6031 // Add this specific item to its proper place. 6032 if (ri == null) { 6033 ri = new ResolveInfo(); 6034 ri.activityInfo = ai; 6035 } 6036 results.add(specificsPos, ri); 6037 ri.specificIndex = i; 6038 specificsPos++; 6039 } 6040 } 6041 6042 // Now we go through the remaining generic results and remove any 6043 // duplicate actions that are found here. 6044 N = results.size(); 6045 for (int i=specificsPos; i<N-1; i++) { 6046 final ResolveInfo rii = results.get(i); 6047 if (rii.filter == null) { 6048 continue; 6049 } 6050 6051 // Iterate over all of the actions of this result's intent 6052 // filter... typically this should be just one. 6053 final Iterator<String> it = rii.filter.actionsIterator(); 6054 if (it == null) { 6055 continue; 6056 } 6057 while (it.hasNext()) { 6058 final String action = it.next(); 6059 if (resultsAction != null && resultsAction.equals(action)) { 6060 // If this action was explicitly requested, then don't 6061 // remove things that have it. 6062 continue; 6063 } 6064 for (int j=i+1; j<N; j++) { 6065 final ResolveInfo rij = results.get(j); 6066 if (rij.filter != null && rij.filter.hasAction(action)) { 6067 results.remove(j); 6068 if (DEBUG_INTENT_MATCHING) Log.v( 6069 TAG, "Removing duplicate item from " + j 6070 + " due to action " + action + " at " + i); 6071 j--; 6072 N--; 6073 } 6074 } 6075 } 6076 6077 // If the caller didn't request filter information, drop it now 6078 // so we don't have to marshall/unmarshall it. 6079 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6080 rii.filter = null; 6081 } 6082 } 6083 6084 // Filter out the caller activity if so requested. 6085 if (caller != null) { 6086 N = results.size(); 6087 for (int i=0; i<N; i++) { 6088 ActivityInfo ainfo = results.get(i).activityInfo; 6089 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6090 && caller.getClassName().equals(ainfo.name)) { 6091 results.remove(i); 6092 break; 6093 } 6094 } 6095 } 6096 6097 // If the caller didn't request filter information, 6098 // drop them now so we don't have to 6099 // marshall/unmarshall it. 6100 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6101 N = results.size(); 6102 for (int i=0; i<N; i++) { 6103 results.get(i).filter = null; 6104 } 6105 } 6106 6107 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6108 return results; 6109 } 6110 6111 @Override 6112 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6113 String resolvedType, int flags, int userId) { 6114 return new ParceledListSlice<>( 6115 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6116 } 6117 6118 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6119 String resolvedType, int flags, int userId) { 6120 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6121 flags = updateFlagsForResolve(flags, userId, intent); 6122 ComponentName comp = intent.getComponent(); 6123 if (comp == null) { 6124 if (intent.getSelector() != null) { 6125 intent = intent.getSelector(); 6126 comp = intent.getComponent(); 6127 } 6128 } 6129 if (comp != null) { 6130 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6131 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6132 if (ai != null) { 6133 ResolveInfo ri = new ResolveInfo(); 6134 ri.activityInfo = ai; 6135 list.add(ri); 6136 } 6137 return list; 6138 } 6139 6140 // reader 6141 synchronized (mPackages) { 6142 String pkgName = intent.getPackage(); 6143 if (pkgName == null) { 6144 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6145 } 6146 final PackageParser.Package pkg = mPackages.get(pkgName); 6147 if (pkg != null) { 6148 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6149 userId); 6150 } 6151 return Collections.emptyList(); 6152 } 6153 } 6154 6155 @Override 6156 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6157 if (!sUserManager.exists(userId)) return null; 6158 flags = updateFlagsForResolve(flags, userId, intent); 6159 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6160 if (query != null) { 6161 if (query.size() >= 1) { 6162 // If there is more than one service with the same priority, 6163 // just arbitrarily pick the first one. 6164 return query.get(0); 6165 } 6166 } 6167 return null; 6168 } 6169 6170 @Override 6171 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6172 String resolvedType, int flags, int userId) { 6173 return new ParceledListSlice<>( 6174 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6175 } 6176 6177 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6178 String resolvedType, int flags, int userId) { 6179 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6180 flags = updateFlagsForResolve(flags, userId, intent); 6181 ComponentName comp = intent.getComponent(); 6182 if (comp == null) { 6183 if (intent.getSelector() != null) { 6184 intent = intent.getSelector(); 6185 comp = intent.getComponent(); 6186 } 6187 } 6188 if (comp != null) { 6189 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6190 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6191 if (si != null) { 6192 final ResolveInfo ri = new ResolveInfo(); 6193 ri.serviceInfo = si; 6194 list.add(ri); 6195 } 6196 return list; 6197 } 6198 6199 // reader 6200 synchronized (mPackages) { 6201 String pkgName = intent.getPackage(); 6202 if (pkgName == null) { 6203 return mServices.queryIntent(intent, resolvedType, flags, userId); 6204 } 6205 final PackageParser.Package pkg = mPackages.get(pkgName); 6206 if (pkg != null) { 6207 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6208 userId); 6209 } 6210 return Collections.emptyList(); 6211 } 6212 } 6213 6214 @Override 6215 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6216 String resolvedType, int flags, int userId) { 6217 return new ParceledListSlice<>( 6218 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6219 } 6220 6221 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6222 Intent intent, String resolvedType, int flags, int userId) { 6223 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6224 flags = updateFlagsForResolve(flags, userId, intent); 6225 ComponentName comp = intent.getComponent(); 6226 if (comp == null) { 6227 if (intent.getSelector() != null) { 6228 intent = intent.getSelector(); 6229 comp = intent.getComponent(); 6230 } 6231 } 6232 if (comp != null) { 6233 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6234 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6235 if (pi != null) { 6236 final ResolveInfo ri = new ResolveInfo(); 6237 ri.providerInfo = pi; 6238 list.add(ri); 6239 } 6240 return list; 6241 } 6242 6243 // reader 6244 synchronized (mPackages) { 6245 String pkgName = intent.getPackage(); 6246 if (pkgName == null) { 6247 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6248 } 6249 final PackageParser.Package pkg = mPackages.get(pkgName); 6250 if (pkg != null) { 6251 return mProviders.queryIntentForPackage( 6252 intent, resolvedType, flags, pkg.providers, userId); 6253 } 6254 return Collections.emptyList(); 6255 } 6256 } 6257 6258 @Override 6259 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6260 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6261 flags = updateFlagsForPackage(flags, userId, null); 6262 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6263 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6264 true /* requireFullPermission */, false /* checkShell */, 6265 "get installed packages"); 6266 6267 // writer 6268 synchronized (mPackages) { 6269 ArrayList<PackageInfo> list; 6270 if (listUninstalled) { 6271 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6272 for (PackageSetting ps : mSettings.mPackages.values()) { 6273 final PackageInfo pi; 6274 if (ps.pkg != null) { 6275 pi = generatePackageInfo(ps, flags, userId); 6276 } else { 6277 pi = generatePackageInfo(ps, flags, userId); 6278 } 6279 if (pi != null) { 6280 list.add(pi); 6281 } 6282 } 6283 } else { 6284 list = new ArrayList<PackageInfo>(mPackages.size()); 6285 for (PackageParser.Package p : mPackages.values()) { 6286 final PackageInfo pi = 6287 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6288 if (pi != null) { 6289 list.add(pi); 6290 } 6291 } 6292 } 6293 6294 return new ParceledListSlice<PackageInfo>(list); 6295 } 6296 } 6297 6298 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6299 String[] permissions, boolean[] tmp, int flags, int userId) { 6300 int numMatch = 0; 6301 final PermissionsState permissionsState = ps.getPermissionsState(); 6302 for (int i=0; i<permissions.length; i++) { 6303 final String permission = permissions[i]; 6304 if (permissionsState.hasPermission(permission, userId)) { 6305 tmp[i] = true; 6306 numMatch++; 6307 } else { 6308 tmp[i] = false; 6309 } 6310 } 6311 if (numMatch == 0) { 6312 return; 6313 } 6314 final PackageInfo pi; 6315 if (ps.pkg != null) { 6316 pi = generatePackageInfo(ps, flags, userId); 6317 } else { 6318 pi = generatePackageInfo(ps, flags, userId); 6319 } 6320 // The above might return null in cases of uninstalled apps or install-state 6321 // skew across users/profiles. 6322 if (pi != null) { 6323 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6324 if (numMatch == permissions.length) { 6325 pi.requestedPermissions = permissions; 6326 } else { 6327 pi.requestedPermissions = new String[numMatch]; 6328 numMatch = 0; 6329 for (int i=0; i<permissions.length; i++) { 6330 if (tmp[i]) { 6331 pi.requestedPermissions[numMatch] = permissions[i]; 6332 numMatch++; 6333 } 6334 } 6335 } 6336 } 6337 list.add(pi); 6338 } 6339 } 6340 6341 @Override 6342 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6343 String[] permissions, int flags, int userId) { 6344 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6345 flags = updateFlagsForPackage(flags, userId, permissions); 6346 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6347 6348 // writer 6349 synchronized (mPackages) { 6350 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6351 boolean[] tmpBools = new boolean[permissions.length]; 6352 if (listUninstalled) { 6353 for (PackageSetting ps : mSettings.mPackages.values()) { 6354 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6355 } 6356 } else { 6357 for (PackageParser.Package pkg : mPackages.values()) { 6358 PackageSetting ps = (PackageSetting)pkg.mExtras; 6359 if (ps != null) { 6360 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6361 userId); 6362 } 6363 } 6364 } 6365 6366 return new ParceledListSlice<PackageInfo>(list); 6367 } 6368 } 6369 6370 @Override 6371 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6372 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6373 flags = updateFlagsForApplication(flags, userId, null); 6374 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6375 6376 // writer 6377 synchronized (mPackages) { 6378 ArrayList<ApplicationInfo> list; 6379 if (listUninstalled) { 6380 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6381 for (PackageSetting ps : mSettings.mPackages.values()) { 6382 ApplicationInfo ai; 6383 if (ps.pkg != null) { 6384 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6385 ps.readUserState(userId), userId); 6386 } else { 6387 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6388 } 6389 if (ai != null) { 6390 list.add(ai); 6391 } 6392 } 6393 } else { 6394 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6395 for (PackageParser.Package p : mPackages.values()) { 6396 if (p.mExtras != null) { 6397 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6398 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6399 if (ai != null) { 6400 list.add(ai); 6401 } 6402 } 6403 } 6404 } 6405 6406 return new ParceledListSlice<ApplicationInfo>(list); 6407 } 6408 } 6409 6410 @Override 6411 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6412 if (DISABLE_EPHEMERAL_APPS) { 6413 return null; 6414 } 6415 6416 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6417 "getEphemeralApplications"); 6418 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6419 true /* requireFullPermission */, false /* checkShell */, 6420 "getEphemeralApplications"); 6421 synchronized (mPackages) { 6422 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6423 .getEphemeralApplicationsLPw(userId); 6424 if (ephemeralApps != null) { 6425 return new ParceledListSlice<>(ephemeralApps); 6426 } 6427 } 6428 return null; 6429 } 6430 6431 @Override 6432 public boolean isEphemeralApplication(String packageName, int userId) { 6433 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6434 true /* requireFullPermission */, false /* checkShell */, 6435 "isEphemeral"); 6436 if (DISABLE_EPHEMERAL_APPS) { 6437 return false; 6438 } 6439 6440 if (!isCallerSameApp(packageName)) { 6441 return false; 6442 } 6443 synchronized (mPackages) { 6444 PackageParser.Package pkg = mPackages.get(packageName); 6445 if (pkg != null) { 6446 return pkg.applicationInfo.isEphemeralApp(); 6447 } 6448 } 6449 return false; 6450 } 6451 6452 @Override 6453 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6454 if (DISABLE_EPHEMERAL_APPS) { 6455 return null; 6456 } 6457 6458 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6459 true /* requireFullPermission */, false /* checkShell */, 6460 "getCookie"); 6461 if (!isCallerSameApp(packageName)) { 6462 return null; 6463 } 6464 synchronized (mPackages) { 6465 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6466 packageName, userId); 6467 } 6468 } 6469 6470 @Override 6471 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6472 if (DISABLE_EPHEMERAL_APPS) { 6473 return true; 6474 } 6475 6476 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6477 true /* requireFullPermission */, true /* checkShell */, 6478 "setCookie"); 6479 if (!isCallerSameApp(packageName)) { 6480 return false; 6481 } 6482 synchronized (mPackages) { 6483 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6484 packageName, cookie, userId); 6485 } 6486 } 6487 6488 @Override 6489 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6490 if (DISABLE_EPHEMERAL_APPS) { 6491 return null; 6492 } 6493 6494 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6495 "getEphemeralApplicationIcon"); 6496 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6497 true /* requireFullPermission */, false /* checkShell */, 6498 "getEphemeralApplicationIcon"); 6499 synchronized (mPackages) { 6500 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6501 packageName, userId); 6502 } 6503 } 6504 6505 private boolean isCallerSameApp(String packageName) { 6506 PackageParser.Package pkg = mPackages.get(packageName); 6507 return pkg != null 6508 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6509 } 6510 6511 @Override 6512 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6513 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6514 } 6515 6516 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6517 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6518 6519 // reader 6520 synchronized (mPackages) { 6521 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6522 final int userId = UserHandle.getCallingUserId(); 6523 while (i.hasNext()) { 6524 final PackageParser.Package p = i.next(); 6525 if (p.applicationInfo == null) continue; 6526 6527 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6528 && !p.applicationInfo.isDirectBootAware(); 6529 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6530 && p.applicationInfo.isDirectBootAware(); 6531 6532 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6533 && (!mSafeMode || isSystemApp(p)) 6534 && (matchesUnaware || matchesAware)) { 6535 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6536 if (ps != null) { 6537 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6538 ps.readUserState(userId), userId); 6539 if (ai != null) { 6540 finalList.add(ai); 6541 } 6542 } 6543 } 6544 } 6545 } 6546 6547 return finalList; 6548 } 6549 6550 @Override 6551 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6552 if (!sUserManager.exists(userId)) return null; 6553 flags = updateFlagsForComponent(flags, userId, name); 6554 // reader 6555 synchronized (mPackages) { 6556 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6557 PackageSetting ps = provider != null 6558 ? mSettings.mPackages.get(provider.owner.packageName) 6559 : null; 6560 return ps != null 6561 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6562 ? PackageParser.generateProviderInfo(provider, flags, 6563 ps.readUserState(userId), userId) 6564 : null; 6565 } 6566 } 6567 6568 /** 6569 * @deprecated 6570 */ 6571 @Deprecated 6572 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6573 // reader 6574 synchronized (mPackages) { 6575 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6576 .entrySet().iterator(); 6577 final int userId = UserHandle.getCallingUserId(); 6578 while (i.hasNext()) { 6579 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6580 PackageParser.Provider p = entry.getValue(); 6581 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6582 6583 if (ps != null && p.syncable 6584 && (!mSafeMode || (p.info.applicationInfo.flags 6585 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6586 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6587 ps.readUserState(userId), userId); 6588 if (info != null) { 6589 outNames.add(entry.getKey()); 6590 outInfo.add(info); 6591 } 6592 } 6593 } 6594 } 6595 } 6596 6597 @Override 6598 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6599 int uid, int flags) { 6600 final int userId = processName != null ? UserHandle.getUserId(uid) 6601 : UserHandle.getCallingUserId(); 6602 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6603 flags = updateFlagsForComponent(flags, userId, processName); 6604 6605 ArrayList<ProviderInfo> finalList = null; 6606 // reader 6607 synchronized (mPackages) { 6608 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6609 while (i.hasNext()) { 6610 final PackageParser.Provider p = i.next(); 6611 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6612 if (ps != null && p.info.authority != null 6613 && (processName == null 6614 || (p.info.processName.equals(processName) 6615 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6616 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6617 if (finalList == null) { 6618 finalList = new ArrayList<ProviderInfo>(3); 6619 } 6620 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6621 ps.readUserState(userId), userId); 6622 if (info != null) { 6623 finalList.add(info); 6624 } 6625 } 6626 } 6627 } 6628 6629 if (finalList != null) { 6630 Collections.sort(finalList, mProviderInitOrderSorter); 6631 return new ParceledListSlice<ProviderInfo>(finalList); 6632 } 6633 6634 return ParceledListSlice.emptyList(); 6635 } 6636 6637 @Override 6638 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6639 // reader 6640 synchronized (mPackages) { 6641 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6642 return PackageParser.generateInstrumentationInfo(i, flags); 6643 } 6644 } 6645 6646 @Override 6647 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6648 String targetPackage, int flags) { 6649 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6650 } 6651 6652 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6653 int flags) { 6654 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6655 6656 // reader 6657 synchronized (mPackages) { 6658 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6659 while (i.hasNext()) { 6660 final PackageParser.Instrumentation p = i.next(); 6661 if (targetPackage == null 6662 || targetPackage.equals(p.info.targetPackage)) { 6663 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6664 flags); 6665 if (ii != null) { 6666 finalList.add(ii); 6667 } 6668 } 6669 } 6670 } 6671 6672 return finalList; 6673 } 6674 6675 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6676 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6677 if (overlays == null) { 6678 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6679 return; 6680 } 6681 for (PackageParser.Package opkg : overlays.values()) { 6682 // Not much to do if idmap fails: we already logged the error 6683 // and we certainly don't want to abort installation of pkg simply 6684 // because an overlay didn't fit properly. For these reasons, 6685 // ignore the return value of createIdmapForPackagePairLI. 6686 createIdmapForPackagePairLI(pkg, opkg); 6687 } 6688 } 6689 6690 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6691 PackageParser.Package opkg) { 6692 if (!opkg.mTrustedOverlay) { 6693 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6694 opkg.baseCodePath + ": overlay not trusted"); 6695 return false; 6696 } 6697 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6698 if (overlaySet == null) { 6699 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6700 opkg.baseCodePath + " but target package has no known overlays"); 6701 return false; 6702 } 6703 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6704 // TODO: generate idmap for split APKs 6705 try { 6706 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6707 } catch (InstallerException e) { 6708 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6709 + opkg.baseCodePath); 6710 return false; 6711 } 6712 PackageParser.Package[] overlayArray = 6713 overlaySet.values().toArray(new PackageParser.Package[0]); 6714 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6715 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6716 return p1.mOverlayPriority - p2.mOverlayPriority; 6717 } 6718 }; 6719 Arrays.sort(overlayArray, cmp); 6720 6721 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6722 int i = 0; 6723 for (PackageParser.Package p : overlayArray) { 6724 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6725 } 6726 return true; 6727 } 6728 6729 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6730 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6731 try { 6732 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6733 } finally { 6734 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6735 } 6736 } 6737 6738 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6739 final File[] files = dir.listFiles(); 6740 if (ArrayUtils.isEmpty(files)) { 6741 Log.d(TAG, "No files in app dir " + dir); 6742 return; 6743 } 6744 6745 if (DEBUG_PACKAGE_SCANNING) { 6746 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6747 + " flags=0x" + Integer.toHexString(parseFlags)); 6748 } 6749 6750 for (File file : files) { 6751 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6752 && !PackageInstallerService.isStageName(file.getName()); 6753 if (!isPackage) { 6754 // Ignore entries which are not packages 6755 continue; 6756 } 6757 try { 6758 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6759 scanFlags, currentTime, null); 6760 } catch (PackageManagerException e) { 6761 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6762 6763 // Delete invalid userdata apps 6764 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6765 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6766 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6767 removeCodePathLI(file); 6768 } 6769 } 6770 } 6771 } 6772 6773 private static File getSettingsProblemFile() { 6774 File dataDir = Environment.getDataDirectory(); 6775 File systemDir = new File(dataDir, "system"); 6776 File fname = new File(systemDir, "uiderrors.txt"); 6777 return fname; 6778 } 6779 6780 static void reportSettingsProblem(int priority, String msg) { 6781 logCriticalInfo(priority, msg); 6782 } 6783 6784 static void logCriticalInfo(int priority, String msg) { 6785 Slog.println(priority, TAG, msg); 6786 EventLogTags.writePmCriticalInfo(msg); 6787 try { 6788 File fname = getSettingsProblemFile(); 6789 FileOutputStream out = new FileOutputStream(fname, true); 6790 PrintWriter pw = new FastPrintWriter(out); 6791 SimpleDateFormat formatter = new SimpleDateFormat(); 6792 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6793 pw.println(dateString + ": " + msg); 6794 pw.close(); 6795 FileUtils.setPermissions( 6796 fname.toString(), 6797 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6798 -1, -1); 6799 } catch (java.io.IOException e) { 6800 } 6801 } 6802 6803 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6804 if (srcFile.isDirectory()) { 6805 final File baseFile = new File(pkg.baseCodePath); 6806 long maxModifiedTime = baseFile.lastModified(); 6807 if (pkg.splitCodePaths != null) { 6808 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6809 final File splitFile = new File(pkg.splitCodePaths[i]); 6810 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6811 } 6812 } 6813 return maxModifiedTime; 6814 } 6815 return srcFile.lastModified(); 6816 } 6817 6818 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6819 final int policyFlags) throws PackageManagerException { 6820 if (ps != null 6821 && ps.codePath.equals(srcFile) 6822 && ps.timeStamp == getLastModifiedTime(pkg, srcFile) 6823 && !isCompatSignatureUpdateNeeded(pkg) 6824 && !isRecoverSignatureUpdateNeeded(pkg)) { 6825 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6826 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6827 ArraySet<PublicKey> signingKs; 6828 synchronized (mPackages) { 6829 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6830 } 6831 if (ps.signatures.mSignatures != null 6832 && ps.signatures.mSignatures.length != 0 6833 && signingKs != null) { 6834 // Optimization: reuse the existing cached certificates 6835 // if the package appears to be unchanged. 6836 pkg.mSignatures = ps.signatures.mSignatures; 6837 pkg.mSigningKeys = signingKs; 6838 return; 6839 } 6840 6841 Slog.w(TAG, "PackageSetting for " + ps.name 6842 + " is missing signatures. Collecting certs again to recover them."); 6843 } else { 6844 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6845 } 6846 6847 try { 6848 PackageParser.collectCertificates(pkg, policyFlags); 6849 } catch (PackageParserException e) { 6850 throw PackageManagerException.from(e); 6851 } 6852 } 6853 6854 /** 6855 * Traces a package scan. 6856 * @see #scanPackageLI(File, int, int, long, UserHandle) 6857 */ 6858 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6859 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6860 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6861 try { 6862 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6863 } finally { 6864 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6865 } 6866 } 6867 6868 /** 6869 * Scans a package and returns the newly parsed package. 6870 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6871 */ 6872 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6873 long currentTime, UserHandle user) throws PackageManagerException { 6874 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6875 PackageParser pp = new PackageParser(); 6876 pp.setSeparateProcesses(mSeparateProcesses); 6877 pp.setOnlyCoreApps(mOnlyCore); 6878 pp.setDisplayMetrics(mMetrics); 6879 6880 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6881 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6882 } 6883 6884 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6885 final PackageParser.Package pkg; 6886 try { 6887 pkg = pp.parsePackage(scanFile, parseFlags); 6888 } catch (PackageParserException e) { 6889 throw PackageManagerException.from(e); 6890 } finally { 6891 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6892 } 6893 6894 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6895 } 6896 6897 /** 6898 * Scans a package and returns the newly parsed package. 6899 * @throws PackageManagerException on a parse error. 6900 */ 6901 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6902 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6903 throws PackageManagerException { 6904 // If the package has children and this is the first dive in the function 6905 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6906 // packages (parent and children) would be successfully scanned before the 6907 // actual scan since scanning mutates internal state and we want to atomically 6908 // install the package and its children. 6909 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6910 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6911 scanFlags |= SCAN_CHECK_ONLY; 6912 } 6913 } else { 6914 scanFlags &= ~SCAN_CHECK_ONLY; 6915 } 6916 6917 // Scan the parent 6918 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6919 scanFlags, currentTime, user); 6920 6921 // Scan the children 6922 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6923 for (int i = 0; i < childCount; i++) { 6924 PackageParser.Package childPackage = pkg.childPackages.get(i); 6925 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6926 currentTime, user); 6927 } 6928 6929 6930 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6931 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6932 } 6933 6934 return scannedPkg; 6935 } 6936 6937 /** 6938 * Scans a package and returns the newly parsed package. 6939 * @throws PackageManagerException on a parse error. 6940 */ 6941 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6942 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6943 throws PackageManagerException { 6944 PackageSetting ps = null; 6945 PackageSetting updatedPkg; 6946 // reader 6947 synchronized (mPackages) { 6948 // Look to see if we already know about this package. 6949 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6950 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6951 // This package has been renamed to its original name. Let's 6952 // use that. 6953 ps = mSettings.peekPackageLPr(oldName); 6954 } 6955 // If there was no original package, see one for the real package name. 6956 if (ps == null) { 6957 ps = mSettings.peekPackageLPr(pkg.packageName); 6958 } 6959 // Check to see if this package could be hiding/updating a system 6960 // package. Must look for it either under the original or real 6961 // package name depending on our state. 6962 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6963 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6964 6965 // If this is a package we don't know about on the system partition, we 6966 // may need to remove disabled child packages on the system partition 6967 // or may need to not add child packages if the parent apk is updated 6968 // on the data partition and no longer defines this child package. 6969 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6970 // If this is a parent package for an updated system app and this system 6971 // app got an OTA update which no longer defines some of the child packages 6972 // we have to prune them from the disabled system packages. 6973 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6974 if (disabledPs != null) { 6975 final int scannedChildCount = (pkg.childPackages != null) 6976 ? pkg.childPackages.size() : 0; 6977 final int disabledChildCount = disabledPs.childPackageNames != null 6978 ? disabledPs.childPackageNames.size() : 0; 6979 for (int i = 0; i < disabledChildCount; i++) { 6980 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6981 boolean disabledPackageAvailable = false; 6982 for (int j = 0; j < scannedChildCount; j++) { 6983 PackageParser.Package childPkg = pkg.childPackages.get(j); 6984 if (childPkg.packageName.equals(disabledChildPackageName)) { 6985 disabledPackageAvailable = true; 6986 break; 6987 } 6988 } 6989 if (!disabledPackageAvailable) { 6990 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6991 } 6992 } 6993 } 6994 } 6995 } 6996 6997 boolean updatedPkgBetter = false; 6998 // First check if this is a system package that may involve an update 6999 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7000 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7001 // it needs to drop FLAG_PRIVILEGED. 7002 if (locationIsPrivileged(scanFile)) { 7003 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7004 } else { 7005 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7006 } 7007 7008 if (ps != null && !ps.codePath.equals(scanFile)) { 7009 // The path has changed from what was last scanned... check the 7010 // version of the new path against what we have stored to determine 7011 // what to do. 7012 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7013 if (pkg.mVersionCode <= ps.versionCode) { 7014 // The system package has been updated and the code path does not match 7015 // Ignore entry. Skip it. 7016 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7017 + " ignored: updated version " + ps.versionCode 7018 + " better than this " + pkg.mVersionCode); 7019 if (!updatedPkg.codePath.equals(scanFile)) { 7020 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7021 + ps.name + " changing from " + updatedPkg.codePathString 7022 + " to " + scanFile); 7023 updatedPkg.codePath = scanFile; 7024 updatedPkg.codePathString = scanFile.toString(); 7025 updatedPkg.resourcePath = scanFile; 7026 updatedPkg.resourcePathString = scanFile.toString(); 7027 } 7028 updatedPkg.pkg = pkg; 7029 updatedPkg.versionCode = pkg.mVersionCode; 7030 7031 // Update the disabled system child packages to point to the package too. 7032 final int childCount = updatedPkg.childPackageNames != null 7033 ? updatedPkg.childPackageNames.size() : 0; 7034 for (int i = 0; i < childCount; i++) { 7035 String childPackageName = updatedPkg.childPackageNames.get(i); 7036 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7037 childPackageName); 7038 if (updatedChildPkg != null) { 7039 updatedChildPkg.pkg = pkg; 7040 updatedChildPkg.versionCode = pkg.mVersionCode; 7041 } 7042 } 7043 7044 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7045 + scanFile + " ignored: updated version " + ps.versionCode 7046 + " better than this " + pkg.mVersionCode); 7047 } else { 7048 // The current app on the system partition is better than 7049 // what we have updated to on the data partition; switch 7050 // back to the system partition version. 7051 // At this point, its safely assumed that package installation for 7052 // apps in system partition will go through. If not there won't be a working 7053 // version of the app 7054 // writer 7055 synchronized (mPackages) { 7056 // Just remove the loaded entries from package lists. 7057 mPackages.remove(ps.name); 7058 } 7059 7060 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7061 + " reverting from " + ps.codePathString 7062 + ": new version " + pkg.mVersionCode 7063 + " better than installed " + ps.versionCode); 7064 7065 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7066 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7067 synchronized (mInstallLock) { 7068 args.cleanUpResourcesLI(); 7069 } 7070 synchronized (mPackages) { 7071 mSettings.enableSystemPackageLPw(ps.name); 7072 } 7073 updatedPkgBetter = true; 7074 } 7075 } 7076 } 7077 7078 if (updatedPkg != null) { 7079 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7080 // initially 7081 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7082 7083 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7084 // flag set initially 7085 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7086 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7087 } 7088 } 7089 7090 // Verify certificates against what was last scanned 7091 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7092 7093 /* 7094 * A new system app appeared, but we already had a non-system one of the 7095 * same name installed earlier. 7096 */ 7097 boolean shouldHideSystemApp = false; 7098 if (updatedPkg == null && ps != null 7099 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7100 /* 7101 * Check to make sure the signatures match first. If they don't, 7102 * wipe the installed application and its data. 7103 */ 7104 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7105 != PackageManager.SIGNATURE_MATCH) { 7106 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7107 + " signatures don't match existing userdata copy; removing"); 7108 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7109 "scanPackageInternalLI")) { 7110 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7111 } 7112 ps = null; 7113 } else { 7114 /* 7115 * If the newly-added system app is an older version than the 7116 * already installed version, hide it. It will be scanned later 7117 * and re-added like an update. 7118 */ 7119 if (pkg.mVersionCode <= ps.versionCode) { 7120 shouldHideSystemApp = true; 7121 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7122 + " but new version " + pkg.mVersionCode + " better than installed " 7123 + ps.versionCode + "; hiding system"); 7124 } else { 7125 /* 7126 * The newly found system app is a newer version that the 7127 * one previously installed. Simply remove the 7128 * already-installed application and replace it with our own 7129 * while keeping the application data. 7130 */ 7131 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7132 + " reverting from " + ps.codePathString + ": new version " 7133 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7134 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7135 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7136 synchronized (mInstallLock) { 7137 args.cleanUpResourcesLI(); 7138 } 7139 } 7140 } 7141 } 7142 7143 // The apk is forward locked (not public) if its code and resources 7144 // are kept in different files. (except for app in either system or 7145 // vendor path). 7146 // TODO grab this value from PackageSettings 7147 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7148 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7149 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7150 } 7151 } 7152 7153 // TODO: extend to support forward-locked splits 7154 String resourcePath = null; 7155 String baseResourcePath = null; 7156 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7157 if (ps != null && ps.resourcePathString != null) { 7158 resourcePath = ps.resourcePathString; 7159 baseResourcePath = ps.resourcePathString; 7160 } else { 7161 // Should not happen at all. Just log an error. 7162 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7163 } 7164 } else { 7165 resourcePath = pkg.codePath; 7166 baseResourcePath = pkg.baseCodePath; 7167 } 7168 7169 // Set application objects path explicitly. 7170 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7171 pkg.setApplicationInfoCodePath(pkg.codePath); 7172 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7173 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7174 pkg.setApplicationInfoResourcePath(resourcePath); 7175 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7176 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7177 7178 // Note that we invoke the following method only if we are about to unpack an application 7179 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7180 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7181 7182 /* 7183 * If the system app should be overridden by a previously installed 7184 * data, hide the system app now and let the /data/app scan pick it up 7185 * again. 7186 */ 7187 if (shouldHideSystemApp) { 7188 synchronized (mPackages) { 7189 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7190 } 7191 } 7192 7193 return scannedPkg; 7194 } 7195 7196 private static String fixProcessName(String defProcessName, 7197 String processName, int uid) { 7198 if (processName == null) { 7199 return defProcessName; 7200 } 7201 return processName; 7202 } 7203 7204 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7205 throws PackageManagerException { 7206 if (pkgSetting.signatures.mSignatures != null) { 7207 // Already existing package. Make sure signatures match 7208 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7209 == PackageManager.SIGNATURE_MATCH; 7210 if (!match) { 7211 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7212 == PackageManager.SIGNATURE_MATCH; 7213 } 7214 if (!match) { 7215 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7216 == PackageManager.SIGNATURE_MATCH; 7217 } 7218 if (!match) { 7219 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7220 + pkg.packageName + " signatures do not match the " 7221 + "previously installed version; ignoring!"); 7222 } 7223 } 7224 7225 // Check for shared user signatures 7226 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7227 // Already existing package. Make sure signatures match 7228 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7229 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7230 if (!match) { 7231 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7232 == PackageManager.SIGNATURE_MATCH; 7233 } 7234 if (!match) { 7235 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7236 == PackageManager.SIGNATURE_MATCH; 7237 } 7238 if (!match) { 7239 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7240 "Package " + pkg.packageName 7241 + " has no signatures that match those in shared user " 7242 + pkgSetting.sharedUser.name + "; ignoring!"); 7243 } 7244 } 7245 } 7246 7247 /** 7248 * Enforces that only the system UID or root's UID can call a method exposed 7249 * via Binder. 7250 * 7251 * @param message used as message if SecurityException is thrown 7252 * @throws SecurityException if the caller is not system or root 7253 */ 7254 private static final void enforceSystemOrRoot(String message) { 7255 final int uid = Binder.getCallingUid(); 7256 if (uid != Process.SYSTEM_UID && uid != 0) { 7257 throw new SecurityException(message); 7258 } 7259 } 7260 7261 @Override 7262 public void performFstrimIfNeeded() { 7263 enforceSystemOrRoot("Only the system can request fstrim"); 7264 7265 // Before everything else, see whether we need to fstrim. 7266 try { 7267 IMountService ms = PackageHelper.getMountService(); 7268 if (ms != null) { 7269 final boolean isUpgrade = isUpgrade(); 7270 boolean doTrim = isUpgrade; 7271 if (doTrim) { 7272 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7273 } else { 7274 final long interval = android.provider.Settings.Global.getLong( 7275 mContext.getContentResolver(), 7276 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7277 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7278 if (interval > 0) { 7279 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7280 if (timeSinceLast > interval) { 7281 doTrim = true; 7282 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7283 + "; running immediately"); 7284 } 7285 } 7286 } 7287 if (doTrim) { 7288 if (!isFirstBoot()) { 7289 try { 7290 ActivityManagerNative.getDefault().showBootMessage( 7291 mContext.getResources().getString( 7292 R.string.android_upgrading_fstrim), true); 7293 } catch (RemoteException e) { 7294 } 7295 } 7296 ms.runMaintenance(); 7297 } 7298 } else { 7299 Slog.e(TAG, "Mount service unavailable!"); 7300 } 7301 } catch (RemoteException e) { 7302 // Can't happen; MountService is local 7303 } 7304 } 7305 7306 @Override 7307 public void updatePackagesIfNeeded() { 7308 enforceSystemOrRoot("Only the system can request package update"); 7309 7310 // We need to re-extract after an OTA. 7311 boolean causeUpgrade = isUpgrade(); 7312 7313 // First boot or factory reset. 7314 // Note: we also handle devices that are upgrading to N right now as if it is their 7315 // first boot, as they do not have profile data. 7316 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7317 7318 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7319 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7320 7321 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7322 return; 7323 } 7324 7325 List<PackageParser.Package> pkgs; 7326 synchronized (mPackages) { 7327 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7328 } 7329 7330 final long startTime = System.nanoTime(); 7331 final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */, 7332 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7333 7334 final int elapsedTimeSeconds = 7335 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7336 7337 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7338 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7339 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7340 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7341 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7342 } 7343 7344 /** 7345 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7346 * containing statistics about the invocation. The array consists of three elements, 7347 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7348 * and {@code numberOfPackagesFailed}. 7349 */ 7350 private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog, 7351 String compilerFilter) { 7352 7353 int numberOfPackagesVisited = 0; 7354 int numberOfPackagesOptimized = 0; 7355 int numberOfPackagesSkipped = 0; 7356 int numberOfPackagesFailed = 0; 7357 final int numberOfPackagesToDexopt = pkgs.size(); 7358 7359 for (PackageParser.Package pkg : pkgs) { 7360 numberOfPackagesVisited++; 7361 7362 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7363 if (DEBUG_DEXOPT) { 7364 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7365 } 7366 numberOfPackagesSkipped++; 7367 continue; 7368 } 7369 7370 if (DEBUG_DEXOPT) { 7371 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7372 numberOfPackagesToDexopt + ": " + pkg.packageName); 7373 } 7374 7375 if (showDialog) { 7376 try { 7377 ActivityManagerNative.getDefault().showBootMessage( 7378 mContext.getResources().getString(R.string.android_upgrading_apk, 7379 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7380 } catch (RemoteException e) { 7381 } 7382 } 7383 7384 // checkProfiles is false to avoid merging profiles during boot which 7385 // might interfere with background compilation (b/28612421). 7386 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7387 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7388 // trade-off worth doing to save boot time work. 7389 int dexOptStatus = performDexOptTraced(pkg.packageName, 7390 false /* checkProfiles */, 7391 compilerFilter, 7392 false /* force */); 7393 switch (dexOptStatus) { 7394 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7395 numberOfPackagesOptimized++; 7396 break; 7397 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7398 numberOfPackagesSkipped++; 7399 break; 7400 case PackageDexOptimizer.DEX_OPT_FAILED: 7401 numberOfPackagesFailed++; 7402 break; 7403 default: 7404 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7405 break; 7406 } 7407 } 7408 7409 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7410 numberOfPackagesFailed }; 7411 } 7412 7413 @Override 7414 public void notifyPackageUse(String packageName, int reason) { 7415 synchronized (mPackages) { 7416 PackageParser.Package p = mPackages.get(packageName); 7417 if (p == null) { 7418 return; 7419 } 7420 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7421 } 7422 } 7423 7424 // TODO: this is not used nor needed. Delete it. 7425 @Override 7426 public boolean performDexOptIfNeeded(String packageName) { 7427 int dexOptStatus = performDexOptTraced(packageName, 7428 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7429 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7430 } 7431 7432 @Override 7433 public boolean performDexOpt(String packageName, 7434 boolean checkProfiles, int compileReason, boolean force) { 7435 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7436 getCompilerFilterForReason(compileReason), force); 7437 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7438 } 7439 7440 @Override 7441 public boolean performDexOptMode(String packageName, 7442 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7443 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7444 targetCompilerFilter, force); 7445 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7446 } 7447 7448 private int performDexOptTraced(String packageName, 7449 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7450 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7451 try { 7452 return performDexOptInternal(packageName, checkProfiles, 7453 targetCompilerFilter, force); 7454 } finally { 7455 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7456 } 7457 } 7458 7459 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7460 // if the package can now be considered up to date for the given filter. 7461 private int performDexOptInternal(String packageName, 7462 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7463 PackageParser.Package p; 7464 synchronized (mPackages) { 7465 p = mPackages.get(packageName); 7466 if (p == null) { 7467 // Package could not be found. Report failure. 7468 return PackageDexOptimizer.DEX_OPT_FAILED; 7469 } 7470 mPackageUsage.write(false); 7471 } 7472 long callingId = Binder.clearCallingIdentity(); 7473 try { 7474 synchronized (mInstallLock) { 7475 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7476 targetCompilerFilter, force); 7477 } 7478 } finally { 7479 Binder.restoreCallingIdentity(callingId); 7480 } 7481 } 7482 7483 public ArraySet<String> getOptimizablePackages() { 7484 ArraySet<String> pkgs = new ArraySet<String>(); 7485 synchronized (mPackages) { 7486 for (PackageParser.Package p : mPackages.values()) { 7487 if (PackageDexOptimizer.canOptimizePackage(p)) { 7488 pkgs.add(p.packageName); 7489 } 7490 } 7491 } 7492 return pkgs; 7493 } 7494 7495 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7496 boolean checkProfiles, String targetCompilerFilter, 7497 boolean force) { 7498 // Select the dex optimizer based on the force parameter. 7499 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7500 // allocate an object here. 7501 PackageDexOptimizer pdo = force 7502 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7503 : mPackageDexOptimizer; 7504 7505 // Optimize all dependencies first. Note: we ignore the return value and march on 7506 // on errors. 7507 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7508 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7509 if (!deps.isEmpty()) { 7510 for (PackageParser.Package depPackage : deps) { 7511 // TODO: Analyze and investigate if we (should) profile libraries. 7512 // Currently this will do a full compilation of the library by default. 7513 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7514 false /* checkProfiles */, 7515 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7516 } 7517 } 7518 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7519 targetCompilerFilter); 7520 } 7521 7522 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7523 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7524 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7525 Set<String> collectedNames = new HashSet<>(); 7526 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7527 7528 retValue.remove(p); 7529 7530 return retValue; 7531 } else { 7532 return Collections.emptyList(); 7533 } 7534 } 7535 7536 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7537 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7538 if (!collectedNames.contains(p.packageName)) { 7539 collectedNames.add(p.packageName); 7540 collected.add(p); 7541 7542 if (p.usesLibraries != null) { 7543 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7544 } 7545 if (p.usesOptionalLibraries != null) { 7546 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7547 collectedNames); 7548 } 7549 } 7550 } 7551 7552 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7553 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7554 for (String libName : libs) { 7555 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7556 if (libPkg != null) { 7557 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7558 } 7559 } 7560 } 7561 7562 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7563 synchronized (mPackages) { 7564 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7565 if (lib != null && lib.apk != null) { 7566 return mPackages.get(lib.apk); 7567 } 7568 } 7569 return null; 7570 } 7571 7572 public void shutdown() { 7573 mPackageUsage.write(true); 7574 } 7575 7576 @Override 7577 public void dumpProfiles(String packageName) { 7578 PackageParser.Package pkg; 7579 synchronized (mPackages) { 7580 pkg = mPackages.get(packageName); 7581 if (pkg == null) { 7582 throw new IllegalArgumentException("Unknown package: " + packageName); 7583 } 7584 } 7585 /* Only the shell, root, or the app user should be able to dump profiles. */ 7586 int callingUid = Binder.getCallingUid(); 7587 if (callingUid != Process.SHELL_UID && 7588 callingUid != Process.ROOT_UID && 7589 callingUid != pkg.applicationInfo.uid) { 7590 throw new SecurityException("dumpProfiles"); 7591 } 7592 7593 synchronized (mInstallLock) { 7594 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7595 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7596 try { 7597 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7598 String gid = Integer.toString(sharedGid); 7599 String codePaths = TextUtils.join(";", allCodePaths); 7600 mInstaller.dumpProfiles(gid, packageName, codePaths); 7601 } catch (InstallerException e) { 7602 Slog.w(TAG, "Failed to dump profiles", e); 7603 } 7604 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7605 } 7606 } 7607 7608 @Override 7609 public void forceDexOpt(String packageName) { 7610 enforceSystemOrRoot("forceDexOpt"); 7611 7612 PackageParser.Package pkg; 7613 synchronized (mPackages) { 7614 pkg = mPackages.get(packageName); 7615 if (pkg == null) { 7616 throw new IllegalArgumentException("Unknown package: " + packageName); 7617 } 7618 } 7619 7620 synchronized (mInstallLock) { 7621 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7622 7623 // Whoever is calling forceDexOpt wants a fully compiled package. 7624 // Don't use profiles since that may cause compilation to be skipped. 7625 final int res = performDexOptInternalWithDependenciesLI(pkg, 7626 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7627 true /* force */); 7628 7629 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7630 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7631 throw new IllegalStateException("Failed to dexopt: " + res); 7632 } 7633 } 7634 } 7635 7636 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7637 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7638 Slog.w(TAG, "Unable to update from " + oldPkg.name 7639 + " to " + newPkg.packageName 7640 + ": old package not in system partition"); 7641 return false; 7642 } else if (mPackages.get(oldPkg.name) != null) { 7643 Slog.w(TAG, "Unable to update from " + oldPkg.name 7644 + " to " + newPkg.packageName 7645 + ": old package still exists"); 7646 return false; 7647 } 7648 return true; 7649 } 7650 7651 void removeCodePathLI(File codePath) { 7652 if (codePath.isDirectory()) { 7653 try { 7654 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7655 } catch (InstallerException e) { 7656 Slog.w(TAG, "Failed to remove code path", e); 7657 } 7658 } else { 7659 codePath.delete(); 7660 } 7661 } 7662 7663 private int[] resolveUserIds(int userId) { 7664 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7665 } 7666 7667 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7668 if (pkg == null) { 7669 Slog.wtf(TAG, "Package was null!", new Throwable()); 7670 return; 7671 } 7672 clearAppDataLeafLIF(pkg, userId, flags); 7673 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7674 for (int i = 0; i < childCount; i++) { 7675 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7676 } 7677 } 7678 7679 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7680 final PackageSetting ps; 7681 synchronized (mPackages) { 7682 ps = mSettings.mPackages.get(pkg.packageName); 7683 } 7684 for (int realUserId : resolveUserIds(userId)) { 7685 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7686 try { 7687 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7688 ceDataInode); 7689 } catch (InstallerException e) { 7690 Slog.w(TAG, String.valueOf(e)); 7691 } 7692 } 7693 } 7694 7695 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7696 if (pkg == null) { 7697 Slog.wtf(TAG, "Package was null!", new Throwable()); 7698 return; 7699 } 7700 destroyAppDataLeafLIF(pkg, userId, flags); 7701 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7702 for (int i = 0; i < childCount; i++) { 7703 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7704 } 7705 } 7706 7707 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7708 final PackageSetting ps; 7709 synchronized (mPackages) { 7710 ps = mSettings.mPackages.get(pkg.packageName); 7711 } 7712 for (int realUserId : resolveUserIds(userId)) { 7713 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7714 try { 7715 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7716 ceDataInode); 7717 } catch (InstallerException e) { 7718 Slog.w(TAG, String.valueOf(e)); 7719 } 7720 } 7721 } 7722 7723 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7724 if (pkg == null) { 7725 Slog.wtf(TAG, "Package was null!", new Throwable()); 7726 return; 7727 } 7728 destroyAppProfilesLeafLIF(pkg); 7729 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7730 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7731 for (int i = 0; i < childCount; i++) { 7732 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7733 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7734 true /* removeBaseMarker */); 7735 } 7736 } 7737 7738 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7739 boolean removeBaseMarker) { 7740 if (pkg.isForwardLocked()) { 7741 return; 7742 } 7743 7744 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7745 try { 7746 path = PackageManagerServiceUtils.realpath(new File(path)); 7747 } catch (IOException e) { 7748 // TODO: Should we return early here ? 7749 Slog.w(TAG, "Failed to get canonical path", e); 7750 continue; 7751 } 7752 7753 final String useMarker = path.replace('/', '@'); 7754 for (int realUserId : resolveUserIds(userId)) { 7755 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7756 if (removeBaseMarker) { 7757 File foreignUseMark = new File(profileDir, useMarker); 7758 if (foreignUseMark.exists()) { 7759 if (!foreignUseMark.delete()) { 7760 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7761 + pkg.packageName); 7762 } 7763 } 7764 } 7765 7766 File[] markers = profileDir.listFiles(); 7767 if (markers != null) { 7768 final String searchString = "@" + pkg.packageName + "@"; 7769 // We also delete all markers that contain the package name we're 7770 // uninstalling. These are associated with secondary dex-files belonging 7771 // to the package. Reconstructing the path of these dex files is messy 7772 // in general. 7773 for (File marker : markers) { 7774 if (marker.getName().indexOf(searchString) > 0) { 7775 if (!marker.delete()) { 7776 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7777 + pkg.packageName); 7778 } 7779 } 7780 } 7781 } 7782 } 7783 } 7784 } 7785 7786 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7787 try { 7788 mInstaller.destroyAppProfiles(pkg.packageName); 7789 } catch (InstallerException e) { 7790 Slog.w(TAG, String.valueOf(e)); 7791 } 7792 } 7793 7794 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7795 if (pkg == null) { 7796 Slog.wtf(TAG, "Package was null!", new Throwable()); 7797 return; 7798 } 7799 clearAppProfilesLeafLIF(pkg); 7800 // We don't remove the base foreign use marker when clearing profiles because 7801 // we will rename it when the app is updated. Unlike the actual profile contents, 7802 // the foreign use marker is good across installs. 7803 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7804 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7805 for (int i = 0; i < childCount; i++) { 7806 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7807 } 7808 } 7809 7810 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7811 try { 7812 mInstaller.clearAppProfiles(pkg.packageName); 7813 } catch (InstallerException e) { 7814 Slog.w(TAG, String.valueOf(e)); 7815 } 7816 } 7817 7818 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7819 long lastUpdateTime) { 7820 // Set parent install/update time 7821 PackageSetting ps = (PackageSetting) pkg.mExtras; 7822 if (ps != null) { 7823 ps.firstInstallTime = firstInstallTime; 7824 ps.lastUpdateTime = lastUpdateTime; 7825 } 7826 // Set children install/update time 7827 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7828 for (int i = 0; i < childCount; i++) { 7829 PackageParser.Package childPkg = pkg.childPackages.get(i); 7830 ps = (PackageSetting) childPkg.mExtras; 7831 if (ps != null) { 7832 ps.firstInstallTime = firstInstallTime; 7833 ps.lastUpdateTime = lastUpdateTime; 7834 } 7835 } 7836 } 7837 7838 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7839 PackageParser.Package changingLib) { 7840 if (file.path != null) { 7841 usesLibraryFiles.add(file.path); 7842 return; 7843 } 7844 PackageParser.Package p = mPackages.get(file.apk); 7845 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7846 // If we are doing this while in the middle of updating a library apk, 7847 // then we need to make sure to use that new apk for determining the 7848 // dependencies here. (We haven't yet finished committing the new apk 7849 // to the package manager state.) 7850 if (p == null || p.packageName.equals(changingLib.packageName)) { 7851 p = changingLib; 7852 } 7853 } 7854 if (p != null) { 7855 usesLibraryFiles.addAll(p.getAllCodePaths()); 7856 } 7857 } 7858 7859 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7860 PackageParser.Package changingLib) throws PackageManagerException { 7861 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7862 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7863 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7864 for (int i=0; i<N; i++) { 7865 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7866 if (file == null) { 7867 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7868 "Package " + pkg.packageName + " requires unavailable shared library " 7869 + pkg.usesLibraries.get(i) + "; failing!"); 7870 } 7871 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7872 } 7873 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7874 for (int i=0; i<N; i++) { 7875 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7876 if (file == null) { 7877 Slog.w(TAG, "Package " + pkg.packageName 7878 + " desires unavailable shared library " 7879 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7880 } else { 7881 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7882 } 7883 } 7884 N = usesLibraryFiles.size(); 7885 if (N > 0) { 7886 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7887 } else { 7888 pkg.usesLibraryFiles = null; 7889 } 7890 } 7891 } 7892 7893 private static boolean hasString(List<String> list, List<String> which) { 7894 if (list == null) { 7895 return false; 7896 } 7897 for (int i=list.size()-1; i>=0; i--) { 7898 for (int j=which.size()-1; j>=0; j--) { 7899 if (which.get(j).equals(list.get(i))) { 7900 return true; 7901 } 7902 } 7903 } 7904 return false; 7905 } 7906 7907 private void updateAllSharedLibrariesLPw() { 7908 for (PackageParser.Package pkg : mPackages.values()) { 7909 try { 7910 updateSharedLibrariesLPw(pkg, null); 7911 } catch (PackageManagerException e) { 7912 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7913 } 7914 } 7915 } 7916 7917 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7918 PackageParser.Package changingPkg) { 7919 ArrayList<PackageParser.Package> res = null; 7920 for (PackageParser.Package pkg : mPackages.values()) { 7921 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7922 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7923 if (res == null) { 7924 res = new ArrayList<PackageParser.Package>(); 7925 } 7926 res.add(pkg); 7927 try { 7928 updateSharedLibrariesLPw(pkg, changingPkg); 7929 } catch (PackageManagerException e) { 7930 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7931 } 7932 } 7933 } 7934 return res; 7935 } 7936 7937 /** 7938 * Derive the value of the {@code cpuAbiOverride} based on the provided 7939 * value and an optional stored value from the package settings. 7940 */ 7941 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7942 String cpuAbiOverride = null; 7943 7944 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7945 cpuAbiOverride = null; 7946 } else if (abiOverride != null) { 7947 cpuAbiOverride = abiOverride; 7948 } else if (settings != null) { 7949 cpuAbiOverride = settings.cpuAbiOverrideString; 7950 } 7951 7952 return cpuAbiOverride; 7953 } 7954 7955 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7956 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7957 throws PackageManagerException { 7958 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7959 // If the package has children and this is the first dive in the function 7960 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7961 // whether all packages (parent and children) would be successfully scanned 7962 // before the actual scan since scanning mutates internal state and we want 7963 // to atomically install the package and its children. 7964 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7965 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7966 scanFlags |= SCAN_CHECK_ONLY; 7967 } 7968 } else { 7969 scanFlags &= ~SCAN_CHECK_ONLY; 7970 } 7971 7972 final PackageParser.Package scannedPkg; 7973 try { 7974 // Scan the parent 7975 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7976 // Scan the children 7977 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7978 for (int i = 0; i < childCount; i++) { 7979 PackageParser.Package childPkg = pkg.childPackages.get(i); 7980 scanPackageLI(childPkg, policyFlags, 7981 scanFlags, currentTime, user); 7982 } 7983 } finally { 7984 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7985 } 7986 7987 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7988 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7989 } 7990 7991 return scannedPkg; 7992 } 7993 7994 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7995 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7996 boolean success = false; 7997 try { 7998 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7999 currentTime, user); 8000 success = true; 8001 return res; 8002 } finally { 8003 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8004 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8005 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8006 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8007 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8008 } 8009 } 8010 } 8011 8012 /** 8013 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8014 */ 8015 private static boolean apkHasCode(String fileName) { 8016 StrictJarFile jarFile = null; 8017 try { 8018 jarFile = new StrictJarFile(fileName, 8019 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8020 return jarFile.findEntry("classes.dex") != null; 8021 } catch (IOException ignore) { 8022 } finally { 8023 try { 8024 jarFile.close(); 8025 } catch (IOException ignore) {} 8026 } 8027 return false; 8028 } 8029 8030 /** 8031 * Enforces code policy for the package. This ensures that if an APK has 8032 * declared hasCode="true" in its manifest that the APK actually contains 8033 * code. 8034 * 8035 * @throws PackageManagerException If bytecode could not be found when it should exist 8036 */ 8037 private static void enforceCodePolicy(PackageParser.Package pkg) 8038 throws PackageManagerException { 8039 final boolean shouldHaveCode = 8040 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8041 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8042 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8043 "Package " + pkg.baseCodePath + " code is missing"); 8044 } 8045 8046 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8047 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8048 final boolean splitShouldHaveCode = 8049 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8050 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8051 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8052 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8053 } 8054 } 8055 } 8056 } 8057 8058 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8059 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8060 throws PackageManagerException { 8061 final File scanFile = new File(pkg.codePath); 8062 if (pkg.applicationInfo.getCodePath() == null || 8063 pkg.applicationInfo.getResourcePath() == null) { 8064 // Bail out. The resource and code paths haven't been set. 8065 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8066 "Code and resource paths haven't been set correctly"); 8067 } 8068 8069 // Apply policy 8070 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8071 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8072 if (pkg.applicationInfo.isDirectBootAware()) { 8073 // we're direct boot aware; set for all components 8074 for (PackageParser.Service s : pkg.services) { 8075 s.info.encryptionAware = s.info.directBootAware = true; 8076 } 8077 for (PackageParser.Provider p : pkg.providers) { 8078 p.info.encryptionAware = p.info.directBootAware = true; 8079 } 8080 for (PackageParser.Activity a : pkg.activities) { 8081 a.info.encryptionAware = a.info.directBootAware = true; 8082 } 8083 for (PackageParser.Activity r : pkg.receivers) { 8084 r.info.encryptionAware = r.info.directBootAware = true; 8085 } 8086 } 8087 } else { 8088 // Only allow system apps to be flagged as core apps. 8089 pkg.coreApp = false; 8090 // clear flags not applicable to regular apps 8091 pkg.applicationInfo.privateFlags &= 8092 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8093 pkg.applicationInfo.privateFlags &= 8094 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8095 } 8096 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8097 8098 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8099 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8100 } 8101 8102 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8103 enforceCodePolicy(pkg); 8104 } 8105 8106 if (mCustomResolverComponentName != null && 8107 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8108 setUpCustomResolverActivity(pkg); 8109 } 8110 8111 if (pkg.packageName.equals("android")) { 8112 synchronized (mPackages) { 8113 if (mAndroidApplication != null) { 8114 Slog.w(TAG, "*************************************************"); 8115 Slog.w(TAG, "Core android package being redefined. Skipping."); 8116 Slog.w(TAG, " file=" + scanFile); 8117 Slog.w(TAG, "*************************************************"); 8118 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8119 "Core android package being redefined. Skipping."); 8120 } 8121 8122 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8123 // Set up information for our fall-back user intent resolution activity. 8124 mPlatformPackage = pkg; 8125 pkg.mVersionCode = mSdkVersion; 8126 mAndroidApplication = pkg.applicationInfo; 8127 8128 if (!mResolverReplaced) { 8129 mResolveActivity.applicationInfo = mAndroidApplication; 8130 mResolveActivity.name = ResolverActivity.class.getName(); 8131 mResolveActivity.packageName = mAndroidApplication.packageName; 8132 mResolveActivity.processName = "system:ui"; 8133 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8134 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8135 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8136 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8137 mResolveActivity.exported = true; 8138 mResolveActivity.enabled = true; 8139 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8140 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8141 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8142 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8143 | ActivityInfo.CONFIG_ORIENTATION 8144 | ActivityInfo.CONFIG_KEYBOARD 8145 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8146 mResolveInfo.activityInfo = mResolveActivity; 8147 mResolveInfo.priority = 0; 8148 mResolveInfo.preferredOrder = 0; 8149 mResolveInfo.match = 0; 8150 mResolveComponentName = new ComponentName( 8151 mAndroidApplication.packageName, mResolveActivity.name); 8152 } 8153 } 8154 } 8155 } 8156 8157 if (DEBUG_PACKAGE_SCANNING) { 8158 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8159 Log.d(TAG, "Scanning package " + pkg.packageName); 8160 } 8161 8162 synchronized (mPackages) { 8163 if (mPackages.containsKey(pkg.packageName) 8164 || mSharedLibraries.containsKey(pkg.packageName)) { 8165 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8166 "Application package " + pkg.packageName 8167 + " already installed. Skipping duplicate."); 8168 } 8169 8170 // If we're only installing presumed-existing packages, require that the 8171 // scanned APK is both already known and at the path previously established 8172 // for it. Previously unknown packages we pick up normally, but if we have an 8173 // a priori expectation about this package's install presence, enforce it. 8174 // With a singular exception for new system packages. When an OTA contains 8175 // a new system package, we allow the codepath to change from a system location 8176 // to the user-installed location. If we don't allow this change, any newer, 8177 // user-installed version of the application will be ignored. 8178 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8179 if (mExpectingBetter.containsKey(pkg.packageName)) { 8180 logCriticalInfo(Log.WARN, 8181 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8182 } else { 8183 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8184 if (known != null) { 8185 if (DEBUG_PACKAGE_SCANNING) { 8186 Log.d(TAG, "Examining " + pkg.codePath 8187 + " and requiring known paths " + known.codePathString 8188 + " & " + known.resourcePathString); 8189 } 8190 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8191 || !pkg.applicationInfo.getResourcePath().equals( 8192 known.resourcePathString)) { 8193 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8194 "Application package " + pkg.packageName 8195 + " found at " + pkg.applicationInfo.getCodePath() 8196 + " but expected at " + known.codePathString 8197 + "; ignoring."); 8198 } 8199 } 8200 } 8201 } 8202 } 8203 8204 // Initialize package source and resource directories 8205 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8206 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8207 8208 SharedUserSetting suid = null; 8209 PackageSetting pkgSetting = null; 8210 8211 if (!isSystemApp(pkg)) { 8212 // Only system apps can use these features. 8213 pkg.mOriginalPackages = null; 8214 pkg.mRealPackage = null; 8215 pkg.mAdoptPermissions = null; 8216 } 8217 8218 // Getting the package setting may have a side-effect, so if we 8219 // are only checking if scan would succeed, stash a copy of the 8220 // old setting to restore at the end. 8221 PackageSetting nonMutatedPs = null; 8222 8223 // writer 8224 synchronized (mPackages) { 8225 if (pkg.mSharedUserId != null) { 8226 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8227 if (suid == null) { 8228 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8229 "Creating application package " + pkg.packageName 8230 + " for shared user failed"); 8231 } 8232 if (DEBUG_PACKAGE_SCANNING) { 8233 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8234 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8235 + "): packages=" + suid.packages); 8236 } 8237 } 8238 8239 // Check if we are renaming from an original package name. 8240 PackageSetting origPackage = null; 8241 String realName = null; 8242 if (pkg.mOriginalPackages != null) { 8243 // This package may need to be renamed to a previously 8244 // installed name. Let's check on that... 8245 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8246 if (pkg.mOriginalPackages.contains(renamed)) { 8247 // This package had originally been installed as the 8248 // original name, and we have already taken care of 8249 // transitioning to the new one. Just update the new 8250 // one to continue using the old name. 8251 realName = pkg.mRealPackage; 8252 if (!pkg.packageName.equals(renamed)) { 8253 // Callers into this function may have already taken 8254 // care of renaming the package; only do it here if 8255 // it is not already done. 8256 pkg.setPackageName(renamed); 8257 } 8258 8259 } else { 8260 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8261 if ((origPackage = mSettings.peekPackageLPr( 8262 pkg.mOriginalPackages.get(i))) != null) { 8263 // We do have the package already installed under its 8264 // original name... should we use it? 8265 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8266 // New package is not compatible with original. 8267 origPackage = null; 8268 continue; 8269 } else if (origPackage.sharedUser != null) { 8270 // Make sure uid is compatible between packages. 8271 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8272 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8273 + " to " + pkg.packageName + ": old uid " 8274 + origPackage.sharedUser.name 8275 + " differs from " + pkg.mSharedUserId); 8276 origPackage = null; 8277 continue; 8278 } 8279 // TODO: Add case when shared user id is added [b/28144775] 8280 } else { 8281 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8282 + pkg.packageName + " to old name " + origPackage.name); 8283 } 8284 break; 8285 } 8286 } 8287 } 8288 } 8289 8290 if (mTransferedPackages.contains(pkg.packageName)) { 8291 Slog.w(TAG, "Package " + pkg.packageName 8292 + " was transferred to another, but its .apk remains"); 8293 } 8294 8295 // See comments in nonMutatedPs declaration 8296 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8297 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8298 if (foundPs != null) { 8299 nonMutatedPs = new PackageSetting(foundPs); 8300 } 8301 } 8302 8303 // Just create the setting, don't add it yet. For already existing packages 8304 // the PkgSetting exists already and doesn't have to be created. 8305 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8306 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8307 pkg.applicationInfo.primaryCpuAbi, 8308 pkg.applicationInfo.secondaryCpuAbi, 8309 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8310 user, false); 8311 if (pkgSetting == null) { 8312 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8313 "Creating application package " + pkg.packageName + " failed"); 8314 } 8315 8316 if (pkgSetting.origPackage != null) { 8317 // If we are first transitioning from an original package, 8318 // fix up the new package's name now. We need to do this after 8319 // looking up the package under its new name, so getPackageLP 8320 // can take care of fiddling things correctly. 8321 pkg.setPackageName(origPackage.name); 8322 8323 // File a report about this. 8324 String msg = "New package " + pkgSetting.realName 8325 + " renamed to replace old package " + pkgSetting.name; 8326 reportSettingsProblem(Log.WARN, msg); 8327 8328 // Make a note of it. 8329 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8330 mTransferedPackages.add(origPackage.name); 8331 } 8332 8333 // No longer need to retain this. 8334 pkgSetting.origPackage = null; 8335 } 8336 8337 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8338 // Make a note of it. 8339 mTransferedPackages.add(pkg.packageName); 8340 } 8341 8342 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8343 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8344 } 8345 8346 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8347 // Check all shared libraries and map to their actual file path. 8348 // We only do this here for apps not on a system dir, because those 8349 // are the only ones that can fail an install due to this. We 8350 // will take care of the system apps by updating all of their 8351 // library paths after the scan is done. 8352 updateSharedLibrariesLPw(pkg, null); 8353 } 8354 8355 if (mFoundPolicyFile) { 8356 SELinuxMMAC.assignSeinfoValue(pkg); 8357 } 8358 8359 pkg.applicationInfo.uid = pkgSetting.appId; 8360 pkg.mExtras = pkgSetting; 8361 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8362 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8363 // We just determined the app is signed correctly, so bring 8364 // over the latest parsed certs. 8365 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8366 } else { 8367 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8368 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8369 "Package " + pkg.packageName + " upgrade keys do not match the " 8370 + "previously installed version"); 8371 } else { 8372 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8373 String msg = "System package " + pkg.packageName 8374 + " signature changed; retaining data."; 8375 reportSettingsProblem(Log.WARN, msg); 8376 } 8377 } 8378 } else { 8379 try { 8380 verifySignaturesLP(pkgSetting, pkg); 8381 // We just determined the app is signed correctly, so bring 8382 // over the latest parsed certs. 8383 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8384 } catch (PackageManagerException e) { 8385 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8386 throw e; 8387 } 8388 // The signature has changed, but this package is in the system 8389 // image... let's recover! 8390 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8391 // However... if this package is part of a shared user, but it 8392 // doesn't match the signature of the shared user, let's fail. 8393 // What this means is that you can't change the signatures 8394 // associated with an overall shared user, which doesn't seem all 8395 // that unreasonable. 8396 if (pkgSetting.sharedUser != null) { 8397 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8398 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8399 throw new PackageManagerException( 8400 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8401 "Signature mismatch for shared user: " 8402 + pkgSetting.sharedUser); 8403 } 8404 } 8405 // File a report about this. 8406 String msg = "System package " + pkg.packageName 8407 + " signature changed; retaining data."; 8408 reportSettingsProblem(Log.WARN, msg); 8409 } 8410 } 8411 // Verify that this new package doesn't have any content providers 8412 // that conflict with existing packages. Only do this if the 8413 // package isn't already installed, since we don't want to break 8414 // things that are installed. 8415 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8416 final int N = pkg.providers.size(); 8417 int i; 8418 for (i=0; i<N; i++) { 8419 PackageParser.Provider p = pkg.providers.get(i); 8420 if (p.info.authority != null) { 8421 String names[] = p.info.authority.split(";"); 8422 for (int j = 0; j < names.length; j++) { 8423 if (mProvidersByAuthority.containsKey(names[j])) { 8424 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8425 final String otherPackageName = 8426 ((other != null && other.getComponentName() != null) ? 8427 other.getComponentName().getPackageName() : "?"); 8428 throw new PackageManagerException( 8429 INSTALL_FAILED_CONFLICTING_PROVIDER, 8430 "Can't install because provider name " + names[j] 8431 + " (in package " + pkg.applicationInfo.packageName 8432 + ") is already used by " + otherPackageName); 8433 } 8434 } 8435 } 8436 } 8437 } 8438 8439 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8440 // This package wants to adopt ownership of permissions from 8441 // another package. 8442 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8443 final String origName = pkg.mAdoptPermissions.get(i); 8444 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8445 if (orig != null) { 8446 if (verifyPackageUpdateLPr(orig, pkg)) { 8447 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8448 + pkg.packageName); 8449 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8450 } 8451 } 8452 } 8453 } 8454 } 8455 8456 final String pkgName = pkg.packageName; 8457 8458 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8459 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8460 pkg.applicationInfo.processName = fixProcessName( 8461 pkg.applicationInfo.packageName, 8462 pkg.applicationInfo.processName, 8463 pkg.applicationInfo.uid); 8464 8465 if (pkg != mPlatformPackage) { 8466 // Get all of our default paths setup 8467 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8468 } 8469 8470 final String path = scanFile.getPath(); 8471 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8472 8473 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8474 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8475 8476 // Some system apps still use directory structure for native libraries 8477 // in which case we might end up not detecting abi solely based on apk 8478 // structure. Try to detect abi based on directory structure. 8479 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8480 pkg.applicationInfo.primaryCpuAbi == null) { 8481 setBundledAppAbisAndRoots(pkg, pkgSetting); 8482 setNativeLibraryPaths(pkg); 8483 } 8484 8485 } else { 8486 if ((scanFlags & SCAN_MOVE) != 0) { 8487 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8488 // but we already have this packages package info in the PackageSetting. We just 8489 // use that and derive the native library path based on the new codepath. 8490 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8491 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8492 } 8493 8494 // Set native library paths again. For moves, the path will be updated based on the 8495 // ABIs we've determined above. For non-moves, the path will be updated based on the 8496 // ABIs we determined during compilation, but the path will depend on the final 8497 // package path (after the rename away from the stage path). 8498 setNativeLibraryPaths(pkg); 8499 } 8500 8501 // This is a special case for the "system" package, where the ABI is 8502 // dictated by the zygote configuration (and init.rc). We should keep track 8503 // of this ABI so that we can deal with "normal" applications that run under 8504 // the same UID correctly. 8505 if (mPlatformPackage == pkg) { 8506 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8507 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8508 } 8509 8510 // If there's a mismatch between the abi-override in the package setting 8511 // and the abiOverride specified for the install. Warn about this because we 8512 // would've already compiled the app without taking the package setting into 8513 // account. 8514 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8515 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8516 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8517 " for package " + pkg.packageName); 8518 } 8519 } 8520 8521 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8522 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8523 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8524 8525 // Copy the derived override back to the parsed package, so that we can 8526 // update the package settings accordingly. 8527 pkg.cpuAbiOverride = cpuAbiOverride; 8528 8529 if (DEBUG_ABI_SELECTION) { 8530 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8531 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8532 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8533 } 8534 8535 // Push the derived path down into PackageSettings so we know what to 8536 // clean up at uninstall time. 8537 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8538 8539 if (DEBUG_ABI_SELECTION) { 8540 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8541 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8542 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8543 } 8544 8545 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8546 // We don't do this here during boot because we can do it all 8547 // at once after scanning all existing packages. 8548 // 8549 // We also do this *before* we perform dexopt on this package, so that 8550 // we can avoid redundant dexopts, and also to make sure we've got the 8551 // code and package path correct. 8552 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8553 pkg, true /* boot complete */); 8554 } 8555 8556 if (mFactoryTest && pkg.requestedPermissions.contains( 8557 android.Manifest.permission.FACTORY_TEST)) { 8558 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8559 } 8560 8561 ArrayList<PackageParser.Package> clientLibPkgs = null; 8562 8563 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8564 if (nonMutatedPs != null) { 8565 synchronized (mPackages) { 8566 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8567 } 8568 } 8569 return pkg; 8570 } 8571 8572 // Only privileged apps and updated privileged apps can add child packages. 8573 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8574 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8575 throw new PackageManagerException("Only privileged apps and updated " 8576 + "privileged apps can add child packages. Ignoring package " 8577 + pkg.packageName); 8578 } 8579 final int childCount = pkg.childPackages.size(); 8580 for (int i = 0; i < childCount; i++) { 8581 PackageParser.Package childPkg = pkg.childPackages.get(i); 8582 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8583 childPkg.packageName)) { 8584 throw new PackageManagerException("Cannot override a child package of " 8585 + "another disabled system app. Ignoring package " + pkg.packageName); 8586 } 8587 } 8588 } 8589 8590 // writer 8591 synchronized (mPackages) { 8592 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8593 // Only system apps can add new shared libraries. 8594 if (pkg.libraryNames != null) { 8595 for (int i=0; i<pkg.libraryNames.size(); i++) { 8596 String name = pkg.libraryNames.get(i); 8597 boolean allowed = false; 8598 if (pkg.isUpdatedSystemApp()) { 8599 // New library entries can only be added through the 8600 // system image. This is important to get rid of a lot 8601 // of nasty edge cases: for example if we allowed a non- 8602 // system update of the app to add a library, then uninstalling 8603 // the update would make the library go away, and assumptions 8604 // we made such as through app install filtering would now 8605 // have allowed apps on the device which aren't compatible 8606 // with it. Better to just have the restriction here, be 8607 // conservative, and create many fewer cases that can negatively 8608 // impact the user experience. 8609 final PackageSetting sysPs = mSettings 8610 .getDisabledSystemPkgLPr(pkg.packageName); 8611 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8612 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8613 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8614 allowed = true; 8615 break; 8616 } 8617 } 8618 } 8619 } else { 8620 allowed = true; 8621 } 8622 if (allowed) { 8623 if (!mSharedLibraries.containsKey(name)) { 8624 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8625 } else if (!name.equals(pkg.packageName)) { 8626 Slog.w(TAG, "Package " + pkg.packageName + " library " 8627 + name + " already exists; skipping"); 8628 } 8629 } else { 8630 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8631 + name + " that is not declared on system image; skipping"); 8632 } 8633 } 8634 if ((scanFlags & SCAN_BOOTING) == 0) { 8635 // If we are not booting, we need to update any applications 8636 // that are clients of our shared library. If we are booting, 8637 // this will all be done once the scan is complete. 8638 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8639 } 8640 } 8641 } 8642 } 8643 8644 if ((scanFlags & SCAN_BOOTING) != 0) { 8645 // No apps can run during boot scan, so they don't need to be frozen 8646 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8647 // Caller asked to not kill app, so it's probably not frozen 8648 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8649 // Caller asked us to ignore frozen check for some reason; they 8650 // probably didn't know the package name 8651 } else { 8652 // We're doing major surgery on this package, so it better be frozen 8653 // right now to keep it from launching 8654 checkPackageFrozen(pkgName); 8655 } 8656 8657 // Also need to kill any apps that are dependent on the library. 8658 if (clientLibPkgs != null) { 8659 for (int i=0; i<clientLibPkgs.size(); i++) { 8660 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8661 killApplication(clientPkg.applicationInfo.packageName, 8662 clientPkg.applicationInfo.uid, "update lib"); 8663 } 8664 } 8665 8666 // Make sure we're not adding any bogus keyset info 8667 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8668 ksms.assertScannedPackageValid(pkg); 8669 8670 // writer 8671 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8672 8673 boolean createIdmapFailed = false; 8674 synchronized (mPackages) { 8675 // We don't expect installation to fail beyond this point 8676 8677 if (pkgSetting.pkg != null) { 8678 // Note that |user| might be null during the initial boot scan. If a codePath 8679 // for an app has changed during a boot scan, it's due to an app update that's 8680 // part of the system partition and marker changes must be applied to all users. 8681 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8682 (user != null) ? user : UserHandle.ALL); 8683 } 8684 8685 // Add the new setting to mSettings 8686 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8687 // Add the new setting to mPackages 8688 mPackages.put(pkg.applicationInfo.packageName, pkg); 8689 // Make sure we don't accidentally delete its data. 8690 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8691 while (iter.hasNext()) { 8692 PackageCleanItem item = iter.next(); 8693 if (pkgName.equals(item.packageName)) { 8694 iter.remove(); 8695 } 8696 } 8697 8698 // Take care of first install / last update times. 8699 if (currentTime != 0) { 8700 if (pkgSetting.firstInstallTime == 0) { 8701 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8702 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8703 pkgSetting.lastUpdateTime = currentTime; 8704 } 8705 } else if (pkgSetting.firstInstallTime == 0) { 8706 // We need *something*. Take time time stamp of the file. 8707 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8708 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8709 if (scanFileTime != pkgSetting.timeStamp) { 8710 // A package on the system image has changed; consider this 8711 // to be an update. 8712 pkgSetting.lastUpdateTime = scanFileTime; 8713 } 8714 } 8715 8716 // Add the package's KeySets to the global KeySetManagerService 8717 ksms.addScannedPackageLPw(pkg); 8718 8719 int N = pkg.providers.size(); 8720 StringBuilder r = null; 8721 int i; 8722 for (i=0; i<N; i++) { 8723 PackageParser.Provider p = pkg.providers.get(i); 8724 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8725 p.info.processName, pkg.applicationInfo.uid); 8726 mProviders.addProvider(p); 8727 p.syncable = p.info.isSyncable; 8728 if (p.info.authority != null) { 8729 String names[] = p.info.authority.split(";"); 8730 p.info.authority = null; 8731 for (int j = 0; j < names.length; j++) { 8732 if (j == 1 && p.syncable) { 8733 // We only want the first authority for a provider to possibly be 8734 // syncable, so if we already added this provider using a different 8735 // authority clear the syncable flag. We copy the provider before 8736 // changing it because the mProviders object contains a reference 8737 // to a provider that we don't want to change. 8738 // Only do this for the second authority since the resulting provider 8739 // object can be the same for all future authorities for this provider. 8740 p = new PackageParser.Provider(p); 8741 p.syncable = false; 8742 } 8743 if (!mProvidersByAuthority.containsKey(names[j])) { 8744 mProvidersByAuthority.put(names[j], p); 8745 if (p.info.authority == null) { 8746 p.info.authority = names[j]; 8747 } else { 8748 p.info.authority = p.info.authority + ";" + names[j]; 8749 } 8750 if (DEBUG_PACKAGE_SCANNING) { 8751 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8752 Log.d(TAG, "Registered content provider: " + names[j] 8753 + ", className = " + p.info.name + ", isSyncable = " 8754 + p.info.isSyncable); 8755 } 8756 } else { 8757 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8758 Slog.w(TAG, "Skipping provider name " + names[j] + 8759 " (in package " + pkg.applicationInfo.packageName + 8760 "): name already used by " 8761 + ((other != null && other.getComponentName() != null) 8762 ? other.getComponentName().getPackageName() : "?")); 8763 } 8764 } 8765 } 8766 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8767 if (r == null) { 8768 r = new StringBuilder(256); 8769 } else { 8770 r.append(' '); 8771 } 8772 r.append(p.info.name); 8773 } 8774 } 8775 if (r != null) { 8776 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8777 } 8778 8779 N = pkg.services.size(); 8780 r = null; 8781 for (i=0; i<N; i++) { 8782 PackageParser.Service s = pkg.services.get(i); 8783 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8784 s.info.processName, pkg.applicationInfo.uid); 8785 mServices.addService(s); 8786 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8787 if (r == null) { 8788 r = new StringBuilder(256); 8789 } else { 8790 r.append(' '); 8791 } 8792 r.append(s.info.name); 8793 } 8794 } 8795 if (r != null) { 8796 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8797 } 8798 8799 N = pkg.receivers.size(); 8800 r = null; 8801 for (i=0; i<N; i++) { 8802 PackageParser.Activity a = pkg.receivers.get(i); 8803 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8804 a.info.processName, pkg.applicationInfo.uid); 8805 mReceivers.addActivity(a, "receiver"); 8806 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8807 if (r == null) { 8808 r = new StringBuilder(256); 8809 } else { 8810 r.append(' '); 8811 } 8812 r.append(a.info.name); 8813 } 8814 } 8815 if (r != null) { 8816 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8817 } 8818 8819 N = pkg.activities.size(); 8820 r = null; 8821 for (i=0; i<N; i++) { 8822 PackageParser.Activity a = pkg.activities.get(i); 8823 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8824 a.info.processName, pkg.applicationInfo.uid); 8825 mActivities.addActivity(a, "activity"); 8826 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8827 if (r == null) { 8828 r = new StringBuilder(256); 8829 } else { 8830 r.append(' '); 8831 } 8832 r.append(a.info.name); 8833 } 8834 } 8835 if (r != null) { 8836 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8837 } 8838 8839 N = pkg.permissionGroups.size(); 8840 r = null; 8841 for (i=0; i<N; i++) { 8842 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8843 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8844 if (cur == null) { 8845 mPermissionGroups.put(pg.info.name, pg); 8846 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8847 if (r == null) { 8848 r = new StringBuilder(256); 8849 } else { 8850 r.append(' '); 8851 } 8852 r.append(pg.info.name); 8853 } 8854 } else { 8855 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8856 + pg.info.packageName + " ignored: original from " 8857 + cur.info.packageName); 8858 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8859 if (r == null) { 8860 r = new StringBuilder(256); 8861 } else { 8862 r.append(' '); 8863 } 8864 r.append("DUP:"); 8865 r.append(pg.info.name); 8866 } 8867 } 8868 } 8869 if (r != null) { 8870 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8871 } 8872 8873 N = pkg.permissions.size(); 8874 r = null; 8875 for (i=0; i<N; i++) { 8876 PackageParser.Permission p = pkg.permissions.get(i); 8877 8878 // Assume by default that we did not install this permission into the system. 8879 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8880 8881 // Now that permission groups have a special meaning, we ignore permission 8882 // groups for legacy apps to prevent unexpected behavior. In particular, 8883 // permissions for one app being granted to someone just becase they happen 8884 // to be in a group defined by another app (before this had no implications). 8885 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8886 p.group = mPermissionGroups.get(p.info.group); 8887 // Warn for a permission in an unknown group. 8888 if (p.info.group != null && p.group == null) { 8889 Slog.w(TAG, "Permission " + p.info.name + " from package " 8890 + p.info.packageName + " in an unknown group " + p.info.group); 8891 } 8892 } 8893 8894 ArrayMap<String, BasePermission> permissionMap = 8895 p.tree ? mSettings.mPermissionTrees 8896 : mSettings.mPermissions; 8897 BasePermission bp = permissionMap.get(p.info.name); 8898 8899 // Allow system apps to redefine non-system permissions 8900 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8901 final boolean currentOwnerIsSystem = (bp.perm != null 8902 && isSystemApp(bp.perm.owner)); 8903 if (isSystemApp(p.owner)) { 8904 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8905 // It's a built-in permission and no owner, take ownership now 8906 bp.packageSetting = pkgSetting; 8907 bp.perm = p; 8908 bp.uid = pkg.applicationInfo.uid; 8909 bp.sourcePackage = p.info.packageName; 8910 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8911 } else if (!currentOwnerIsSystem) { 8912 String msg = "New decl " + p.owner + " of permission " 8913 + p.info.name + " is system; overriding " + bp.sourcePackage; 8914 reportSettingsProblem(Log.WARN, msg); 8915 bp = null; 8916 } 8917 } 8918 } 8919 8920 if (bp == null) { 8921 bp = new BasePermission(p.info.name, p.info.packageName, 8922 BasePermission.TYPE_NORMAL); 8923 permissionMap.put(p.info.name, bp); 8924 } 8925 8926 if (bp.perm == null) { 8927 if (bp.sourcePackage == null 8928 || bp.sourcePackage.equals(p.info.packageName)) { 8929 BasePermission tree = findPermissionTreeLP(p.info.name); 8930 if (tree == null 8931 || tree.sourcePackage.equals(p.info.packageName)) { 8932 bp.packageSetting = pkgSetting; 8933 bp.perm = p; 8934 bp.uid = pkg.applicationInfo.uid; 8935 bp.sourcePackage = p.info.packageName; 8936 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8937 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8938 if (r == null) { 8939 r = new StringBuilder(256); 8940 } else { 8941 r.append(' '); 8942 } 8943 r.append(p.info.name); 8944 } 8945 } else { 8946 Slog.w(TAG, "Permission " + p.info.name + " from package " 8947 + p.info.packageName + " ignored: base tree " 8948 + tree.name + " is from package " 8949 + tree.sourcePackage); 8950 } 8951 } else { 8952 Slog.w(TAG, "Permission " + p.info.name + " from package " 8953 + p.info.packageName + " ignored: original from " 8954 + bp.sourcePackage); 8955 } 8956 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8957 if (r == null) { 8958 r = new StringBuilder(256); 8959 } else { 8960 r.append(' '); 8961 } 8962 r.append("DUP:"); 8963 r.append(p.info.name); 8964 } 8965 if (bp.perm == p) { 8966 bp.protectionLevel = p.info.protectionLevel; 8967 } 8968 } 8969 8970 if (r != null) { 8971 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8972 } 8973 8974 N = pkg.instrumentation.size(); 8975 r = null; 8976 for (i=0; i<N; i++) { 8977 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8978 a.info.packageName = pkg.applicationInfo.packageName; 8979 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8980 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8981 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8982 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8983 a.info.dataDir = pkg.applicationInfo.dataDir; 8984 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8985 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8986 8987 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8988 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8989 mInstrumentation.put(a.getComponentName(), a); 8990 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8991 if (r == null) { 8992 r = new StringBuilder(256); 8993 } else { 8994 r.append(' '); 8995 } 8996 r.append(a.info.name); 8997 } 8998 } 8999 if (r != null) { 9000 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9001 } 9002 9003 if (pkg.protectedBroadcasts != null) { 9004 N = pkg.protectedBroadcasts.size(); 9005 for (i=0; i<N; i++) { 9006 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9007 } 9008 } 9009 9010 pkgSetting.setTimeStamp(scanFileTime); 9011 9012 // Create idmap files for pairs of (packages, overlay packages). 9013 // Note: "android", ie framework-res.apk, is handled by native layers. 9014 if (pkg.mOverlayTarget != null) { 9015 // This is an overlay package. 9016 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9017 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9018 mOverlays.put(pkg.mOverlayTarget, 9019 new ArrayMap<String, PackageParser.Package>()); 9020 } 9021 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9022 map.put(pkg.packageName, pkg); 9023 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9024 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9025 createIdmapFailed = true; 9026 } 9027 } 9028 } else if (mOverlays.containsKey(pkg.packageName) && 9029 !pkg.packageName.equals("android")) { 9030 // This is a regular package, with one or more known overlay packages. 9031 createIdmapsForPackageLI(pkg); 9032 } 9033 } 9034 9035 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9036 9037 if (createIdmapFailed) { 9038 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9039 "scanPackageLI failed to createIdmap"); 9040 } 9041 return pkg; 9042 } 9043 9044 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9045 PackageParser.Package update, UserHandle user) { 9046 if (existing.applicationInfo == null || update.applicationInfo == null) { 9047 // This isn't due to an app installation. 9048 return; 9049 } 9050 9051 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9052 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9053 9054 // The codePath hasn't changed, so there's nothing for us to do. 9055 if (Objects.equals(oldCodePath, newCodePath)) { 9056 return; 9057 } 9058 9059 File canonicalNewCodePath; 9060 try { 9061 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9062 } catch (IOException e) { 9063 Slog.w(TAG, "Failed to get canonical path.", e); 9064 return; 9065 } 9066 9067 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9068 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9069 // that the last component of the path (i.e, the name) doesn't need canonicalization 9070 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9071 // but may change in the future. Hopefully this function won't exist at that point. 9072 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9073 oldCodePath.getName()); 9074 9075 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9076 // with "@". 9077 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9078 if (!oldMarkerPrefix.endsWith("@")) { 9079 oldMarkerPrefix += "@"; 9080 } 9081 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9082 if (!newMarkerPrefix.endsWith("@")) { 9083 newMarkerPrefix += "@"; 9084 } 9085 9086 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9087 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9088 for (String updatedPath : updatedPaths) { 9089 String updatedPathName = new File(updatedPath).getName(); 9090 markerSuffixes.add(updatedPathName.replace('/', '@')); 9091 } 9092 9093 for (int userId : resolveUserIds(user.getIdentifier())) { 9094 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9095 9096 for (String markerSuffix : markerSuffixes) { 9097 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9098 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9099 if (oldForeignUseMark.exists()) { 9100 try { 9101 Os.rename(oldForeignUseMark.getAbsolutePath(), 9102 newForeignUseMark.getAbsolutePath()); 9103 } catch (ErrnoException e) { 9104 Slog.w(TAG, "Failed to rename foreign use marker", e); 9105 oldForeignUseMark.delete(); 9106 } 9107 } 9108 } 9109 } 9110 } 9111 9112 /** 9113 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9114 * is derived purely on the basis of the contents of {@code scanFile} and 9115 * {@code cpuAbiOverride}. 9116 * 9117 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9118 */ 9119 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9120 String cpuAbiOverride, boolean extractLibs) 9121 throws PackageManagerException { 9122 // TODO: We can probably be smarter about this stuff. For installed apps, 9123 // we can calculate this information at install time once and for all. For 9124 // system apps, we can probably assume that this information doesn't change 9125 // after the first boot scan. As things stand, we do lots of unnecessary work. 9126 9127 // Give ourselves some initial paths; we'll come back for another 9128 // pass once we've determined ABI below. 9129 setNativeLibraryPaths(pkg); 9130 9131 // We would never need to extract libs for forward-locked and external packages, 9132 // since the container service will do it for us. We shouldn't attempt to 9133 // extract libs from system app when it was not updated. 9134 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9135 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9136 extractLibs = false; 9137 } 9138 9139 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9140 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9141 9142 NativeLibraryHelper.Handle handle = null; 9143 try { 9144 handle = NativeLibraryHelper.Handle.create(pkg); 9145 // TODO(multiArch): This can be null for apps that didn't go through the 9146 // usual installation process. We can calculate it again, like we 9147 // do during install time. 9148 // 9149 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9150 // unnecessary. 9151 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9152 9153 // Null out the abis so that they can be recalculated. 9154 pkg.applicationInfo.primaryCpuAbi = null; 9155 pkg.applicationInfo.secondaryCpuAbi = null; 9156 if (isMultiArch(pkg.applicationInfo)) { 9157 // Warn if we've set an abiOverride for multi-lib packages.. 9158 // By definition, we need to copy both 32 and 64 bit libraries for 9159 // such packages. 9160 if (pkg.cpuAbiOverride != null 9161 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9162 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9163 } 9164 9165 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9166 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9167 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9168 if (extractLibs) { 9169 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9170 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9171 useIsaSpecificSubdirs); 9172 } else { 9173 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9174 } 9175 } 9176 9177 maybeThrowExceptionForMultiArchCopy( 9178 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9179 9180 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9181 if (extractLibs) { 9182 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9183 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9184 useIsaSpecificSubdirs); 9185 } else { 9186 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9187 } 9188 } 9189 9190 maybeThrowExceptionForMultiArchCopy( 9191 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9192 9193 if (abi64 >= 0) { 9194 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9195 } 9196 9197 if (abi32 >= 0) { 9198 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9199 if (abi64 >= 0) { 9200 if (pkg.use32bitAbi) { 9201 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9202 pkg.applicationInfo.primaryCpuAbi = abi; 9203 } else { 9204 pkg.applicationInfo.secondaryCpuAbi = abi; 9205 } 9206 } else { 9207 pkg.applicationInfo.primaryCpuAbi = abi; 9208 } 9209 } 9210 9211 } else { 9212 String[] abiList = (cpuAbiOverride != null) ? 9213 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9214 9215 // Enable gross and lame hacks for apps that are built with old 9216 // SDK tools. We must scan their APKs for renderscript bitcode and 9217 // not launch them if it's present. Don't bother checking on devices 9218 // that don't have 64 bit support. 9219 boolean needsRenderScriptOverride = false; 9220 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9221 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9222 abiList = Build.SUPPORTED_32_BIT_ABIS; 9223 needsRenderScriptOverride = true; 9224 } 9225 9226 final int copyRet; 9227 if (extractLibs) { 9228 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9229 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9230 } else { 9231 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9232 } 9233 9234 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9235 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9236 "Error unpackaging native libs for app, errorCode=" + copyRet); 9237 } 9238 9239 if (copyRet >= 0) { 9240 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9241 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9242 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9243 } else if (needsRenderScriptOverride) { 9244 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9245 } 9246 } 9247 } catch (IOException ioe) { 9248 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9249 } finally { 9250 IoUtils.closeQuietly(handle); 9251 } 9252 9253 // Now that we've calculated the ABIs and determined if it's an internal app, 9254 // we will go ahead and populate the nativeLibraryPath. 9255 setNativeLibraryPaths(pkg); 9256 } 9257 9258 /** 9259 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9260 * i.e, so that all packages can be run inside a single process if required. 9261 * 9262 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9263 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9264 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9265 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9266 * updating a package that belongs to a shared user. 9267 * 9268 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9269 * adds unnecessary complexity. 9270 */ 9271 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9272 PackageParser.Package scannedPackage, boolean bootComplete) { 9273 String requiredInstructionSet = null; 9274 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9275 requiredInstructionSet = VMRuntime.getInstructionSet( 9276 scannedPackage.applicationInfo.primaryCpuAbi); 9277 } 9278 9279 PackageSetting requirer = null; 9280 for (PackageSetting ps : packagesForUser) { 9281 // If packagesForUser contains scannedPackage, we skip it. This will happen 9282 // when scannedPackage is an update of an existing package. Without this check, 9283 // we will never be able to change the ABI of any package belonging to a shared 9284 // user, even if it's compatible with other packages. 9285 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9286 if (ps.primaryCpuAbiString == null) { 9287 continue; 9288 } 9289 9290 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9291 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9292 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9293 // this but there's not much we can do. 9294 String errorMessage = "Instruction set mismatch, " 9295 + ((requirer == null) ? "[caller]" : requirer) 9296 + " requires " + requiredInstructionSet + " whereas " + ps 9297 + " requires " + instructionSet; 9298 Slog.w(TAG, errorMessage); 9299 } 9300 9301 if (requiredInstructionSet == null) { 9302 requiredInstructionSet = instructionSet; 9303 requirer = ps; 9304 } 9305 } 9306 } 9307 9308 if (requiredInstructionSet != null) { 9309 String adjustedAbi; 9310 if (requirer != null) { 9311 // requirer != null implies that either scannedPackage was null or that scannedPackage 9312 // did not require an ABI, in which case we have to adjust scannedPackage to match 9313 // the ABI of the set (which is the same as requirer's ABI) 9314 adjustedAbi = requirer.primaryCpuAbiString; 9315 if (scannedPackage != null) { 9316 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9317 } 9318 } else { 9319 // requirer == null implies that we're updating all ABIs in the set to 9320 // match scannedPackage. 9321 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9322 } 9323 9324 for (PackageSetting ps : packagesForUser) { 9325 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9326 if (ps.primaryCpuAbiString != null) { 9327 continue; 9328 } 9329 9330 ps.primaryCpuAbiString = adjustedAbi; 9331 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9332 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9333 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9334 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9335 + " (requirer=" 9336 + (requirer == null ? "null" : requirer.pkg.packageName) 9337 + ", scannedPackage=" 9338 + (scannedPackage != null ? scannedPackage.packageName : "null") 9339 + ")"); 9340 try { 9341 mInstaller.rmdex(ps.codePathString, 9342 getDexCodeInstructionSet(getPreferredInstructionSet())); 9343 } catch (InstallerException ignored) { 9344 } 9345 } 9346 } 9347 } 9348 } 9349 } 9350 9351 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9352 synchronized (mPackages) { 9353 mResolverReplaced = true; 9354 // Set up information for custom user intent resolution activity. 9355 mResolveActivity.applicationInfo = pkg.applicationInfo; 9356 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9357 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9358 mResolveActivity.processName = pkg.applicationInfo.packageName; 9359 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9360 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9361 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9362 mResolveActivity.theme = 0; 9363 mResolveActivity.exported = true; 9364 mResolveActivity.enabled = true; 9365 mResolveInfo.activityInfo = mResolveActivity; 9366 mResolveInfo.priority = 0; 9367 mResolveInfo.preferredOrder = 0; 9368 mResolveInfo.match = 0; 9369 mResolveComponentName = mCustomResolverComponentName; 9370 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9371 mResolveComponentName); 9372 } 9373 } 9374 9375 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9376 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9377 9378 // Set up information for ephemeral installer activity 9379 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9380 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9381 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9382 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9383 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9384 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9385 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9386 mEphemeralInstallerActivity.theme = 0; 9387 mEphemeralInstallerActivity.exported = true; 9388 mEphemeralInstallerActivity.enabled = true; 9389 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9390 mEphemeralInstallerInfo.priority = 0; 9391 mEphemeralInstallerInfo.preferredOrder = 0; 9392 mEphemeralInstallerInfo.match = 0; 9393 9394 if (DEBUG_EPHEMERAL) { 9395 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9396 } 9397 } 9398 9399 private static String calculateBundledApkRoot(final String codePathString) { 9400 final File codePath = new File(codePathString); 9401 final File codeRoot; 9402 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9403 codeRoot = Environment.getRootDirectory(); 9404 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9405 codeRoot = Environment.getOemDirectory(); 9406 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9407 codeRoot = Environment.getVendorDirectory(); 9408 } else { 9409 // Unrecognized code path; take its top real segment as the apk root: 9410 // e.g. /something/app/blah.apk => /something 9411 try { 9412 File f = codePath.getCanonicalFile(); 9413 File parent = f.getParentFile(); // non-null because codePath is a file 9414 File tmp; 9415 while ((tmp = parent.getParentFile()) != null) { 9416 f = parent; 9417 parent = tmp; 9418 } 9419 codeRoot = f; 9420 Slog.w(TAG, "Unrecognized code path " 9421 + codePath + " - using " + codeRoot); 9422 } catch (IOException e) { 9423 // Can't canonicalize the code path -- shenanigans? 9424 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9425 return Environment.getRootDirectory().getPath(); 9426 } 9427 } 9428 return codeRoot.getPath(); 9429 } 9430 9431 /** 9432 * Derive and set the location of native libraries for the given package, 9433 * which varies depending on where and how the package was installed. 9434 */ 9435 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9436 final ApplicationInfo info = pkg.applicationInfo; 9437 final String codePath = pkg.codePath; 9438 final File codeFile = new File(codePath); 9439 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9440 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9441 9442 info.nativeLibraryRootDir = null; 9443 info.nativeLibraryRootRequiresIsa = false; 9444 info.nativeLibraryDir = null; 9445 info.secondaryNativeLibraryDir = null; 9446 9447 if (isApkFile(codeFile)) { 9448 // Monolithic install 9449 if (bundledApp) { 9450 // If "/system/lib64/apkname" exists, assume that is the per-package 9451 // native library directory to use; otherwise use "/system/lib/apkname". 9452 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9453 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9454 getPrimaryInstructionSet(info)); 9455 9456 // This is a bundled system app so choose the path based on the ABI. 9457 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9458 // is just the default path. 9459 final String apkName = deriveCodePathName(codePath); 9460 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9461 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9462 apkName).getAbsolutePath(); 9463 9464 if (info.secondaryCpuAbi != null) { 9465 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9466 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9467 secondaryLibDir, apkName).getAbsolutePath(); 9468 } 9469 } else if (asecApp) { 9470 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9471 .getAbsolutePath(); 9472 } else { 9473 final String apkName = deriveCodePathName(codePath); 9474 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9475 .getAbsolutePath(); 9476 } 9477 9478 info.nativeLibraryRootRequiresIsa = false; 9479 info.nativeLibraryDir = info.nativeLibraryRootDir; 9480 } else { 9481 // Cluster install 9482 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9483 info.nativeLibraryRootRequiresIsa = true; 9484 9485 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9486 getPrimaryInstructionSet(info)).getAbsolutePath(); 9487 9488 if (info.secondaryCpuAbi != null) { 9489 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9490 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9491 } 9492 } 9493 } 9494 9495 /** 9496 * Calculate the abis and roots for a bundled app. These can uniquely 9497 * be determined from the contents of the system partition, i.e whether 9498 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9499 * of this information, and instead assume that the system was built 9500 * sensibly. 9501 */ 9502 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9503 PackageSetting pkgSetting) { 9504 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9505 9506 // If "/system/lib64/apkname" exists, assume that is the per-package 9507 // native library directory to use; otherwise use "/system/lib/apkname". 9508 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9509 setBundledAppAbi(pkg, apkRoot, apkName); 9510 // pkgSetting might be null during rescan following uninstall of updates 9511 // to a bundled app, so accommodate that possibility. The settings in 9512 // that case will be established later from the parsed package. 9513 // 9514 // If the settings aren't null, sync them up with what we've just derived. 9515 // note that apkRoot isn't stored in the package settings. 9516 if (pkgSetting != null) { 9517 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9518 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9519 } 9520 } 9521 9522 /** 9523 * Deduces the ABI of a bundled app and sets the relevant fields on the 9524 * parsed pkg object. 9525 * 9526 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9527 * under which system libraries are installed. 9528 * @param apkName the name of the installed package. 9529 */ 9530 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9531 final File codeFile = new File(pkg.codePath); 9532 9533 final boolean has64BitLibs; 9534 final boolean has32BitLibs; 9535 if (isApkFile(codeFile)) { 9536 // Monolithic install 9537 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9538 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9539 } else { 9540 // Cluster install 9541 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9542 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9543 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9544 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9545 has64BitLibs = (new File(rootDir, isa)).exists(); 9546 } else { 9547 has64BitLibs = false; 9548 } 9549 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9550 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9551 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9552 has32BitLibs = (new File(rootDir, isa)).exists(); 9553 } else { 9554 has32BitLibs = false; 9555 } 9556 } 9557 9558 if (has64BitLibs && !has32BitLibs) { 9559 // The package has 64 bit libs, but not 32 bit libs. Its primary 9560 // ABI should be 64 bit. We can safely assume here that the bundled 9561 // native libraries correspond to the most preferred ABI in the list. 9562 9563 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9564 pkg.applicationInfo.secondaryCpuAbi = null; 9565 } else if (has32BitLibs && !has64BitLibs) { 9566 // The package has 32 bit libs but not 64 bit libs. Its primary 9567 // ABI should be 32 bit. 9568 9569 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9570 pkg.applicationInfo.secondaryCpuAbi = null; 9571 } else if (has32BitLibs && has64BitLibs) { 9572 // The application has both 64 and 32 bit bundled libraries. We check 9573 // here that the app declares multiArch support, and warn if it doesn't. 9574 // 9575 // We will be lenient here and record both ABIs. The primary will be the 9576 // ABI that's higher on the list, i.e, a device that's configured to prefer 9577 // 64 bit apps will see a 64 bit primary ABI, 9578 9579 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9580 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9581 } 9582 9583 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9584 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9585 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9586 } else { 9587 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9588 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9589 } 9590 } else { 9591 pkg.applicationInfo.primaryCpuAbi = null; 9592 pkg.applicationInfo.secondaryCpuAbi = null; 9593 } 9594 } 9595 9596 private void killApplication(String pkgName, int appId, String reason) { 9597 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9598 } 9599 9600 private void killApplication(String pkgName, int appId, int userId, String reason) { 9601 // Request the ActivityManager to kill the process(only for existing packages) 9602 // so that we do not end up in a confused state while the user is still using the older 9603 // version of the application while the new one gets installed. 9604 final long token = Binder.clearCallingIdentity(); 9605 try { 9606 IActivityManager am = ActivityManagerNative.getDefault(); 9607 if (am != null) { 9608 try { 9609 am.killApplication(pkgName, appId, userId, reason); 9610 } catch (RemoteException e) { 9611 } 9612 } 9613 } finally { 9614 Binder.restoreCallingIdentity(token); 9615 } 9616 } 9617 9618 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9619 // Remove the parent package setting 9620 PackageSetting ps = (PackageSetting) pkg.mExtras; 9621 if (ps != null) { 9622 removePackageLI(ps, chatty); 9623 } 9624 // Remove the child package setting 9625 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9626 for (int i = 0; i < childCount; i++) { 9627 PackageParser.Package childPkg = pkg.childPackages.get(i); 9628 ps = (PackageSetting) childPkg.mExtras; 9629 if (ps != null) { 9630 removePackageLI(ps, chatty); 9631 } 9632 } 9633 } 9634 9635 void removePackageLI(PackageSetting ps, boolean chatty) { 9636 if (DEBUG_INSTALL) { 9637 if (chatty) 9638 Log.d(TAG, "Removing package " + ps.name); 9639 } 9640 9641 // writer 9642 synchronized (mPackages) { 9643 mPackages.remove(ps.name); 9644 final PackageParser.Package pkg = ps.pkg; 9645 if (pkg != null) { 9646 cleanPackageDataStructuresLILPw(pkg, chatty); 9647 } 9648 } 9649 } 9650 9651 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9652 if (DEBUG_INSTALL) { 9653 if (chatty) 9654 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9655 } 9656 9657 // writer 9658 synchronized (mPackages) { 9659 // Remove the parent package 9660 mPackages.remove(pkg.applicationInfo.packageName); 9661 cleanPackageDataStructuresLILPw(pkg, chatty); 9662 9663 // Remove the child packages 9664 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9665 for (int i = 0; i < childCount; i++) { 9666 PackageParser.Package childPkg = pkg.childPackages.get(i); 9667 mPackages.remove(childPkg.applicationInfo.packageName); 9668 cleanPackageDataStructuresLILPw(childPkg, chatty); 9669 } 9670 } 9671 } 9672 9673 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9674 int N = pkg.providers.size(); 9675 StringBuilder r = null; 9676 int i; 9677 for (i=0; i<N; i++) { 9678 PackageParser.Provider p = pkg.providers.get(i); 9679 mProviders.removeProvider(p); 9680 if (p.info.authority == null) { 9681 9682 /* There was another ContentProvider with this authority when 9683 * this app was installed so this authority is null, 9684 * Ignore it as we don't have to unregister the provider. 9685 */ 9686 continue; 9687 } 9688 String names[] = p.info.authority.split(";"); 9689 for (int j = 0; j < names.length; j++) { 9690 if (mProvidersByAuthority.get(names[j]) == p) { 9691 mProvidersByAuthority.remove(names[j]); 9692 if (DEBUG_REMOVE) { 9693 if (chatty) 9694 Log.d(TAG, "Unregistered content provider: " + names[j] 9695 + ", className = " + p.info.name + ", isSyncable = " 9696 + p.info.isSyncable); 9697 } 9698 } 9699 } 9700 if (DEBUG_REMOVE && chatty) { 9701 if (r == null) { 9702 r = new StringBuilder(256); 9703 } else { 9704 r.append(' '); 9705 } 9706 r.append(p.info.name); 9707 } 9708 } 9709 if (r != null) { 9710 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9711 } 9712 9713 N = pkg.services.size(); 9714 r = null; 9715 for (i=0; i<N; i++) { 9716 PackageParser.Service s = pkg.services.get(i); 9717 mServices.removeService(s); 9718 if (chatty) { 9719 if (r == null) { 9720 r = new StringBuilder(256); 9721 } else { 9722 r.append(' '); 9723 } 9724 r.append(s.info.name); 9725 } 9726 } 9727 if (r != null) { 9728 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9729 } 9730 9731 N = pkg.receivers.size(); 9732 r = null; 9733 for (i=0; i<N; i++) { 9734 PackageParser.Activity a = pkg.receivers.get(i); 9735 mReceivers.removeActivity(a, "receiver"); 9736 if (DEBUG_REMOVE && chatty) { 9737 if (r == null) { 9738 r = new StringBuilder(256); 9739 } else { 9740 r.append(' '); 9741 } 9742 r.append(a.info.name); 9743 } 9744 } 9745 if (r != null) { 9746 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9747 } 9748 9749 N = pkg.activities.size(); 9750 r = null; 9751 for (i=0; i<N; i++) { 9752 PackageParser.Activity a = pkg.activities.get(i); 9753 mActivities.removeActivity(a, "activity"); 9754 if (DEBUG_REMOVE && chatty) { 9755 if (r == null) { 9756 r = new StringBuilder(256); 9757 } else { 9758 r.append(' '); 9759 } 9760 r.append(a.info.name); 9761 } 9762 } 9763 if (r != null) { 9764 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9765 } 9766 9767 N = pkg.permissions.size(); 9768 r = null; 9769 for (i=0; i<N; i++) { 9770 PackageParser.Permission p = pkg.permissions.get(i); 9771 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9772 if (bp == null) { 9773 bp = mSettings.mPermissionTrees.get(p.info.name); 9774 } 9775 if (bp != null && bp.perm == p) { 9776 bp.perm = null; 9777 if (DEBUG_REMOVE && chatty) { 9778 if (r == null) { 9779 r = new StringBuilder(256); 9780 } else { 9781 r.append(' '); 9782 } 9783 r.append(p.info.name); 9784 } 9785 } 9786 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9787 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9788 if (appOpPkgs != null) { 9789 appOpPkgs.remove(pkg.packageName); 9790 } 9791 } 9792 } 9793 if (r != null) { 9794 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9795 } 9796 9797 N = pkg.requestedPermissions.size(); 9798 r = null; 9799 for (i=0; i<N; i++) { 9800 String perm = pkg.requestedPermissions.get(i); 9801 BasePermission bp = mSettings.mPermissions.get(perm); 9802 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9803 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9804 if (appOpPkgs != null) { 9805 appOpPkgs.remove(pkg.packageName); 9806 if (appOpPkgs.isEmpty()) { 9807 mAppOpPermissionPackages.remove(perm); 9808 } 9809 } 9810 } 9811 } 9812 if (r != null) { 9813 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9814 } 9815 9816 N = pkg.instrumentation.size(); 9817 r = null; 9818 for (i=0; i<N; i++) { 9819 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9820 mInstrumentation.remove(a.getComponentName()); 9821 if (DEBUG_REMOVE && chatty) { 9822 if (r == null) { 9823 r = new StringBuilder(256); 9824 } else { 9825 r.append(' '); 9826 } 9827 r.append(a.info.name); 9828 } 9829 } 9830 if (r != null) { 9831 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9832 } 9833 9834 r = null; 9835 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9836 // Only system apps can hold shared libraries. 9837 if (pkg.libraryNames != null) { 9838 for (i=0; i<pkg.libraryNames.size(); i++) { 9839 String name = pkg.libraryNames.get(i); 9840 SharedLibraryEntry cur = mSharedLibraries.get(name); 9841 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9842 mSharedLibraries.remove(name); 9843 if (DEBUG_REMOVE && chatty) { 9844 if (r == null) { 9845 r = new StringBuilder(256); 9846 } else { 9847 r.append(' '); 9848 } 9849 r.append(name); 9850 } 9851 } 9852 } 9853 } 9854 } 9855 if (r != null) { 9856 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9857 } 9858 } 9859 9860 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9861 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9862 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9863 return true; 9864 } 9865 } 9866 return false; 9867 } 9868 9869 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9870 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9871 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9872 9873 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9874 // Update the parent permissions 9875 updatePermissionsLPw(pkg.packageName, pkg, flags); 9876 // Update the child permissions 9877 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9878 for (int i = 0; i < childCount; i++) { 9879 PackageParser.Package childPkg = pkg.childPackages.get(i); 9880 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9881 } 9882 } 9883 9884 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9885 int flags) { 9886 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9887 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9888 } 9889 9890 private void updatePermissionsLPw(String changingPkg, 9891 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9892 // Make sure there are no dangling permission trees. 9893 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9894 while (it.hasNext()) { 9895 final BasePermission bp = it.next(); 9896 if (bp.packageSetting == null) { 9897 // We may not yet have parsed the package, so just see if 9898 // we still know about its settings. 9899 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9900 } 9901 if (bp.packageSetting == null) { 9902 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9903 + " from package " + bp.sourcePackage); 9904 it.remove(); 9905 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9906 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9907 Slog.i(TAG, "Removing old permission tree: " + bp.name 9908 + " from package " + bp.sourcePackage); 9909 flags |= UPDATE_PERMISSIONS_ALL; 9910 it.remove(); 9911 } 9912 } 9913 } 9914 9915 // Make sure all dynamic permissions have been assigned to a package, 9916 // and make sure there are no dangling permissions. 9917 it = mSettings.mPermissions.values().iterator(); 9918 while (it.hasNext()) { 9919 final BasePermission bp = it.next(); 9920 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9921 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9922 + bp.name + " pkg=" + bp.sourcePackage 9923 + " info=" + bp.pendingInfo); 9924 if (bp.packageSetting == null && bp.pendingInfo != null) { 9925 final BasePermission tree = findPermissionTreeLP(bp.name); 9926 if (tree != null && tree.perm != null) { 9927 bp.packageSetting = tree.packageSetting; 9928 bp.perm = new PackageParser.Permission(tree.perm.owner, 9929 new PermissionInfo(bp.pendingInfo)); 9930 bp.perm.info.packageName = tree.perm.info.packageName; 9931 bp.perm.info.name = bp.name; 9932 bp.uid = tree.uid; 9933 } 9934 } 9935 } 9936 if (bp.packageSetting == null) { 9937 // We may not yet have parsed the package, so just see if 9938 // we still know about its settings. 9939 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9940 } 9941 if (bp.packageSetting == null) { 9942 Slog.w(TAG, "Removing dangling permission: " + bp.name 9943 + " from package " + bp.sourcePackage); 9944 it.remove(); 9945 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9946 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9947 Slog.i(TAG, "Removing old permission: " + bp.name 9948 + " from package " + bp.sourcePackage); 9949 flags |= UPDATE_PERMISSIONS_ALL; 9950 it.remove(); 9951 } 9952 } 9953 } 9954 9955 // Now update the permissions for all packages, in particular 9956 // replace the granted permissions of the system packages. 9957 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9958 for (PackageParser.Package pkg : mPackages.values()) { 9959 if (pkg != pkgInfo) { 9960 // Only replace for packages on requested volume 9961 final String volumeUuid = getVolumeUuidForPackage(pkg); 9962 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9963 && Objects.equals(replaceVolumeUuid, volumeUuid); 9964 grantPermissionsLPw(pkg, replace, changingPkg); 9965 } 9966 } 9967 } 9968 9969 if (pkgInfo != null) { 9970 // Only replace for packages on requested volume 9971 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9972 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9973 && Objects.equals(replaceVolumeUuid, volumeUuid); 9974 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9975 } 9976 } 9977 9978 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9979 String packageOfInterest) { 9980 // IMPORTANT: There are two types of permissions: install and runtime. 9981 // Install time permissions are granted when the app is installed to 9982 // all device users and users added in the future. Runtime permissions 9983 // are granted at runtime explicitly to specific users. Normal and signature 9984 // protected permissions are install time permissions. Dangerous permissions 9985 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9986 // otherwise they are runtime permissions. This function does not manage 9987 // runtime permissions except for the case an app targeting Lollipop MR1 9988 // being upgraded to target a newer SDK, in which case dangerous permissions 9989 // are transformed from install time to runtime ones. 9990 9991 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9992 if (ps == null) { 9993 return; 9994 } 9995 9996 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9997 9998 PermissionsState permissionsState = ps.getPermissionsState(); 9999 PermissionsState origPermissions = permissionsState; 10000 10001 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10002 10003 boolean runtimePermissionsRevoked = false; 10004 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10005 10006 boolean changedInstallPermission = false; 10007 10008 if (replace) { 10009 ps.installPermissionsFixed = false; 10010 if (!ps.isSharedUser()) { 10011 origPermissions = new PermissionsState(permissionsState); 10012 permissionsState.reset(); 10013 } else { 10014 // We need to know only about runtime permission changes since the 10015 // calling code always writes the install permissions state but 10016 // the runtime ones are written only if changed. The only cases of 10017 // changed runtime permissions here are promotion of an install to 10018 // runtime and revocation of a runtime from a shared user. 10019 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10020 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10021 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10022 runtimePermissionsRevoked = true; 10023 } 10024 } 10025 } 10026 10027 permissionsState.setGlobalGids(mGlobalGids); 10028 10029 final int N = pkg.requestedPermissions.size(); 10030 for (int i=0; i<N; i++) { 10031 final String name = pkg.requestedPermissions.get(i); 10032 final BasePermission bp = mSettings.mPermissions.get(name); 10033 10034 if (DEBUG_INSTALL) { 10035 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10036 } 10037 10038 if (bp == null || bp.packageSetting == null) { 10039 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10040 Slog.w(TAG, "Unknown permission " + name 10041 + " in package " + pkg.packageName); 10042 } 10043 continue; 10044 } 10045 10046 final String perm = bp.name; 10047 boolean allowedSig = false; 10048 int grant = GRANT_DENIED; 10049 10050 // Keep track of app op permissions. 10051 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10052 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10053 if (pkgs == null) { 10054 pkgs = new ArraySet<>(); 10055 mAppOpPermissionPackages.put(bp.name, pkgs); 10056 } 10057 pkgs.add(pkg.packageName); 10058 } 10059 10060 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10061 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10062 >= Build.VERSION_CODES.M; 10063 switch (level) { 10064 case PermissionInfo.PROTECTION_NORMAL: { 10065 // For all apps normal permissions are install time ones. 10066 grant = GRANT_INSTALL; 10067 } break; 10068 10069 case PermissionInfo.PROTECTION_DANGEROUS: { 10070 // If a permission review is required for legacy apps we represent 10071 // their permissions as always granted runtime ones since we need 10072 // to keep the review required permission flag per user while an 10073 // install permission's state is shared across all users. 10074 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10075 // For legacy apps dangerous permissions are install time ones. 10076 grant = GRANT_INSTALL; 10077 } else if (origPermissions.hasInstallPermission(bp.name)) { 10078 // For legacy apps that became modern, install becomes runtime. 10079 grant = GRANT_UPGRADE; 10080 } else if (mPromoteSystemApps 10081 && isSystemApp(ps) 10082 && mExistingSystemPackages.contains(ps.name)) { 10083 // For legacy system apps, install becomes runtime. 10084 // We cannot check hasInstallPermission() for system apps since those 10085 // permissions were granted implicitly and not persisted pre-M. 10086 grant = GRANT_UPGRADE; 10087 } else { 10088 // For modern apps keep runtime permissions unchanged. 10089 grant = GRANT_RUNTIME; 10090 } 10091 } break; 10092 10093 case PermissionInfo.PROTECTION_SIGNATURE: { 10094 // For all apps signature permissions are install time ones. 10095 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10096 if (allowedSig) { 10097 grant = GRANT_INSTALL; 10098 } 10099 } break; 10100 } 10101 10102 if (DEBUG_INSTALL) { 10103 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10104 } 10105 10106 if (grant != GRANT_DENIED) { 10107 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10108 // If this is an existing, non-system package, then 10109 // we can't add any new permissions to it. 10110 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10111 // Except... if this is a permission that was added 10112 // to the platform (note: need to only do this when 10113 // updating the platform). 10114 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10115 grant = GRANT_DENIED; 10116 } 10117 } 10118 } 10119 10120 switch (grant) { 10121 case GRANT_INSTALL: { 10122 // Revoke this as runtime permission to handle the case of 10123 // a runtime permission being downgraded to an install one. 10124 // Also in permission review mode we keep dangerous permissions 10125 // for legacy apps 10126 for (int userId : UserManagerService.getInstance().getUserIds()) { 10127 if (origPermissions.getRuntimePermissionState( 10128 bp.name, userId) != null) { 10129 // Revoke the runtime permission and clear the flags. 10130 origPermissions.revokeRuntimePermission(bp, userId); 10131 origPermissions.updatePermissionFlags(bp, userId, 10132 PackageManager.MASK_PERMISSION_FLAGS, 0); 10133 // If we revoked a permission permission, we have to write. 10134 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10135 changedRuntimePermissionUserIds, userId); 10136 } 10137 } 10138 // Grant an install permission. 10139 if (permissionsState.grantInstallPermission(bp) != 10140 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10141 changedInstallPermission = true; 10142 } 10143 } break; 10144 10145 case GRANT_RUNTIME: { 10146 // Grant previously granted runtime permissions. 10147 for (int userId : UserManagerService.getInstance().getUserIds()) { 10148 PermissionState permissionState = origPermissions 10149 .getRuntimePermissionState(bp.name, userId); 10150 int flags = permissionState != null 10151 ? permissionState.getFlags() : 0; 10152 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10153 if (permissionsState.grantRuntimePermission(bp, userId) == 10154 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10155 // If we cannot put the permission as it was, we have to write. 10156 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10157 changedRuntimePermissionUserIds, userId); 10158 } 10159 // If the app supports runtime permissions no need for a review. 10160 if (Build.PERMISSIONS_REVIEW_REQUIRED 10161 && appSupportsRuntimePermissions 10162 && (flags & PackageManager 10163 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10164 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10165 // Since we changed the flags, we have to write. 10166 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10167 changedRuntimePermissionUserIds, userId); 10168 } 10169 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10170 && !appSupportsRuntimePermissions) { 10171 // For legacy apps that need a permission review, every new 10172 // runtime permission is granted but it is pending a review. 10173 // We also need to review only platform defined runtime 10174 // permissions as these are the only ones the platform knows 10175 // how to disable the API to simulate revocation as legacy 10176 // apps don't expect to run with revoked permissions. 10177 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10178 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10179 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10180 // We changed the flags, hence have to write. 10181 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10182 changedRuntimePermissionUserIds, userId); 10183 } 10184 } 10185 if (permissionsState.grantRuntimePermission(bp, userId) 10186 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10187 // We changed the permission, hence have to write. 10188 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10189 changedRuntimePermissionUserIds, userId); 10190 } 10191 } 10192 // Propagate the permission flags. 10193 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10194 } 10195 } break; 10196 10197 case GRANT_UPGRADE: { 10198 // Grant runtime permissions for a previously held install permission. 10199 PermissionState permissionState = origPermissions 10200 .getInstallPermissionState(bp.name); 10201 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10202 10203 if (origPermissions.revokeInstallPermission(bp) 10204 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10205 // We will be transferring the permission flags, so clear them. 10206 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10207 PackageManager.MASK_PERMISSION_FLAGS, 0); 10208 changedInstallPermission = true; 10209 } 10210 10211 // If the permission is not to be promoted to runtime we ignore it and 10212 // also its other flags as they are not applicable to install permissions. 10213 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10214 for (int userId : currentUserIds) { 10215 if (permissionsState.grantRuntimePermission(bp, userId) != 10216 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10217 // Transfer the permission flags. 10218 permissionsState.updatePermissionFlags(bp, userId, 10219 flags, flags); 10220 // If we granted the permission, we have to write. 10221 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10222 changedRuntimePermissionUserIds, userId); 10223 } 10224 } 10225 } 10226 } break; 10227 10228 default: { 10229 if (packageOfInterest == null 10230 || packageOfInterest.equals(pkg.packageName)) { 10231 Slog.w(TAG, "Not granting permission " + perm 10232 + " to package " + pkg.packageName 10233 + " because it was previously installed without"); 10234 } 10235 } break; 10236 } 10237 } else { 10238 if (permissionsState.revokeInstallPermission(bp) != 10239 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10240 // Also drop the permission flags. 10241 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10242 PackageManager.MASK_PERMISSION_FLAGS, 0); 10243 changedInstallPermission = true; 10244 Slog.i(TAG, "Un-granting permission " + perm 10245 + " from package " + pkg.packageName 10246 + " (protectionLevel=" + bp.protectionLevel 10247 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10248 + ")"); 10249 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10250 // Don't print warning for app op permissions, since it is fine for them 10251 // not to be granted, there is a UI for the user to decide. 10252 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10253 Slog.w(TAG, "Not granting permission " + perm 10254 + " to package " + pkg.packageName 10255 + " (protectionLevel=" + bp.protectionLevel 10256 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10257 + ")"); 10258 } 10259 } 10260 } 10261 } 10262 10263 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10264 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10265 // This is the first that we have heard about this package, so the 10266 // permissions we have now selected are fixed until explicitly 10267 // changed. 10268 ps.installPermissionsFixed = true; 10269 } 10270 10271 // Persist the runtime permissions state for users with changes. If permissions 10272 // were revoked because no app in the shared user declares them we have to 10273 // write synchronously to avoid losing runtime permissions state. 10274 for (int userId : changedRuntimePermissionUserIds) { 10275 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10276 } 10277 10278 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10279 } 10280 10281 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10282 boolean allowed = false; 10283 final int NP = PackageParser.NEW_PERMISSIONS.length; 10284 for (int ip=0; ip<NP; ip++) { 10285 final PackageParser.NewPermissionInfo npi 10286 = PackageParser.NEW_PERMISSIONS[ip]; 10287 if (npi.name.equals(perm) 10288 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10289 allowed = true; 10290 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10291 + pkg.packageName); 10292 break; 10293 } 10294 } 10295 return allowed; 10296 } 10297 10298 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10299 BasePermission bp, PermissionsState origPermissions) { 10300 boolean allowed; 10301 allowed = (compareSignatures( 10302 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10303 == PackageManager.SIGNATURE_MATCH) 10304 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10305 == PackageManager.SIGNATURE_MATCH); 10306 if (!allowed && (bp.protectionLevel 10307 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10308 if (isSystemApp(pkg)) { 10309 // For updated system applications, a system permission 10310 // is granted only if it had been defined by the original application. 10311 if (pkg.isUpdatedSystemApp()) { 10312 final PackageSetting sysPs = mSettings 10313 .getDisabledSystemPkgLPr(pkg.packageName); 10314 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10315 // If the original was granted this permission, we take 10316 // that grant decision as read and propagate it to the 10317 // update. 10318 if (sysPs.isPrivileged()) { 10319 allowed = true; 10320 } 10321 } else { 10322 // The system apk may have been updated with an older 10323 // version of the one on the data partition, but which 10324 // granted a new system permission that it didn't have 10325 // before. In this case we do want to allow the app to 10326 // now get the new permission if the ancestral apk is 10327 // privileged to get it. 10328 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10329 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10330 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10331 allowed = true; 10332 break; 10333 } 10334 } 10335 } 10336 // Also if a privileged parent package on the system image or any of 10337 // its children requested a privileged permission, the updated child 10338 // packages can also get the permission. 10339 if (pkg.parentPackage != null) { 10340 final PackageSetting disabledSysParentPs = mSettings 10341 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10342 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10343 && disabledSysParentPs.isPrivileged()) { 10344 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10345 allowed = true; 10346 } else if (disabledSysParentPs.pkg.childPackages != null) { 10347 final int count = disabledSysParentPs.pkg.childPackages.size(); 10348 for (int i = 0; i < count; i++) { 10349 PackageParser.Package disabledSysChildPkg = 10350 disabledSysParentPs.pkg.childPackages.get(i); 10351 if (isPackageRequestingPermission(disabledSysChildPkg, 10352 perm)) { 10353 allowed = true; 10354 break; 10355 } 10356 } 10357 } 10358 } 10359 } 10360 } 10361 } else { 10362 allowed = isPrivilegedApp(pkg); 10363 } 10364 } 10365 } 10366 if (!allowed) { 10367 if (!allowed && (bp.protectionLevel 10368 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10369 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10370 // If this was a previously normal/dangerous permission that got moved 10371 // to a system permission as part of the runtime permission redesign, then 10372 // we still want to blindly grant it to old apps. 10373 allowed = true; 10374 } 10375 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10376 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10377 // If this permission is to be granted to the system installer and 10378 // this app is an installer, then it gets the permission. 10379 allowed = true; 10380 } 10381 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10382 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10383 // If this permission is to be granted to the system verifier and 10384 // this app is a verifier, then it gets the permission. 10385 allowed = true; 10386 } 10387 if (!allowed && (bp.protectionLevel 10388 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10389 && isSystemApp(pkg)) { 10390 // Any pre-installed system app is allowed to get this permission. 10391 allowed = true; 10392 } 10393 if (!allowed && (bp.protectionLevel 10394 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10395 // For development permissions, a development permission 10396 // is granted only if it was already granted. 10397 allowed = origPermissions.hasInstallPermission(perm); 10398 } 10399 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10400 && pkg.packageName.equals(mSetupWizardPackage)) { 10401 // If this permission is to be granted to the system setup wizard and 10402 // this app is a setup wizard, then it gets the permission. 10403 allowed = true; 10404 } 10405 } 10406 return allowed; 10407 } 10408 10409 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10410 final int permCount = pkg.requestedPermissions.size(); 10411 for (int j = 0; j < permCount; j++) { 10412 String requestedPermission = pkg.requestedPermissions.get(j); 10413 if (permission.equals(requestedPermission)) { 10414 return true; 10415 } 10416 } 10417 return false; 10418 } 10419 10420 final class ActivityIntentResolver 10421 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10422 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10423 boolean defaultOnly, int userId) { 10424 if (!sUserManager.exists(userId)) return null; 10425 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10426 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10427 } 10428 10429 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10430 int userId) { 10431 if (!sUserManager.exists(userId)) return null; 10432 mFlags = flags; 10433 return super.queryIntent(intent, resolvedType, 10434 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10435 } 10436 10437 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10438 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10439 if (!sUserManager.exists(userId)) return null; 10440 if (packageActivities == null) { 10441 return null; 10442 } 10443 mFlags = flags; 10444 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10445 final int N = packageActivities.size(); 10446 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10447 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10448 10449 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10450 for (int i = 0; i < N; ++i) { 10451 intentFilters = packageActivities.get(i).intents; 10452 if (intentFilters != null && intentFilters.size() > 0) { 10453 PackageParser.ActivityIntentInfo[] array = 10454 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10455 intentFilters.toArray(array); 10456 listCut.add(array); 10457 } 10458 } 10459 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10460 } 10461 10462 /** 10463 * Finds a privileged activity that matches the specified activity names. 10464 */ 10465 private PackageParser.Activity findMatchingActivity( 10466 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10467 for (PackageParser.Activity sysActivity : activityList) { 10468 if (sysActivity.info.name.equals(activityInfo.name)) { 10469 return sysActivity; 10470 } 10471 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10472 return sysActivity; 10473 } 10474 if (sysActivity.info.targetActivity != null) { 10475 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10476 return sysActivity; 10477 } 10478 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10479 return sysActivity; 10480 } 10481 } 10482 } 10483 return null; 10484 } 10485 10486 public class IterGenerator<E> { 10487 public Iterator<E> generate(ActivityIntentInfo info) { 10488 return null; 10489 } 10490 } 10491 10492 public class ActionIterGenerator extends IterGenerator<String> { 10493 @Override 10494 public Iterator<String> generate(ActivityIntentInfo info) { 10495 return info.actionsIterator(); 10496 } 10497 } 10498 10499 public class CategoriesIterGenerator extends IterGenerator<String> { 10500 @Override 10501 public Iterator<String> generate(ActivityIntentInfo info) { 10502 return info.categoriesIterator(); 10503 } 10504 } 10505 10506 public class SchemesIterGenerator extends IterGenerator<String> { 10507 @Override 10508 public Iterator<String> generate(ActivityIntentInfo info) { 10509 return info.schemesIterator(); 10510 } 10511 } 10512 10513 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10514 @Override 10515 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10516 return info.authoritiesIterator(); 10517 } 10518 } 10519 10520 /** 10521 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10522 * MODIFIED. Do not pass in a list that should not be changed. 10523 */ 10524 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10525 IterGenerator<T> generator, Iterator<T> searchIterator) { 10526 // loop through the set of actions; every one must be found in the intent filter 10527 while (searchIterator.hasNext()) { 10528 // we must have at least one filter in the list to consider a match 10529 if (intentList.size() == 0) { 10530 break; 10531 } 10532 10533 final T searchAction = searchIterator.next(); 10534 10535 // loop through the set of intent filters 10536 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10537 while (intentIter.hasNext()) { 10538 final ActivityIntentInfo intentInfo = intentIter.next(); 10539 boolean selectionFound = false; 10540 10541 // loop through the intent filter's selection criteria; at least one 10542 // of them must match the searched criteria 10543 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10544 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10545 final T intentSelection = intentSelectionIter.next(); 10546 if (intentSelection != null && intentSelection.equals(searchAction)) { 10547 selectionFound = true; 10548 break; 10549 } 10550 } 10551 10552 // the selection criteria wasn't found in this filter's set; this filter 10553 // is not a potential match 10554 if (!selectionFound) { 10555 intentIter.remove(); 10556 } 10557 } 10558 } 10559 } 10560 10561 private boolean isProtectedAction(ActivityIntentInfo filter) { 10562 final Iterator<String> actionsIter = filter.actionsIterator(); 10563 while (actionsIter != null && actionsIter.hasNext()) { 10564 final String filterAction = actionsIter.next(); 10565 if (PROTECTED_ACTIONS.contains(filterAction)) { 10566 return true; 10567 } 10568 } 10569 return false; 10570 } 10571 10572 /** 10573 * Adjusts the priority of the given intent filter according to policy. 10574 * <p> 10575 * <ul> 10576 * <li>The priority for non privileged applications is capped to '0'</li> 10577 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10578 * <li>The priority for unbundled updates to privileged applications is capped to the 10579 * priority defined on the system partition</li> 10580 * </ul> 10581 * <p> 10582 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10583 * allowed to obtain any priority on any action. 10584 */ 10585 private void adjustPriority( 10586 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10587 // nothing to do; priority is fine as-is 10588 if (intent.getPriority() <= 0) { 10589 return; 10590 } 10591 10592 final ActivityInfo activityInfo = intent.activity.info; 10593 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10594 10595 final boolean privilegedApp = 10596 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10597 if (!privilegedApp) { 10598 // non-privileged applications can never define a priority >0 10599 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10600 + " package: " + applicationInfo.packageName 10601 + " activity: " + intent.activity.className 10602 + " origPrio: " + intent.getPriority()); 10603 intent.setPriority(0); 10604 return; 10605 } 10606 10607 if (systemActivities == null) { 10608 // the system package is not disabled; we're parsing the system partition 10609 if (isProtectedAction(intent)) { 10610 if (mDeferProtectedFilters) { 10611 // We can't deal with these just yet. No component should ever obtain a 10612 // >0 priority for a protected actions, with ONE exception -- the setup 10613 // wizard. The setup wizard, however, cannot be known until we're able to 10614 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10615 // until all intent filters have been processed. Chicken, meet egg. 10616 // Let the filter temporarily have a high priority and rectify the 10617 // priorities after all system packages have been scanned. 10618 mProtectedFilters.add(intent); 10619 if (DEBUG_FILTERS) { 10620 Slog.i(TAG, "Protected action; save for later;" 10621 + " package: " + applicationInfo.packageName 10622 + " activity: " + intent.activity.className 10623 + " origPrio: " + intent.getPriority()); 10624 } 10625 return; 10626 } else { 10627 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10628 Slog.i(TAG, "No setup wizard;" 10629 + " All protected intents capped to priority 0"); 10630 } 10631 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10632 if (DEBUG_FILTERS) { 10633 Slog.i(TAG, "Found setup wizard;" 10634 + " allow priority " + intent.getPriority() + ";" 10635 + " package: " + intent.activity.info.packageName 10636 + " activity: " + intent.activity.className 10637 + " priority: " + intent.getPriority()); 10638 } 10639 // setup wizard gets whatever it wants 10640 return; 10641 } 10642 Slog.w(TAG, "Protected action; cap priority to 0;" 10643 + " package: " + intent.activity.info.packageName 10644 + " activity: " + intent.activity.className 10645 + " origPrio: " + intent.getPriority()); 10646 intent.setPriority(0); 10647 return; 10648 } 10649 } 10650 // privileged apps on the system image get whatever priority they request 10651 return; 10652 } 10653 10654 // privileged app unbundled update ... try to find the same activity 10655 final PackageParser.Activity foundActivity = 10656 findMatchingActivity(systemActivities, activityInfo); 10657 if (foundActivity == null) { 10658 // this is a new activity; it cannot obtain >0 priority 10659 if (DEBUG_FILTERS) { 10660 Slog.i(TAG, "New activity; cap priority to 0;" 10661 + " package: " + applicationInfo.packageName 10662 + " activity: " + intent.activity.className 10663 + " origPrio: " + intent.getPriority()); 10664 } 10665 intent.setPriority(0); 10666 return; 10667 } 10668 10669 // found activity, now check for filter equivalence 10670 10671 // a shallow copy is enough; we modify the list, not its contents 10672 final List<ActivityIntentInfo> intentListCopy = 10673 new ArrayList<>(foundActivity.intents); 10674 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10675 10676 // find matching action subsets 10677 final Iterator<String> actionsIterator = intent.actionsIterator(); 10678 if (actionsIterator != null) { 10679 getIntentListSubset( 10680 intentListCopy, new ActionIterGenerator(), actionsIterator); 10681 if (intentListCopy.size() == 0) { 10682 // no more intents to match; we're not equivalent 10683 if (DEBUG_FILTERS) { 10684 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10685 + " package: " + applicationInfo.packageName 10686 + " activity: " + intent.activity.className 10687 + " origPrio: " + intent.getPriority()); 10688 } 10689 intent.setPriority(0); 10690 return; 10691 } 10692 } 10693 10694 // find matching category subsets 10695 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10696 if (categoriesIterator != null) { 10697 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10698 categoriesIterator); 10699 if (intentListCopy.size() == 0) { 10700 // no more intents to match; we're not equivalent 10701 if (DEBUG_FILTERS) { 10702 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10703 + " package: " + applicationInfo.packageName 10704 + " activity: " + intent.activity.className 10705 + " origPrio: " + intent.getPriority()); 10706 } 10707 intent.setPriority(0); 10708 return; 10709 } 10710 } 10711 10712 // find matching schemes subsets 10713 final Iterator<String> schemesIterator = intent.schemesIterator(); 10714 if (schemesIterator != null) { 10715 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10716 schemesIterator); 10717 if (intentListCopy.size() == 0) { 10718 // no more intents to match; we're not equivalent 10719 if (DEBUG_FILTERS) { 10720 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10721 + " package: " + applicationInfo.packageName 10722 + " activity: " + intent.activity.className 10723 + " origPrio: " + intent.getPriority()); 10724 } 10725 intent.setPriority(0); 10726 return; 10727 } 10728 } 10729 10730 // find matching authorities subsets 10731 final Iterator<IntentFilter.AuthorityEntry> 10732 authoritiesIterator = intent.authoritiesIterator(); 10733 if (authoritiesIterator != null) { 10734 getIntentListSubset(intentListCopy, 10735 new AuthoritiesIterGenerator(), 10736 authoritiesIterator); 10737 if (intentListCopy.size() == 0) { 10738 // no more intents to match; we're not equivalent 10739 if (DEBUG_FILTERS) { 10740 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10741 + " package: " + applicationInfo.packageName 10742 + " activity: " + intent.activity.className 10743 + " origPrio: " + intent.getPriority()); 10744 } 10745 intent.setPriority(0); 10746 return; 10747 } 10748 } 10749 10750 // we found matching filter(s); app gets the max priority of all intents 10751 int cappedPriority = 0; 10752 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10753 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10754 } 10755 if (intent.getPriority() > cappedPriority) { 10756 if (DEBUG_FILTERS) { 10757 Slog.i(TAG, "Found matching filter(s);" 10758 + " cap priority to " + cappedPriority + ";" 10759 + " package: " + applicationInfo.packageName 10760 + " activity: " + intent.activity.className 10761 + " origPrio: " + intent.getPriority()); 10762 } 10763 intent.setPriority(cappedPriority); 10764 return; 10765 } 10766 // all this for nothing; the requested priority was <= what was on the system 10767 } 10768 10769 public final void addActivity(PackageParser.Activity a, String type) { 10770 mActivities.put(a.getComponentName(), a); 10771 if (DEBUG_SHOW_INFO) 10772 Log.v( 10773 TAG, " " + type + " " + 10774 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10775 if (DEBUG_SHOW_INFO) 10776 Log.v(TAG, " Class=" + a.info.name); 10777 final int NI = a.intents.size(); 10778 for (int j=0; j<NI; j++) { 10779 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10780 if ("activity".equals(type)) { 10781 final PackageSetting ps = 10782 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10783 final List<PackageParser.Activity> systemActivities = 10784 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10785 adjustPriority(systemActivities, intent); 10786 } 10787 if (DEBUG_SHOW_INFO) { 10788 Log.v(TAG, " IntentFilter:"); 10789 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10790 } 10791 if (!intent.debugCheck()) { 10792 Log.w(TAG, "==> For Activity " + a.info.name); 10793 } 10794 addFilter(intent); 10795 } 10796 } 10797 10798 public final void removeActivity(PackageParser.Activity a, String type) { 10799 mActivities.remove(a.getComponentName()); 10800 if (DEBUG_SHOW_INFO) { 10801 Log.v(TAG, " " + type + " " 10802 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10803 : a.info.name) + ":"); 10804 Log.v(TAG, " Class=" + a.info.name); 10805 } 10806 final int NI = a.intents.size(); 10807 for (int j=0; j<NI; j++) { 10808 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10809 if (DEBUG_SHOW_INFO) { 10810 Log.v(TAG, " IntentFilter:"); 10811 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10812 } 10813 removeFilter(intent); 10814 } 10815 } 10816 10817 @Override 10818 protected boolean allowFilterResult( 10819 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10820 ActivityInfo filterAi = filter.activity.info; 10821 for (int i=dest.size()-1; i>=0; i--) { 10822 ActivityInfo destAi = dest.get(i).activityInfo; 10823 if (destAi.name == filterAi.name 10824 && destAi.packageName == filterAi.packageName) { 10825 return false; 10826 } 10827 } 10828 return true; 10829 } 10830 10831 @Override 10832 protected ActivityIntentInfo[] newArray(int size) { 10833 return new ActivityIntentInfo[size]; 10834 } 10835 10836 @Override 10837 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10838 if (!sUserManager.exists(userId)) return true; 10839 PackageParser.Package p = filter.activity.owner; 10840 if (p != null) { 10841 PackageSetting ps = (PackageSetting)p.mExtras; 10842 if (ps != null) { 10843 // System apps are never considered stopped for purposes of 10844 // filtering, because there may be no way for the user to 10845 // actually re-launch them. 10846 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10847 && ps.getStopped(userId); 10848 } 10849 } 10850 return false; 10851 } 10852 10853 @Override 10854 protected boolean isPackageForFilter(String packageName, 10855 PackageParser.ActivityIntentInfo info) { 10856 return packageName.equals(info.activity.owner.packageName); 10857 } 10858 10859 @Override 10860 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10861 int match, int userId) { 10862 if (!sUserManager.exists(userId)) return null; 10863 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10864 return null; 10865 } 10866 final PackageParser.Activity activity = info.activity; 10867 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10868 if (ps == null) { 10869 return null; 10870 } 10871 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10872 ps.readUserState(userId), userId); 10873 if (ai == null) { 10874 return null; 10875 } 10876 final ResolveInfo res = new ResolveInfo(); 10877 res.activityInfo = ai; 10878 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10879 res.filter = info; 10880 } 10881 if (info != null) { 10882 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10883 } 10884 res.priority = info.getPriority(); 10885 res.preferredOrder = activity.owner.mPreferredOrder; 10886 //System.out.println("Result: " + res.activityInfo.className + 10887 // " = " + res.priority); 10888 res.match = match; 10889 res.isDefault = info.hasDefault; 10890 res.labelRes = info.labelRes; 10891 res.nonLocalizedLabel = info.nonLocalizedLabel; 10892 if (userNeedsBadging(userId)) { 10893 res.noResourceId = true; 10894 } else { 10895 res.icon = info.icon; 10896 } 10897 res.iconResourceId = info.icon; 10898 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10899 return res; 10900 } 10901 10902 @Override 10903 protected void sortResults(List<ResolveInfo> results) { 10904 Collections.sort(results, mResolvePrioritySorter); 10905 } 10906 10907 @Override 10908 protected void dumpFilter(PrintWriter out, String prefix, 10909 PackageParser.ActivityIntentInfo filter) { 10910 out.print(prefix); out.print( 10911 Integer.toHexString(System.identityHashCode(filter.activity))); 10912 out.print(' '); 10913 filter.activity.printComponentShortName(out); 10914 out.print(" filter "); 10915 out.println(Integer.toHexString(System.identityHashCode(filter))); 10916 } 10917 10918 @Override 10919 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10920 return filter.activity; 10921 } 10922 10923 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10924 PackageParser.Activity activity = (PackageParser.Activity)label; 10925 out.print(prefix); out.print( 10926 Integer.toHexString(System.identityHashCode(activity))); 10927 out.print(' '); 10928 activity.printComponentShortName(out); 10929 if (count > 1) { 10930 out.print(" ("); out.print(count); out.print(" filters)"); 10931 } 10932 out.println(); 10933 } 10934 10935 // Keys are String (activity class name), values are Activity. 10936 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10937 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10938 private int mFlags; 10939 } 10940 10941 private final class ServiceIntentResolver 10942 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10943 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10944 boolean defaultOnly, int userId) { 10945 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10946 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10947 } 10948 10949 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10950 int userId) { 10951 if (!sUserManager.exists(userId)) return null; 10952 mFlags = flags; 10953 return super.queryIntent(intent, resolvedType, 10954 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10955 } 10956 10957 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10958 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10959 if (!sUserManager.exists(userId)) return null; 10960 if (packageServices == null) { 10961 return null; 10962 } 10963 mFlags = flags; 10964 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10965 final int N = packageServices.size(); 10966 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10967 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10968 10969 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10970 for (int i = 0; i < N; ++i) { 10971 intentFilters = packageServices.get(i).intents; 10972 if (intentFilters != null && intentFilters.size() > 0) { 10973 PackageParser.ServiceIntentInfo[] array = 10974 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10975 intentFilters.toArray(array); 10976 listCut.add(array); 10977 } 10978 } 10979 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10980 } 10981 10982 public final void addService(PackageParser.Service s) { 10983 mServices.put(s.getComponentName(), s); 10984 if (DEBUG_SHOW_INFO) { 10985 Log.v(TAG, " " 10986 + (s.info.nonLocalizedLabel != null 10987 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10988 Log.v(TAG, " Class=" + s.info.name); 10989 } 10990 final int NI = s.intents.size(); 10991 int j; 10992 for (j=0; j<NI; j++) { 10993 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10994 if (DEBUG_SHOW_INFO) { 10995 Log.v(TAG, " IntentFilter:"); 10996 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10997 } 10998 if (!intent.debugCheck()) { 10999 Log.w(TAG, "==> For Service " + s.info.name); 11000 } 11001 addFilter(intent); 11002 } 11003 } 11004 11005 public final void removeService(PackageParser.Service s) { 11006 mServices.remove(s.getComponentName()); 11007 if (DEBUG_SHOW_INFO) { 11008 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11009 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11010 Log.v(TAG, " Class=" + s.info.name); 11011 } 11012 final int NI = s.intents.size(); 11013 int j; 11014 for (j=0; j<NI; j++) { 11015 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11016 if (DEBUG_SHOW_INFO) { 11017 Log.v(TAG, " IntentFilter:"); 11018 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11019 } 11020 removeFilter(intent); 11021 } 11022 } 11023 11024 @Override 11025 protected boolean allowFilterResult( 11026 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11027 ServiceInfo filterSi = filter.service.info; 11028 for (int i=dest.size()-1; i>=0; i--) { 11029 ServiceInfo destAi = dest.get(i).serviceInfo; 11030 if (destAi.name == filterSi.name 11031 && destAi.packageName == filterSi.packageName) { 11032 return false; 11033 } 11034 } 11035 return true; 11036 } 11037 11038 @Override 11039 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11040 return new PackageParser.ServiceIntentInfo[size]; 11041 } 11042 11043 @Override 11044 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11045 if (!sUserManager.exists(userId)) return true; 11046 PackageParser.Package p = filter.service.owner; 11047 if (p != null) { 11048 PackageSetting ps = (PackageSetting)p.mExtras; 11049 if (ps != null) { 11050 // System apps are never considered stopped for purposes of 11051 // filtering, because there may be no way for the user to 11052 // actually re-launch them. 11053 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11054 && ps.getStopped(userId); 11055 } 11056 } 11057 return false; 11058 } 11059 11060 @Override 11061 protected boolean isPackageForFilter(String packageName, 11062 PackageParser.ServiceIntentInfo info) { 11063 return packageName.equals(info.service.owner.packageName); 11064 } 11065 11066 @Override 11067 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11068 int match, int userId) { 11069 if (!sUserManager.exists(userId)) return null; 11070 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11071 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11072 return null; 11073 } 11074 final PackageParser.Service service = info.service; 11075 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11076 if (ps == null) { 11077 return null; 11078 } 11079 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11080 ps.readUserState(userId), userId); 11081 if (si == null) { 11082 return null; 11083 } 11084 final ResolveInfo res = new ResolveInfo(); 11085 res.serviceInfo = si; 11086 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11087 res.filter = filter; 11088 } 11089 res.priority = info.getPriority(); 11090 res.preferredOrder = service.owner.mPreferredOrder; 11091 res.match = match; 11092 res.isDefault = info.hasDefault; 11093 res.labelRes = info.labelRes; 11094 res.nonLocalizedLabel = info.nonLocalizedLabel; 11095 res.icon = info.icon; 11096 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11097 return res; 11098 } 11099 11100 @Override 11101 protected void sortResults(List<ResolveInfo> results) { 11102 Collections.sort(results, mResolvePrioritySorter); 11103 } 11104 11105 @Override 11106 protected void dumpFilter(PrintWriter out, String prefix, 11107 PackageParser.ServiceIntentInfo filter) { 11108 out.print(prefix); out.print( 11109 Integer.toHexString(System.identityHashCode(filter.service))); 11110 out.print(' '); 11111 filter.service.printComponentShortName(out); 11112 out.print(" filter "); 11113 out.println(Integer.toHexString(System.identityHashCode(filter))); 11114 } 11115 11116 @Override 11117 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11118 return filter.service; 11119 } 11120 11121 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11122 PackageParser.Service service = (PackageParser.Service)label; 11123 out.print(prefix); out.print( 11124 Integer.toHexString(System.identityHashCode(service))); 11125 out.print(' '); 11126 service.printComponentShortName(out); 11127 if (count > 1) { 11128 out.print(" ("); out.print(count); out.print(" filters)"); 11129 } 11130 out.println(); 11131 } 11132 11133// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11134// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11135// final List<ResolveInfo> retList = Lists.newArrayList(); 11136// while (i.hasNext()) { 11137// final ResolveInfo resolveInfo = (ResolveInfo) i; 11138// if (isEnabledLP(resolveInfo.serviceInfo)) { 11139// retList.add(resolveInfo); 11140// } 11141// } 11142// return retList; 11143// } 11144 11145 // Keys are String (activity class name), values are Activity. 11146 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11147 = new ArrayMap<ComponentName, PackageParser.Service>(); 11148 private int mFlags; 11149 }; 11150 11151 private final class ProviderIntentResolver 11152 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11153 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11154 boolean defaultOnly, int userId) { 11155 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11156 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11157 } 11158 11159 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11160 int userId) { 11161 if (!sUserManager.exists(userId)) 11162 return null; 11163 mFlags = flags; 11164 return super.queryIntent(intent, resolvedType, 11165 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11166 } 11167 11168 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11169 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11170 if (!sUserManager.exists(userId)) 11171 return null; 11172 if (packageProviders == null) { 11173 return null; 11174 } 11175 mFlags = flags; 11176 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11177 final int N = packageProviders.size(); 11178 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11179 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11180 11181 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11182 for (int i = 0; i < N; ++i) { 11183 intentFilters = packageProviders.get(i).intents; 11184 if (intentFilters != null && intentFilters.size() > 0) { 11185 PackageParser.ProviderIntentInfo[] array = 11186 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11187 intentFilters.toArray(array); 11188 listCut.add(array); 11189 } 11190 } 11191 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11192 } 11193 11194 public final void addProvider(PackageParser.Provider p) { 11195 if (mProviders.containsKey(p.getComponentName())) { 11196 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11197 return; 11198 } 11199 11200 mProviders.put(p.getComponentName(), p); 11201 if (DEBUG_SHOW_INFO) { 11202 Log.v(TAG, " " 11203 + (p.info.nonLocalizedLabel != null 11204 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11205 Log.v(TAG, " Class=" + p.info.name); 11206 } 11207 final int NI = p.intents.size(); 11208 int j; 11209 for (j = 0; j < NI; j++) { 11210 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11211 if (DEBUG_SHOW_INFO) { 11212 Log.v(TAG, " IntentFilter:"); 11213 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11214 } 11215 if (!intent.debugCheck()) { 11216 Log.w(TAG, "==> For Provider " + p.info.name); 11217 } 11218 addFilter(intent); 11219 } 11220 } 11221 11222 public final void removeProvider(PackageParser.Provider p) { 11223 mProviders.remove(p.getComponentName()); 11224 if (DEBUG_SHOW_INFO) { 11225 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11226 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11227 Log.v(TAG, " Class=" + p.info.name); 11228 } 11229 final int NI = p.intents.size(); 11230 int j; 11231 for (j = 0; j < NI; j++) { 11232 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11233 if (DEBUG_SHOW_INFO) { 11234 Log.v(TAG, " IntentFilter:"); 11235 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11236 } 11237 removeFilter(intent); 11238 } 11239 } 11240 11241 @Override 11242 protected boolean allowFilterResult( 11243 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11244 ProviderInfo filterPi = filter.provider.info; 11245 for (int i = dest.size() - 1; i >= 0; i--) { 11246 ProviderInfo destPi = dest.get(i).providerInfo; 11247 if (destPi.name == filterPi.name 11248 && destPi.packageName == filterPi.packageName) { 11249 return false; 11250 } 11251 } 11252 return true; 11253 } 11254 11255 @Override 11256 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11257 return new PackageParser.ProviderIntentInfo[size]; 11258 } 11259 11260 @Override 11261 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11262 if (!sUserManager.exists(userId)) 11263 return true; 11264 PackageParser.Package p = filter.provider.owner; 11265 if (p != null) { 11266 PackageSetting ps = (PackageSetting) p.mExtras; 11267 if (ps != null) { 11268 // System apps are never considered stopped for purposes of 11269 // filtering, because there may be no way for the user to 11270 // actually re-launch them. 11271 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11272 && ps.getStopped(userId); 11273 } 11274 } 11275 return false; 11276 } 11277 11278 @Override 11279 protected boolean isPackageForFilter(String packageName, 11280 PackageParser.ProviderIntentInfo info) { 11281 return packageName.equals(info.provider.owner.packageName); 11282 } 11283 11284 @Override 11285 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11286 int match, int userId) { 11287 if (!sUserManager.exists(userId)) 11288 return null; 11289 final PackageParser.ProviderIntentInfo info = filter; 11290 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11291 return null; 11292 } 11293 final PackageParser.Provider provider = info.provider; 11294 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11295 if (ps == null) { 11296 return null; 11297 } 11298 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11299 ps.readUserState(userId), userId); 11300 if (pi == null) { 11301 return null; 11302 } 11303 final ResolveInfo res = new ResolveInfo(); 11304 res.providerInfo = pi; 11305 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11306 res.filter = filter; 11307 } 11308 res.priority = info.getPriority(); 11309 res.preferredOrder = provider.owner.mPreferredOrder; 11310 res.match = match; 11311 res.isDefault = info.hasDefault; 11312 res.labelRes = info.labelRes; 11313 res.nonLocalizedLabel = info.nonLocalizedLabel; 11314 res.icon = info.icon; 11315 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11316 return res; 11317 } 11318 11319 @Override 11320 protected void sortResults(List<ResolveInfo> results) { 11321 Collections.sort(results, mResolvePrioritySorter); 11322 } 11323 11324 @Override 11325 protected void dumpFilter(PrintWriter out, String prefix, 11326 PackageParser.ProviderIntentInfo filter) { 11327 out.print(prefix); 11328 out.print( 11329 Integer.toHexString(System.identityHashCode(filter.provider))); 11330 out.print(' '); 11331 filter.provider.printComponentShortName(out); 11332 out.print(" filter "); 11333 out.println(Integer.toHexString(System.identityHashCode(filter))); 11334 } 11335 11336 @Override 11337 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11338 return filter.provider; 11339 } 11340 11341 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11342 PackageParser.Provider provider = (PackageParser.Provider)label; 11343 out.print(prefix); out.print( 11344 Integer.toHexString(System.identityHashCode(provider))); 11345 out.print(' '); 11346 provider.printComponentShortName(out); 11347 if (count > 1) { 11348 out.print(" ("); out.print(count); out.print(" filters)"); 11349 } 11350 out.println(); 11351 } 11352 11353 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11354 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11355 private int mFlags; 11356 } 11357 11358 private static final class EphemeralIntentResolver 11359 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11360 @Override 11361 protected EphemeralResolveIntentInfo[] newArray(int size) { 11362 return new EphemeralResolveIntentInfo[size]; 11363 } 11364 11365 @Override 11366 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11367 return true; 11368 } 11369 11370 @Override 11371 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11372 int userId) { 11373 if (!sUserManager.exists(userId)) { 11374 return null; 11375 } 11376 return info.getEphemeralResolveInfo(); 11377 } 11378 } 11379 11380 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11381 new Comparator<ResolveInfo>() { 11382 public int compare(ResolveInfo r1, ResolveInfo r2) { 11383 int v1 = r1.priority; 11384 int v2 = r2.priority; 11385 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11386 if (v1 != v2) { 11387 return (v1 > v2) ? -1 : 1; 11388 } 11389 v1 = r1.preferredOrder; 11390 v2 = r2.preferredOrder; 11391 if (v1 != v2) { 11392 return (v1 > v2) ? -1 : 1; 11393 } 11394 if (r1.isDefault != r2.isDefault) { 11395 return r1.isDefault ? -1 : 1; 11396 } 11397 v1 = r1.match; 11398 v2 = r2.match; 11399 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11400 if (v1 != v2) { 11401 return (v1 > v2) ? -1 : 1; 11402 } 11403 if (r1.system != r2.system) { 11404 return r1.system ? -1 : 1; 11405 } 11406 if (r1.activityInfo != null) { 11407 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11408 } 11409 if (r1.serviceInfo != null) { 11410 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11411 } 11412 if (r1.providerInfo != null) { 11413 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11414 } 11415 return 0; 11416 } 11417 }; 11418 11419 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11420 new Comparator<ProviderInfo>() { 11421 public int compare(ProviderInfo p1, ProviderInfo p2) { 11422 final int v1 = p1.initOrder; 11423 final int v2 = p2.initOrder; 11424 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11425 } 11426 }; 11427 11428 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11429 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11430 final int[] userIds) { 11431 mHandler.post(new Runnable() { 11432 @Override 11433 public void run() { 11434 try { 11435 final IActivityManager am = ActivityManagerNative.getDefault(); 11436 if (am == null) return; 11437 final int[] resolvedUserIds; 11438 if (userIds == null) { 11439 resolvedUserIds = am.getRunningUserIds(); 11440 } else { 11441 resolvedUserIds = userIds; 11442 } 11443 for (int id : resolvedUserIds) { 11444 final Intent intent = new Intent(action, 11445 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11446 if (extras != null) { 11447 intent.putExtras(extras); 11448 } 11449 if (targetPkg != null) { 11450 intent.setPackage(targetPkg); 11451 } 11452 // Modify the UID when posting to other users 11453 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11454 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11455 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11456 intent.putExtra(Intent.EXTRA_UID, uid); 11457 } 11458 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11459 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11460 if (DEBUG_BROADCASTS) { 11461 RuntimeException here = new RuntimeException("here"); 11462 here.fillInStackTrace(); 11463 Slog.d(TAG, "Sending to user " + id + ": " 11464 + intent.toShortString(false, true, false, false) 11465 + " " + intent.getExtras(), here); 11466 } 11467 am.broadcastIntent(null, intent, null, finishedReceiver, 11468 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11469 null, finishedReceiver != null, false, id); 11470 } 11471 } catch (RemoteException ex) { 11472 } 11473 } 11474 }); 11475 } 11476 11477 /** 11478 * Check if the external storage media is available. This is true if there 11479 * is a mounted external storage medium or if the external storage is 11480 * emulated. 11481 */ 11482 private boolean isExternalMediaAvailable() { 11483 return mMediaMounted || Environment.isExternalStorageEmulated(); 11484 } 11485 11486 @Override 11487 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11488 // writer 11489 synchronized (mPackages) { 11490 if (!isExternalMediaAvailable()) { 11491 // If the external storage is no longer mounted at this point, 11492 // the caller may not have been able to delete all of this 11493 // packages files and can not delete any more. Bail. 11494 return null; 11495 } 11496 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11497 if (lastPackage != null) { 11498 pkgs.remove(lastPackage); 11499 } 11500 if (pkgs.size() > 0) { 11501 return pkgs.get(0); 11502 } 11503 } 11504 return null; 11505 } 11506 11507 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11508 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11509 userId, andCode ? 1 : 0, packageName); 11510 if (mSystemReady) { 11511 msg.sendToTarget(); 11512 } else { 11513 if (mPostSystemReadyMessages == null) { 11514 mPostSystemReadyMessages = new ArrayList<>(); 11515 } 11516 mPostSystemReadyMessages.add(msg); 11517 } 11518 } 11519 11520 void startCleaningPackages() { 11521 // reader 11522 if (!isExternalMediaAvailable()) { 11523 return; 11524 } 11525 synchronized (mPackages) { 11526 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11527 return; 11528 } 11529 } 11530 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11531 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11532 IActivityManager am = ActivityManagerNative.getDefault(); 11533 if (am != null) { 11534 try { 11535 am.startService(null, intent, null, mContext.getOpPackageName(), 11536 UserHandle.USER_SYSTEM); 11537 } catch (RemoteException e) { 11538 } 11539 } 11540 } 11541 11542 @Override 11543 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11544 int installFlags, String installerPackageName, int userId) { 11545 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11546 11547 final int callingUid = Binder.getCallingUid(); 11548 enforceCrossUserPermission(callingUid, userId, 11549 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11550 11551 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11552 try { 11553 if (observer != null) { 11554 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11555 } 11556 } catch (RemoteException re) { 11557 } 11558 return; 11559 } 11560 11561 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11562 installFlags |= PackageManager.INSTALL_FROM_ADB; 11563 11564 } else { 11565 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11566 // about installerPackageName. 11567 11568 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11569 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11570 } 11571 11572 UserHandle user; 11573 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11574 user = UserHandle.ALL; 11575 } else { 11576 user = new UserHandle(userId); 11577 } 11578 11579 // Only system components can circumvent runtime permissions when installing. 11580 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11581 && mContext.checkCallingOrSelfPermission(Manifest.permission 11582 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11583 throw new SecurityException("You need the " 11584 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11585 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11586 } 11587 11588 final File originFile = new File(originPath); 11589 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11590 11591 final Message msg = mHandler.obtainMessage(INIT_COPY); 11592 final VerificationInfo verificationInfo = new VerificationInfo( 11593 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11594 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11595 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11596 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11597 null /*certificates*/); 11598 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11599 msg.obj = params; 11600 11601 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11602 System.identityHashCode(msg.obj)); 11603 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11604 System.identityHashCode(msg.obj)); 11605 11606 mHandler.sendMessage(msg); 11607 } 11608 11609 void installStage(String packageName, File stagedDir, String stagedCid, 11610 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11611 String installerPackageName, int installerUid, UserHandle user, 11612 Certificate[][] certificates) { 11613 if (DEBUG_EPHEMERAL) { 11614 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11615 Slog.d(TAG, "Ephemeral install of " + packageName); 11616 } 11617 } 11618 final VerificationInfo verificationInfo = new VerificationInfo( 11619 sessionParams.originatingUri, sessionParams.referrerUri, 11620 sessionParams.originatingUid, installerUid); 11621 11622 final OriginInfo origin; 11623 if (stagedDir != null) { 11624 origin = OriginInfo.fromStagedFile(stagedDir); 11625 } else { 11626 origin = OriginInfo.fromStagedContainer(stagedCid); 11627 } 11628 11629 final Message msg = mHandler.obtainMessage(INIT_COPY); 11630 final InstallParams params = new InstallParams(origin, null, observer, 11631 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11632 verificationInfo, user, sessionParams.abiOverride, 11633 sessionParams.grantedRuntimePermissions, certificates); 11634 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11635 msg.obj = params; 11636 11637 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11638 System.identityHashCode(msg.obj)); 11639 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11640 System.identityHashCode(msg.obj)); 11641 11642 mHandler.sendMessage(msg); 11643 } 11644 11645 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11646 int userId) { 11647 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11648 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11649 } 11650 11651 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11652 int appId, int userId) { 11653 Bundle extras = new Bundle(1); 11654 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11655 11656 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11657 packageName, extras, 0, null, null, new int[] {userId}); 11658 try { 11659 IActivityManager am = ActivityManagerNative.getDefault(); 11660 if (isSystem && am.isUserRunning(userId, 0)) { 11661 // The just-installed/enabled app is bundled on the system, so presumed 11662 // to be able to run automatically without needing an explicit launch. 11663 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11664 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11665 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11666 .setPackage(packageName); 11667 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11668 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11669 } 11670 } catch (RemoteException e) { 11671 // shouldn't happen 11672 Slog.w(TAG, "Unable to bootstrap installed package", e); 11673 } 11674 } 11675 11676 @Override 11677 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11678 int userId) { 11679 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11680 PackageSetting pkgSetting; 11681 final int uid = Binder.getCallingUid(); 11682 enforceCrossUserPermission(uid, userId, 11683 true /* requireFullPermission */, true /* checkShell */, 11684 "setApplicationHiddenSetting for user " + userId); 11685 11686 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11687 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11688 return false; 11689 } 11690 11691 long callingId = Binder.clearCallingIdentity(); 11692 try { 11693 boolean sendAdded = false; 11694 boolean sendRemoved = false; 11695 // writer 11696 synchronized (mPackages) { 11697 pkgSetting = mSettings.mPackages.get(packageName); 11698 if (pkgSetting == null) { 11699 return false; 11700 } 11701 // Only allow protected packages to hide themselves. 11702 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11703 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11704 Slog.w(TAG, "Not hiding protected package: " + packageName); 11705 return false; 11706 } 11707 if (pkgSetting.getHidden(userId) != hidden) { 11708 pkgSetting.setHidden(hidden, userId); 11709 mSettings.writePackageRestrictionsLPr(userId); 11710 if (hidden) { 11711 sendRemoved = true; 11712 } else { 11713 sendAdded = true; 11714 } 11715 } 11716 } 11717 if (sendAdded) { 11718 sendPackageAddedForUser(packageName, pkgSetting, userId); 11719 return true; 11720 } 11721 if (sendRemoved) { 11722 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11723 "hiding pkg"); 11724 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11725 return true; 11726 } 11727 } finally { 11728 Binder.restoreCallingIdentity(callingId); 11729 } 11730 return false; 11731 } 11732 11733 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11734 int userId) { 11735 final PackageRemovedInfo info = new PackageRemovedInfo(); 11736 info.removedPackage = packageName; 11737 info.removedUsers = new int[] {userId}; 11738 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11739 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11740 } 11741 11742 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11743 if (pkgList.length > 0) { 11744 Bundle extras = new Bundle(1); 11745 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11746 11747 sendPackageBroadcast( 11748 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11749 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11750 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11751 new int[] {userId}); 11752 } 11753 } 11754 11755 /** 11756 * Returns true if application is not found or there was an error. Otherwise it returns 11757 * the hidden state of the package for the given user. 11758 */ 11759 @Override 11760 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11761 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11762 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11763 true /* requireFullPermission */, false /* checkShell */, 11764 "getApplicationHidden for user " + userId); 11765 PackageSetting pkgSetting; 11766 long callingId = Binder.clearCallingIdentity(); 11767 try { 11768 // writer 11769 synchronized (mPackages) { 11770 pkgSetting = mSettings.mPackages.get(packageName); 11771 if (pkgSetting == null) { 11772 return true; 11773 } 11774 return pkgSetting.getHidden(userId); 11775 } 11776 } finally { 11777 Binder.restoreCallingIdentity(callingId); 11778 } 11779 } 11780 11781 /** 11782 * @hide 11783 */ 11784 @Override 11785 public int installExistingPackageAsUser(String packageName, int userId) { 11786 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11787 null); 11788 PackageSetting pkgSetting; 11789 final int uid = Binder.getCallingUid(); 11790 enforceCrossUserPermission(uid, userId, 11791 true /* requireFullPermission */, true /* checkShell */, 11792 "installExistingPackage for user " + userId); 11793 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11794 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11795 } 11796 11797 long callingId = Binder.clearCallingIdentity(); 11798 try { 11799 boolean installed = false; 11800 11801 // writer 11802 synchronized (mPackages) { 11803 pkgSetting = mSettings.mPackages.get(packageName); 11804 if (pkgSetting == null) { 11805 return PackageManager.INSTALL_FAILED_INVALID_URI; 11806 } 11807 if (!pkgSetting.getInstalled(userId)) { 11808 pkgSetting.setInstalled(true, userId); 11809 pkgSetting.setHidden(false, userId); 11810 mSettings.writePackageRestrictionsLPr(userId); 11811 installed = true; 11812 } 11813 } 11814 11815 if (installed) { 11816 if (pkgSetting.pkg != null) { 11817 synchronized (mInstallLock) { 11818 // We don't need to freeze for a brand new install 11819 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11820 } 11821 } 11822 sendPackageAddedForUser(packageName, pkgSetting, userId); 11823 } 11824 } finally { 11825 Binder.restoreCallingIdentity(callingId); 11826 } 11827 11828 return PackageManager.INSTALL_SUCCEEDED; 11829 } 11830 11831 boolean isUserRestricted(int userId, String restrictionKey) { 11832 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11833 if (restrictions.getBoolean(restrictionKey, false)) { 11834 Log.w(TAG, "User is restricted: " + restrictionKey); 11835 return true; 11836 } 11837 return false; 11838 } 11839 11840 @Override 11841 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11842 int userId) { 11843 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11844 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11845 true /* requireFullPermission */, true /* checkShell */, 11846 "setPackagesSuspended for user " + userId); 11847 11848 if (ArrayUtils.isEmpty(packageNames)) { 11849 return packageNames; 11850 } 11851 11852 // List of package names for whom the suspended state has changed. 11853 List<String> changedPackages = new ArrayList<>(packageNames.length); 11854 // List of package names for whom the suspended state is not set as requested in this 11855 // method. 11856 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11857 long callingId = Binder.clearCallingIdentity(); 11858 try { 11859 for (int i = 0; i < packageNames.length; i++) { 11860 String packageName = packageNames[i]; 11861 boolean changed = false; 11862 final int appId; 11863 synchronized (mPackages) { 11864 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11865 if (pkgSetting == null) { 11866 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11867 + "\". Skipping suspending/un-suspending."); 11868 unactionedPackages.add(packageName); 11869 continue; 11870 } 11871 appId = pkgSetting.appId; 11872 if (pkgSetting.getSuspended(userId) != suspended) { 11873 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11874 unactionedPackages.add(packageName); 11875 continue; 11876 } 11877 pkgSetting.setSuspended(suspended, userId); 11878 mSettings.writePackageRestrictionsLPr(userId); 11879 changed = true; 11880 changedPackages.add(packageName); 11881 } 11882 } 11883 11884 if (changed && suspended) { 11885 killApplication(packageName, UserHandle.getUid(userId, appId), 11886 "suspending package"); 11887 } 11888 } 11889 } finally { 11890 Binder.restoreCallingIdentity(callingId); 11891 } 11892 11893 if (!changedPackages.isEmpty()) { 11894 sendPackagesSuspendedForUser(changedPackages.toArray( 11895 new String[changedPackages.size()]), userId, suspended); 11896 } 11897 11898 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11899 } 11900 11901 @Override 11902 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11903 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11904 true /* requireFullPermission */, false /* checkShell */, 11905 "isPackageSuspendedForUser for user " + userId); 11906 synchronized (mPackages) { 11907 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11908 if (pkgSetting == null) { 11909 throw new IllegalArgumentException("Unknown target package: " + packageName); 11910 } 11911 return pkgSetting.getSuspended(userId); 11912 } 11913 } 11914 11915 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11916 if (isPackageDeviceAdmin(packageName, userId)) { 11917 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11918 + "\": has an active device admin"); 11919 return false; 11920 } 11921 11922 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11923 if (packageName.equals(activeLauncherPackageName)) { 11924 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11925 + "\": contains the active launcher"); 11926 return false; 11927 } 11928 11929 if (packageName.equals(mRequiredInstallerPackage)) { 11930 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11931 + "\": required for package installation"); 11932 return false; 11933 } 11934 11935 if (packageName.equals(mRequiredVerifierPackage)) { 11936 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11937 + "\": required for package verification"); 11938 return false; 11939 } 11940 11941 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11942 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11943 + "\": is the default dialer"); 11944 return false; 11945 } 11946 11947 return true; 11948 } 11949 11950 private String getActiveLauncherPackageName(int userId) { 11951 Intent intent = new Intent(Intent.ACTION_MAIN); 11952 intent.addCategory(Intent.CATEGORY_HOME); 11953 ResolveInfo resolveInfo = resolveIntent( 11954 intent, 11955 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11956 PackageManager.MATCH_DEFAULT_ONLY, 11957 userId); 11958 11959 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11960 } 11961 11962 private String getDefaultDialerPackageName(int userId) { 11963 synchronized (mPackages) { 11964 return mSettings.getDefaultDialerPackageNameLPw(userId); 11965 } 11966 } 11967 11968 @Override 11969 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11970 mContext.enforceCallingOrSelfPermission( 11971 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11972 "Only package verification agents can verify applications"); 11973 11974 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11975 final PackageVerificationResponse response = new PackageVerificationResponse( 11976 verificationCode, Binder.getCallingUid()); 11977 msg.arg1 = id; 11978 msg.obj = response; 11979 mHandler.sendMessage(msg); 11980 } 11981 11982 @Override 11983 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11984 long millisecondsToDelay) { 11985 mContext.enforceCallingOrSelfPermission( 11986 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11987 "Only package verification agents can extend verification timeouts"); 11988 11989 final PackageVerificationState state = mPendingVerification.get(id); 11990 final PackageVerificationResponse response = new PackageVerificationResponse( 11991 verificationCodeAtTimeout, Binder.getCallingUid()); 11992 11993 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11994 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11995 } 11996 if (millisecondsToDelay < 0) { 11997 millisecondsToDelay = 0; 11998 } 11999 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12000 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12001 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12002 } 12003 12004 if ((state != null) && !state.timeoutExtended()) { 12005 state.extendTimeout(); 12006 12007 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12008 msg.arg1 = id; 12009 msg.obj = response; 12010 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12011 } 12012 } 12013 12014 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12015 int verificationCode, UserHandle user) { 12016 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12017 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12018 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12019 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12020 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12021 12022 mContext.sendBroadcastAsUser(intent, user, 12023 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12024 } 12025 12026 private ComponentName matchComponentForVerifier(String packageName, 12027 List<ResolveInfo> receivers) { 12028 ActivityInfo targetReceiver = null; 12029 12030 final int NR = receivers.size(); 12031 for (int i = 0; i < NR; i++) { 12032 final ResolveInfo info = receivers.get(i); 12033 if (info.activityInfo == null) { 12034 continue; 12035 } 12036 12037 if (packageName.equals(info.activityInfo.packageName)) { 12038 targetReceiver = info.activityInfo; 12039 break; 12040 } 12041 } 12042 12043 if (targetReceiver == null) { 12044 return null; 12045 } 12046 12047 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12048 } 12049 12050 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12051 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12052 if (pkgInfo.verifiers.length == 0) { 12053 return null; 12054 } 12055 12056 final int N = pkgInfo.verifiers.length; 12057 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12058 for (int i = 0; i < N; i++) { 12059 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12060 12061 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12062 receivers); 12063 if (comp == null) { 12064 continue; 12065 } 12066 12067 final int verifierUid = getUidForVerifier(verifierInfo); 12068 if (verifierUid == -1) { 12069 continue; 12070 } 12071 12072 if (DEBUG_VERIFY) { 12073 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12074 + " with the correct signature"); 12075 } 12076 sufficientVerifiers.add(comp); 12077 verificationState.addSufficientVerifier(verifierUid); 12078 } 12079 12080 return sufficientVerifiers; 12081 } 12082 12083 private int getUidForVerifier(VerifierInfo verifierInfo) { 12084 synchronized (mPackages) { 12085 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12086 if (pkg == null) { 12087 return -1; 12088 } else if (pkg.mSignatures.length != 1) { 12089 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12090 + " has more than one signature; ignoring"); 12091 return -1; 12092 } 12093 12094 /* 12095 * If the public key of the package's signature does not match 12096 * our expected public key, then this is a different package and 12097 * we should skip. 12098 */ 12099 12100 final byte[] expectedPublicKey; 12101 try { 12102 final Signature verifierSig = pkg.mSignatures[0]; 12103 final PublicKey publicKey = verifierSig.getPublicKey(); 12104 expectedPublicKey = publicKey.getEncoded(); 12105 } catch (CertificateException e) { 12106 return -1; 12107 } 12108 12109 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12110 12111 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12112 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12113 + " does not have the expected public key; ignoring"); 12114 return -1; 12115 } 12116 12117 return pkg.applicationInfo.uid; 12118 } 12119 } 12120 12121 @Override 12122 public void finishPackageInstall(int token, boolean didLaunch) { 12123 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12124 12125 if (DEBUG_INSTALL) { 12126 Slog.v(TAG, "BM finishing package install for " + token); 12127 } 12128 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12129 12130 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12131 mHandler.sendMessage(msg); 12132 } 12133 12134 /** 12135 * Get the verification agent timeout. 12136 * 12137 * @return verification timeout in milliseconds 12138 */ 12139 private long getVerificationTimeout() { 12140 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12141 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12142 DEFAULT_VERIFICATION_TIMEOUT); 12143 } 12144 12145 /** 12146 * Get the default verification agent response code. 12147 * 12148 * @return default verification response code 12149 */ 12150 private int getDefaultVerificationResponse() { 12151 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12152 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12153 DEFAULT_VERIFICATION_RESPONSE); 12154 } 12155 12156 /** 12157 * Check whether or not package verification has been enabled. 12158 * 12159 * @return true if verification should be performed 12160 */ 12161 private boolean isVerificationEnabled(int userId, int installFlags) { 12162 if (!DEFAULT_VERIFY_ENABLE) { 12163 return false; 12164 } 12165 // Ephemeral apps don't get the full verification treatment 12166 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12167 if (DEBUG_EPHEMERAL) { 12168 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12169 } 12170 return false; 12171 } 12172 12173 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12174 12175 // Check if installing from ADB 12176 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12177 // Do not run verification in a test harness environment 12178 if (ActivityManager.isRunningInTestHarness()) { 12179 return false; 12180 } 12181 if (ensureVerifyAppsEnabled) { 12182 return true; 12183 } 12184 // Check if the developer does not want package verification for ADB installs 12185 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12186 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12187 return false; 12188 } 12189 } 12190 12191 if (ensureVerifyAppsEnabled) { 12192 return true; 12193 } 12194 12195 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12196 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12197 } 12198 12199 @Override 12200 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12201 throws RemoteException { 12202 mContext.enforceCallingOrSelfPermission( 12203 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12204 "Only intentfilter verification agents can verify applications"); 12205 12206 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12207 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12208 Binder.getCallingUid(), verificationCode, failedDomains); 12209 msg.arg1 = id; 12210 msg.obj = response; 12211 mHandler.sendMessage(msg); 12212 } 12213 12214 @Override 12215 public int getIntentVerificationStatus(String packageName, int userId) { 12216 synchronized (mPackages) { 12217 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12218 } 12219 } 12220 12221 @Override 12222 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12223 mContext.enforceCallingOrSelfPermission( 12224 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12225 12226 boolean result = false; 12227 synchronized (mPackages) { 12228 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12229 } 12230 if (result) { 12231 scheduleWritePackageRestrictionsLocked(userId); 12232 } 12233 return result; 12234 } 12235 12236 @Override 12237 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12238 String packageName) { 12239 synchronized (mPackages) { 12240 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12241 } 12242 } 12243 12244 @Override 12245 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12246 if (TextUtils.isEmpty(packageName)) { 12247 return ParceledListSlice.emptyList(); 12248 } 12249 synchronized (mPackages) { 12250 PackageParser.Package pkg = mPackages.get(packageName); 12251 if (pkg == null || pkg.activities == null) { 12252 return ParceledListSlice.emptyList(); 12253 } 12254 final int count = pkg.activities.size(); 12255 ArrayList<IntentFilter> result = new ArrayList<>(); 12256 for (int n=0; n<count; n++) { 12257 PackageParser.Activity activity = pkg.activities.get(n); 12258 if (activity.intents != null && activity.intents.size() > 0) { 12259 result.addAll(activity.intents); 12260 } 12261 } 12262 return new ParceledListSlice<>(result); 12263 } 12264 } 12265 12266 @Override 12267 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12268 mContext.enforceCallingOrSelfPermission( 12269 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12270 12271 synchronized (mPackages) { 12272 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12273 if (packageName != null) { 12274 result |= updateIntentVerificationStatus(packageName, 12275 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12276 userId); 12277 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12278 packageName, userId); 12279 } 12280 return result; 12281 } 12282 } 12283 12284 @Override 12285 public String getDefaultBrowserPackageName(int userId) { 12286 synchronized (mPackages) { 12287 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12288 } 12289 } 12290 12291 /** 12292 * Get the "allow unknown sources" setting. 12293 * 12294 * @return the current "allow unknown sources" setting 12295 */ 12296 private int getUnknownSourcesSettings() { 12297 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12298 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12299 -1); 12300 } 12301 12302 @Override 12303 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12304 final int uid = Binder.getCallingUid(); 12305 // writer 12306 synchronized (mPackages) { 12307 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12308 if (targetPackageSetting == null) { 12309 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12310 } 12311 12312 PackageSetting installerPackageSetting; 12313 if (installerPackageName != null) { 12314 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12315 if (installerPackageSetting == null) { 12316 throw new IllegalArgumentException("Unknown installer package: " 12317 + installerPackageName); 12318 } 12319 } else { 12320 installerPackageSetting = null; 12321 } 12322 12323 Signature[] callerSignature; 12324 Object obj = mSettings.getUserIdLPr(uid); 12325 if (obj != null) { 12326 if (obj instanceof SharedUserSetting) { 12327 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12328 } else if (obj instanceof PackageSetting) { 12329 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12330 } else { 12331 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12332 } 12333 } else { 12334 throw new SecurityException("Unknown calling UID: " + uid); 12335 } 12336 12337 // Verify: can't set installerPackageName to a package that is 12338 // not signed with the same cert as the caller. 12339 if (installerPackageSetting != null) { 12340 if (compareSignatures(callerSignature, 12341 installerPackageSetting.signatures.mSignatures) 12342 != PackageManager.SIGNATURE_MATCH) { 12343 throw new SecurityException( 12344 "Caller does not have same cert as new installer package " 12345 + installerPackageName); 12346 } 12347 } 12348 12349 // Verify: if target already has an installer package, it must 12350 // be signed with the same cert as the caller. 12351 if (targetPackageSetting.installerPackageName != null) { 12352 PackageSetting setting = mSettings.mPackages.get( 12353 targetPackageSetting.installerPackageName); 12354 // If the currently set package isn't valid, then it's always 12355 // okay to change it. 12356 if (setting != null) { 12357 if (compareSignatures(callerSignature, 12358 setting.signatures.mSignatures) 12359 != PackageManager.SIGNATURE_MATCH) { 12360 throw new SecurityException( 12361 "Caller does not have same cert as old installer package " 12362 + targetPackageSetting.installerPackageName); 12363 } 12364 } 12365 } 12366 12367 // Okay! 12368 targetPackageSetting.installerPackageName = installerPackageName; 12369 if (installerPackageName != null) { 12370 mSettings.mInstallerPackages.add(installerPackageName); 12371 } 12372 scheduleWriteSettingsLocked(); 12373 } 12374 } 12375 12376 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12377 // Queue up an async operation since the package installation may take a little while. 12378 mHandler.post(new Runnable() { 12379 public void run() { 12380 mHandler.removeCallbacks(this); 12381 // Result object to be returned 12382 PackageInstalledInfo res = new PackageInstalledInfo(); 12383 res.setReturnCode(currentStatus); 12384 res.uid = -1; 12385 res.pkg = null; 12386 res.removedInfo = null; 12387 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12388 args.doPreInstall(res.returnCode); 12389 synchronized (mInstallLock) { 12390 installPackageTracedLI(args, res); 12391 } 12392 args.doPostInstall(res.returnCode, res.uid); 12393 } 12394 12395 // A restore should be performed at this point if (a) the install 12396 // succeeded, (b) the operation is not an update, and (c) the new 12397 // package has not opted out of backup participation. 12398 final boolean update = res.removedInfo != null 12399 && res.removedInfo.removedPackage != null; 12400 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12401 boolean doRestore = !update 12402 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12403 12404 // Set up the post-install work request bookkeeping. This will be used 12405 // and cleaned up by the post-install event handling regardless of whether 12406 // there's a restore pass performed. Token values are >= 1. 12407 int token; 12408 if (mNextInstallToken < 0) mNextInstallToken = 1; 12409 token = mNextInstallToken++; 12410 12411 PostInstallData data = new PostInstallData(args, res); 12412 mRunningInstalls.put(token, data); 12413 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12414 12415 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12416 // Pass responsibility to the Backup Manager. It will perform a 12417 // restore if appropriate, then pass responsibility back to the 12418 // Package Manager to run the post-install observer callbacks 12419 // and broadcasts. 12420 IBackupManager bm = IBackupManager.Stub.asInterface( 12421 ServiceManager.getService(Context.BACKUP_SERVICE)); 12422 if (bm != null) { 12423 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12424 + " to BM for possible restore"); 12425 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12426 try { 12427 // TODO: http://b/22388012 12428 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12429 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12430 } else { 12431 doRestore = false; 12432 } 12433 } catch (RemoteException e) { 12434 // can't happen; the backup manager is local 12435 } catch (Exception e) { 12436 Slog.e(TAG, "Exception trying to enqueue restore", e); 12437 doRestore = false; 12438 } 12439 } else { 12440 Slog.e(TAG, "Backup Manager not found!"); 12441 doRestore = false; 12442 } 12443 } 12444 12445 if (!doRestore) { 12446 // No restore possible, or the Backup Manager was mysteriously not 12447 // available -- just fire the post-install work request directly. 12448 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12449 12450 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12451 12452 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12453 mHandler.sendMessage(msg); 12454 } 12455 } 12456 }); 12457 } 12458 12459 /** 12460 * Callback from PackageSettings whenever an app is first transitioned out of the 12461 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12462 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12463 * here whether the app is the target of an ongoing install, and only send the 12464 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12465 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12466 * handling. 12467 */ 12468 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12469 // Serialize this with the rest of the install-process message chain. In the 12470 // restore-at-install case, this Runnable will necessarily run before the 12471 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12472 // are coherent. In the non-restore case, the app has already completed install 12473 // and been launched through some other means, so it is not in a problematic 12474 // state for observers to see the FIRST_LAUNCH signal. 12475 mHandler.post(new Runnable() { 12476 @Override 12477 public void run() { 12478 for (int i = 0; i < mRunningInstalls.size(); i++) { 12479 final PostInstallData data = mRunningInstalls.valueAt(i); 12480 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12481 // right package; but is it for the right user? 12482 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12483 if (userId == data.res.newUsers[uIndex]) { 12484 if (DEBUG_BACKUP) { 12485 Slog.i(TAG, "Package " + pkgName 12486 + " being restored so deferring FIRST_LAUNCH"); 12487 } 12488 return; 12489 } 12490 } 12491 } 12492 } 12493 // didn't find it, so not being restored 12494 if (DEBUG_BACKUP) { 12495 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12496 } 12497 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12498 } 12499 }); 12500 } 12501 12502 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12503 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12504 installerPkg, null, userIds); 12505 } 12506 12507 private abstract class HandlerParams { 12508 private static final int MAX_RETRIES = 4; 12509 12510 /** 12511 * Number of times startCopy() has been attempted and had a non-fatal 12512 * error. 12513 */ 12514 private int mRetries = 0; 12515 12516 /** User handle for the user requesting the information or installation. */ 12517 private final UserHandle mUser; 12518 String traceMethod; 12519 int traceCookie; 12520 12521 HandlerParams(UserHandle user) { 12522 mUser = user; 12523 } 12524 12525 UserHandle getUser() { 12526 return mUser; 12527 } 12528 12529 HandlerParams setTraceMethod(String traceMethod) { 12530 this.traceMethod = traceMethod; 12531 return this; 12532 } 12533 12534 HandlerParams setTraceCookie(int traceCookie) { 12535 this.traceCookie = traceCookie; 12536 return this; 12537 } 12538 12539 final boolean startCopy() { 12540 boolean res; 12541 try { 12542 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12543 12544 if (++mRetries > MAX_RETRIES) { 12545 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12546 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12547 handleServiceError(); 12548 return false; 12549 } else { 12550 handleStartCopy(); 12551 res = true; 12552 } 12553 } catch (RemoteException e) { 12554 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12555 mHandler.sendEmptyMessage(MCS_RECONNECT); 12556 res = false; 12557 } 12558 handleReturnCode(); 12559 return res; 12560 } 12561 12562 final void serviceError() { 12563 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12564 handleServiceError(); 12565 handleReturnCode(); 12566 } 12567 12568 abstract void handleStartCopy() throws RemoteException; 12569 abstract void handleServiceError(); 12570 abstract void handleReturnCode(); 12571 } 12572 12573 class MeasureParams extends HandlerParams { 12574 private final PackageStats mStats; 12575 private boolean mSuccess; 12576 12577 private final IPackageStatsObserver mObserver; 12578 12579 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12580 super(new UserHandle(stats.userHandle)); 12581 mObserver = observer; 12582 mStats = stats; 12583 } 12584 12585 @Override 12586 public String toString() { 12587 return "MeasureParams{" 12588 + Integer.toHexString(System.identityHashCode(this)) 12589 + " " + mStats.packageName + "}"; 12590 } 12591 12592 @Override 12593 void handleStartCopy() throws RemoteException { 12594 synchronized (mInstallLock) { 12595 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12596 } 12597 12598 if (mSuccess) { 12599 boolean mounted = false; 12600 try { 12601 final String status = Environment.getExternalStorageState(); 12602 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12603 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12604 } catch (Exception e) { 12605 } 12606 12607 if (mounted) { 12608 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12609 12610 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12611 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12612 12613 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12614 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12615 12616 // Always subtract cache size, since it's a subdirectory 12617 mStats.externalDataSize -= mStats.externalCacheSize; 12618 12619 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12620 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12621 12622 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12623 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12624 } 12625 } 12626 } 12627 12628 @Override 12629 void handleReturnCode() { 12630 if (mObserver != null) { 12631 try { 12632 mObserver.onGetStatsCompleted(mStats, mSuccess); 12633 } catch (RemoteException e) { 12634 Slog.i(TAG, "Observer no longer exists."); 12635 } 12636 } 12637 } 12638 12639 @Override 12640 void handleServiceError() { 12641 Slog.e(TAG, "Could not measure application " + mStats.packageName 12642 + " external storage"); 12643 } 12644 } 12645 12646 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12647 throws RemoteException { 12648 long result = 0; 12649 for (File path : paths) { 12650 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12651 } 12652 return result; 12653 } 12654 12655 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12656 for (File path : paths) { 12657 try { 12658 mcs.clearDirectory(path.getAbsolutePath()); 12659 } catch (RemoteException e) { 12660 } 12661 } 12662 } 12663 12664 static class OriginInfo { 12665 /** 12666 * Location where install is coming from, before it has been 12667 * copied/renamed into place. This could be a single monolithic APK 12668 * file, or a cluster directory. This location may be untrusted. 12669 */ 12670 final File file; 12671 final String cid; 12672 12673 /** 12674 * Flag indicating that {@link #file} or {@link #cid} has already been 12675 * staged, meaning downstream users don't need to defensively copy the 12676 * contents. 12677 */ 12678 final boolean staged; 12679 12680 /** 12681 * Flag indicating that {@link #file} or {@link #cid} is an already 12682 * installed app that is being moved. 12683 */ 12684 final boolean existing; 12685 12686 final String resolvedPath; 12687 final File resolvedFile; 12688 12689 static OriginInfo fromNothing() { 12690 return new OriginInfo(null, null, false, false); 12691 } 12692 12693 static OriginInfo fromUntrustedFile(File file) { 12694 return new OriginInfo(file, null, false, false); 12695 } 12696 12697 static OriginInfo fromExistingFile(File file) { 12698 return new OriginInfo(file, null, false, true); 12699 } 12700 12701 static OriginInfo fromStagedFile(File file) { 12702 return new OriginInfo(file, null, true, false); 12703 } 12704 12705 static OriginInfo fromStagedContainer(String cid) { 12706 return new OriginInfo(null, cid, true, false); 12707 } 12708 12709 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12710 this.file = file; 12711 this.cid = cid; 12712 this.staged = staged; 12713 this.existing = existing; 12714 12715 if (cid != null) { 12716 resolvedPath = PackageHelper.getSdDir(cid); 12717 resolvedFile = new File(resolvedPath); 12718 } else if (file != null) { 12719 resolvedPath = file.getAbsolutePath(); 12720 resolvedFile = file; 12721 } else { 12722 resolvedPath = null; 12723 resolvedFile = null; 12724 } 12725 } 12726 } 12727 12728 static class MoveInfo { 12729 final int moveId; 12730 final String fromUuid; 12731 final String toUuid; 12732 final String packageName; 12733 final String dataAppName; 12734 final int appId; 12735 final String seinfo; 12736 final int targetSdkVersion; 12737 12738 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12739 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12740 this.moveId = moveId; 12741 this.fromUuid = fromUuid; 12742 this.toUuid = toUuid; 12743 this.packageName = packageName; 12744 this.dataAppName = dataAppName; 12745 this.appId = appId; 12746 this.seinfo = seinfo; 12747 this.targetSdkVersion = targetSdkVersion; 12748 } 12749 } 12750 12751 static class VerificationInfo { 12752 /** A constant used to indicate that a uid value is not present. */ 12753 public static final int NO_UID = -1; 12754 12755 /** URI referencing where the package was downloaded from. */ 12756 final Uri originatingUri; 12757 12758 /** HTTP referrer URI associated with the originatingURI. */ 12759 final Uri referrer; 12760 12761 /** UID of the application that the install request originated from. */ 12762 final int originatingUid; 12763 12764 /** UID of application requesting the install */ 12765 final int installerUid; 12766 12767 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12768 this.originatingUri = originatingUri; 12769 this.referrer = referrer; 12770 this.originatingUid = originatingUid; 12771 this.installerUid = installerUid; 12772 } 12773 } 12774 12775 class InstallParams extends HandlerParams { 12776 final OriginInfo origin; 12777 final MoveInfo move; 12778 final IPackageInstallObserver2 observer; 12779 int installFlags; 12780 final String installerPackageName; 12781 final String volumeUuid; 12782 private InstallArgs mArgs; 12783 private int mRet; 12784 final String packageAbiOverride; 12785 final String[] grantedRuntimePermissions; 12786 final VerificationInfo verificationInfo; 12787 final Certificate[][] certificates; 12788 12789 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12790 int installFlags, String installerPackageName, String volumeUuid, 12791 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12792 String[] grantedPermissions, Certificate[][] certificates) { 12793 super(user); 12794 this.origin = origin; 12795 this.move = move; 12796 this.observer = observer; 12797 this.installFlags = installFlags; 12798 this.installerPackageName = installerPackageName; 12799 this.volumeUuid = volumeUuid; 12800 this.verificationInfo = verificationInfo; 12801 this.packageAbiOverride = packageAbiOverride; 12802 this.grantedRuntimePermissions = grantedPermissions; 12803 this.certificates = certificates; 12804 } 12805 12806 @Override 12807 public String toString() { 12808 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12809 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12810 } 12811 12812 private int installLocationPolicy(PackageInfoLite pkgLite) { 12813 String packageName = pkgLite.packageName; 12814 int installLocation = pkgLite.installLocation; 12815 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12816 // reader 12817 synchronized (mPackages) { 12818 // Currently installed package which the new package is attempting to replace or 12819 // null if no such package is installed. 12820 PackageParser.Package installedPkg = mPackages.get(packageName); 12821 // Package which currently owns the data which the new package will own if installed. 12822 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12823 // will be null whereas dataOwnerPkg will contain information about the package 12824 // which was uninstalled while keeping its data. 12825 PackageParser.Package dataOwnerPkg = installedPkg; 12826 if (dataOwnerPkg == null) { 12827 PackageSetting ps = mSettings.mPackages.get(packageName); 12828 if (ps != null) { 12829 dataOwnerPkg = ps.pkg; 12830 } 12831 } 12832 12833 if (dataOwnerPkg != null) { 12834 // If installed, the package will get access to data left on the device by its 12835 // predecessor. As a security measure, this is permited only if this is not a 12836 // version downgrade or if the predecessor package is marked as debuggable and 12837 // a downgrade is explicitly requested. 12838 // 12839 // On debuggable platform builds, downgrades are permitted even for 12840 // non-debuggable packages to make testing easier. Debuggable platform builds do 12841 // not offer security guarantees and thus it's OK to disable some security 12842 // mechanisms to make debugging/testing easier on those builds. However, even on 12843 // debuggable builds downgrades of packages are permitted only if requested via 12844 // installFlags. This is because we aim to keep the behavior of debuggable 12845 // platform builds as close as possible to the behavior of non-debuggable 12846 // platform builds. 12847 final boolean downgradeRequested = 12848 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12849 final boolean packageDebuggable = 12850 (dataOwnerPkg.applicationInfo.flags 12851 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12852 final boolean downgradePermitted = 12853 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12854 if (!downgradePermitted) { 12855 try { 12856 checkDowngrade(dataOwnerPkg, pkgLite); 12857 } catch (PackageManagerException e) { 12858 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12859 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12860 } 12861 } 12862 } 12863 12864 if (installedPkg != null) { 12865 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12866 // Check for updated system application. 12867 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12868 if (onSd) { 12869 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12870 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12871 } 12872 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12873 } else { 12874 if (onSd) { 12875 // Install flag overrides everything. 12876 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12877 } 12878 // If current upgrade specifies particular preference 12879 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12880 // Application explicitly specified internal. 12881 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12882 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12883 // App explictly prefers external. Let policy decide 12884 } else { 12885 // Prefer previous location 12886 if (isExternal(installedPkg)) { 12887 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12888 } 12889 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12890 } 12891 } 12892 } else { 12893 // Invalid install. Return error code 12894 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12895 } 12896 } 12897 } 12898 // All the special cases have been taken care of. 12899 // Return result based on recommended install location. 12900 if (onSd) { 12901 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12902 } 12903 return pkgLite.recommendedInstallLocation; 12904 } 12905 12906 /* 12907 * Invoke remote method to get package information and install 12908 * location values. Override install location based on default 12909 * policy if needed and then create install arguments based 12910 * on the install location. 12911 */ 12912 public void handleStartCopy() throws RemoteException { 12913 int ret = PackageManager.INSTALL_SUCCEEDED; 12914 12915 // If we're already staged, we've firmly committed to an install location 12916 if (origin.staged) { 12917 if (origin.file != null) { 12918 installFlags |= PackageManager.INSTALL_INTERNAL; 12919 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12920 } else if (origin.cid != null) { 12921 installFlags |= PackageManager.INSTALL_EXTERNAL; 12922 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12923 } else { 12924 throw new IllegalStateException("Invalid stage location"); 12925 } 12926 } 12927 12928 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12929 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12930 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12931 PackageInfoLite pkgLite = null; 12932 12933 if (onInt && onSd) { 12934 // Check if both bits are set. 12935 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12936 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12937 } else if (onSd && ephemeral) { 12938 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12939 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12940 } else { 12941 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12942 packageAbiOverride); 12943 12944 if (DEBUG_EPHEMERAL && ephemeral) { 12945 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12946 } 12947 12948 /* 12949 * If we have too little free space, try to free cache 12950 * before giving up. 12951 */ 12952 if (!origin.staged && pkgLite.recommendedInstallLocation 12953 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12954 // TODO: focus freeing disk space on the target device 12955 final StorageManager storage = StorageManager.from(mContext); 12956 final long lowThreshold = storage.getStorageLowBytes( 12957 Environment.getDataDirectory()); 12958 12959 final long sizeBytes = mContainerService.calculateInstalledSize( 12960 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12961 12962 try { 12963 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12964 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12965 installFlags, packageAbiOverride); 12966 } catch (InstallerException e) { 12967 Slog.w(TAG, "Failed to free cache", e); 12968 } 12969 12970 /* 12971 * The cache free must have deleted the file we 12972 * downloaded to install. 12973 * 12974 * TODO: fix the "freeCache" call to not delete 12975 * the file we care about. 12976 */ 12977 if (pkgLite.recommendedInstallLocation 12978 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12979 pkgLite.recommendedInstallLocation 12980 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12981 } 12982 } 12983 } 12984 12985 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12986 int loc = pkgLite.recommendedInstallLocation; 12987 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12988 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12989 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12990 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12991 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12992 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12993 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12994 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12995 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12996 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12997 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12998 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12999 } else { 13000 // Override with defaults if needed. 13001 loc = installLocationPolicy(pkgLite); 13002 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13003 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13004 } else if (!onSd && !onInt) { 13005 // Override install location with flags 13006 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13007 // Set the flag to install on external media. 13008 installFlags |= PackageManager.INSTALL_EXTERNAL; 13009 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13010 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13011 if (DEBUG_EPHEMERAL) { 13012 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13013 } 13014 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13015 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13016 |PackageManager.INSTALL_INTERNAL); 13017 } else { 13018 // Make sure the flag for installing on external 13019 // media is unset 13020 installFlags |= PackageManager.INSTALL_INTERNAL; 13021 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13022 } 13023 } 13024 } 13025 } 13026 13027 final InstallArgs args = createInstallArgs(this); 13028 mArgs = args; 13029 13030 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13031 // TODO: http://b/22976637 13032 // Apps installed for "all" users use the device owner to verify the app 13033 UserHandle verifierUser = getUser(); 13034 if (verifierUser == UserHandle.ALL) { 13035 verifierUser = UserHandle.SYSTEM; 13036 } 13037 13038 /* 13039 * Determine if we have any installed package verifiers. If we 13040 * do, then we'll defer to them to verify the packages. 13041 */ 13042 final int requiredUid = mRequiredVerifierPackage == null ? -1 13043 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13044 verifierUser.getIdentifier()); 13045 if (!origin.existing && requiredUid != -1 13046 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13047 final Intent verification = new Intent( 13048 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13049 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13050 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13051 PACKAGE_MIME_TYPE); 13052 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13053 13054 // Query all live verifiers based on current user state 13055 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13056 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13057 13058 if (DEBUG_VERIFY) { 13059 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13060 + verification.toString() + " with " + pkgLite.verifiers.length 13061 + " optional verifiers"); 13062 } 13063 13064 final int verificationId = mPendingVerificationToken++; 13065 13066 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13067 13068 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13069 installerPackageName); 13070 13071 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13072 installFlags); 13073 13074 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13075 pkgLite.packageName); 13076 13077 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13078 pkgLite.versionCode); 13079 13080 if (verificationInfo != null) { 13081 if (verificationInfo.originatingUri != null) { 13082 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13083 verificationInfo.originatingUri); 13084 } 13085 if (verificationInfo.referrer != null) { 13086 verification.putExtra(Intent.EXTRA_REFERRER, 13087 verificationInfo.referrer); 13088 } 13089 if (verificationInfo.originatingUid >= 0) { 13090 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13091 verificationInfo.originatingUid); 13092 } 13093 if (verificationInfo.installerUid >= 0) { 13094 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13095 verificationInfo.installerUid); 13096 } 13097 } 13098 13099 final PackageVerificationState verificationState = new PackageVerificationState( 13100 requiredUid, args); 13101 13102 mPendingVerification.append(verificationId, verificationState); 13103 13104 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13105 receivers, verificationState); 13106 13107 /* 13108 * If any sufficient verifiers were listed in the package 13109 * manifest, attempt to ask them. 13110 */ 13111 if (sufficientVerifiers != null) { 13112 final int N = sufficientVerifiers.size(); 13113 if (N == 0) { 13114 Slog.i(TAG, "Additional verifiers required, but none installed."); 13115 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13116 } else { 13117 for (int i = 0; i < N; i++) { 13118 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13119 13120 final Intent sufficientIntent = new Intent(verification); 13121 sufficientIntent.setComponent(verifierComponent); 13122 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13123 } 13124 } 13125 } 13126 13127 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13128 mRequiredVerifierPackage, receivers); 13129 if (ret == PackageManager.INSTALL_SUCCEEDED 13130 && mRequiredVerifierPackage != null) { 13131 Trace.asyncTraceBegin( 13132 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13133 /* 13134 * Send the intent to the required verification agent, 13135 * but only start the verification timeout after the 13136 * target BroadcastReceivers have run. 13137 */ 13138 verification.setComponent(requiredVerifierComponent); 13139 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13140 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13141 new BroadcastReceiver() { 13142 @Override 13143 public void onReceive(Context context, Intent intent) { 13144 final Message msg = mHandler 13145 .obtainMessage(CHECK_PENDING_VERIFICATION); 13146 msg.arg1 = verificationId; 13147 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13148 } 13149 }, null, 0, null, null); 13150 13151 /* 13152 * We don't want the copy to proceed until verification 13153 * succeeds, so null out this field. 13154 */ 13155 mArgs = null; 13156 } 13157 } else { 13158 /* 13159 * No package verification is enabled, so immediately start 13160 * the remote call to initiate copy using temporary file. 13161 */ 13162 ret = args.copyApk(mContainerService, true); 13163 } 13164 } 13165 13166 mRet = ret; 13167 } 13168 13169 @Override 13170 void handleReturnCode() { 13171 // If mArgs is null, then MCS couldn't be reached. When it 13172 // reconnects, it will try again to install. At that point, this 13173 // will succeed. 13174 if (mArgs != null) { 13175 processPendingInstall(mArgs, mRet); 13176 } 13177 } 13178 13179 @Override 13180 void handleServiceError() { 13181 mArgs = createInstallArgs(this); 13182 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13183 } 13184 13185 public boolean isForwardLocked() { 13186 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13187 } 13188 } 13189 13190 /** 13191 * Used during creation of InstallArgs 13192 * 13193 * @param installFlags package installation flags 13194 * @return true if should be installed on external storage 13195 */ 13196 private static boolean installOnExternalAsec(int installFlags) { 13197 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13198 return false; 13199 } 13200 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13201 return true; 13202 } 13203 return false; 13204 } 13205 13206 /** 13207 * Used during creation of InstallArgs 13208 * 13209 * @param installFlags package installation flags 13210 * @return true if should be installed as forward locked 13211 */ 13212 private static boolean installForwardLocked(int installFlags) { 13213 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13214 } 13215 13216 private InstallArgs createInstallArgs(InstallParams params) { 13217 if (params.move != null) { 13218 return new MoveInstallArgs(params); 13219 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13220 return new AsecInstallArgs(params); 13221 } else { 13222 return new FileInstallArgs(params); 13223 } 13224 } 13225 13226 /** 13227 * Create args that describe an existing installed package. Typically used 13228 * when cleaning up old installs, or used as a move source. 13229 */ 13230 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13231 String resourcePath, String[] instructionSets) { 13232 final boolean isInAsec; 13233 if (installOnExternalAsec(installFlags)) { 13234 /* Apps on SD card are always in ASEC containers. */ 13235 isInAsec = true; 13236 } else if (installForwardLocked(installFlags) 13237 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13238 /* 13239 * Forward-locked apps are only in ASEC containers if they're the 13240 * new style 13241 */ 13242 isInAsec = true; 13243 } else { 13244 isInAsec = false; 13245 } 13246 13247 if (isInAsec) { 13248 return new AsecInstallArgs(codePath, instructionSets, 13249 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13250 } else { 13251 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13252 } 13253 } 13254 13255 static abstract class InstallArgs { 13256 /** @see InstallParams#origin */ 13257 final OriginInfo origin; 13258 /** @see InstallParams#move */ 13259 final MoveInfo move; 13260 13261 final IPackageInstallObserver2 observer; 13262 // Always refers to PackageManager flags only 13263 final int installFlags; 13264 final String installerPackageName; 13265 final String volumeUuid; 13266 final UserHandle user; 13267 final String abiOverride; 13268 final String[] installGrantPermissions; 13269 /** If non-null, drop an async trace when the install completes */ 13270 final String traceMethod; 13271 final int traceCookie; 13272 final Certificate[][] certificates; 13273 13274 // The list of instruction sets supported by this app. This is currently 13275 // only used during the rmdex() phase to clean up resources. We can get rid of this 13276 // if we move dex files under the common app path. 13277 /* nullable */ String[] instructionSets; 13278 13279 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13280 int installFlags, String installerPackageName, String volumeUuid, 13281 UserHandle user, String[] instructionSets, 13282 String abiOverride, String[] installGrantPermissions, 13283 String traceMethod, int traceCookie, Certificate[][] certificates) { 13284 this.origin = origin; 13285 this.move = move; 13286 this.installFlags = installFlags; 13287 this.observer = observer; 13288 this.installerPackageName = installerPackageName; 13289 this.volumeUuid = volumeUuid; 13290 this.user = user; 13291 this.instructionSets = instructionSets; 13292 this.abiOverride = abiOverride; 13293 this.installGrantPermissions = installGrantPermissions; 13294 this.traceMethod = traceMethod; 13295 this.traceCookie = traceCookie; 13296 this.certificates = certificates; 13297 } 13298 13299 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13300 abstract int doPreInstall(int status); 13301 13302 /** 13303 * Rename package into final resting place. All paths on the given 13304 * scanned package should be updated to reflect the rename. 13305 */ 13306 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13307 abstract int doPostInstall(int status, int uid); 13308 13309 /** @see PackageSettingBase#codePathString */ 13310 abstract String getCodePath(); 13311 /** @see PackageSettingBase#resourcePathString */ 13312 abstract String getResourcePath(); 13313 13314 // Need installer lock especially for dex file removal. 13315 abstract void cleanUpResourcesLI(); 13316 abstract boolean doPostDeleteLI(boolean delete); 13317 13318 /** 13319 * Called before the source arguments are copied. This is used mostly 13320 * for MoveParams when it needs to read the source file to put it in the 13321 * destination. 13322 */ 13323 int doPreCopy() { 13324 return PackageManager.INSTALL_SUCCEEDED; 13325 } 13326 13327 /** 13328 * Called after the source arguments are copied. This is used mostly for 13329 * MoveParams when it needs to read the source file to put it in the 13330 * destination. 13331 */ 13332 int doPostCopy(int uid) { 13333 return PackageManager.INSTALL_SUCCEEDED; 13334 } 13335 13336 protected boolean isFwdLocked() { 13337 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13338 } 13339 13340 protected boolean isExternalAsec() { 13341 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13342 } 13343 13344 protected boolean isEphemeral() { 13345 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13346 } 13347 13348 UserHandle getUser() { 13349 return user; 13350 } 13351 } 13352 13353 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13354 if (!allCodePaths.isEmpty()) { 13355 if (instructionSets == null) { 13356 throw new IllegalStateException("instructionSet == null"); 13357 } 13358 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13359 for (String codePath : allCodePaths) { 13360 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13361 try { 13362 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13363 } catch (InstallerException ignored) { 13364 } 13365 } 13366 } 13367 } 13368 } 13369 13370 /** 13371 * Logic to handle installation of non-ASEC applications, including copying 13372 * and renaming logic. 13373 */ 13374 class FileInstallArgs extends InstallArgs { 13375 private File codeFile; 13376 private File resourceFile; 13377 13378 // Example topology: 13379 // /data/app/com.example/base.apk 13380 // /data/app/com.example/split_foo.apk 13381 // /data/app/com.example/lib/arm/libfoo.so 13382 // /data/app/com.example/lib/arm64/libfoo.so 13383 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13384 13385 /** New install */ 13386 FileInstallArgs(InstallParams params) { 13387 super(params.origin, params.move, params.observer, params.installFlags, 13388 params.installerPackageName, params.volumeUuid, 13389 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13390 params.grantedRuntimePermissions, 13391 params.traceMethod, params.traceCookie, params.certificates); 13392 if (isFwdLocked()) { 13393 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13394 } 13395 } 13396 13397 /** Existing install */ 13398 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13399 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13400 null, null, null, 0, null /*certificates*/); 13401 this.codeFile = (codePath != null) ? new File(codePath) : null; 13402 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13403 } 13404 13405 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13406 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13407 try { 13408 return doCopyApk(imcs, temp); 13409 } finally { 13410 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13411 } 13412 } 13413 13414 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13415 if (origin.staged) { 13416 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13417 codeFile = origin.file; 13418 resourceFile = origin.file; 13419 return PackageManager.INSTALL_SUCCEEDED; 13420 } 13421 13422 try { 13423 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13424 final File tempDir = 13425 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13426 codeFile = tempDir; 13427 resourceFile = tempDir; 13428 } catch (IOException e) { 13429 Slog.w(TAG, "Failed to create copy file: " + e); 13430 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13431 } 13432 13433 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13434 @Override 13435 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13436 if (!FileUtils.isValidExtFilename(name)) { 13437 throw new IllegalArgumentException("Invalid filename: " + name); 13438 } 13439 try { 13440 final File file = new File(codeFile, name); 13441 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13442 O_RDWR | O_CREAT, 0644); 13443 Os.chmod(file.getAbsolutePath(), 0644); 13444 return new ParcelFileDescriptor(fd); 13445 } catch (ErrnoException e) { 13446 throw new RemoteException("Failed to open: " + e.getMessage()); 13447 } 13448 } 13449 }; 13450 13451 int ret = PackageManager.INSTALL_SUCCEEDED; 13452 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13453 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13454 Slog.e(TAG, "Failed to copy package"); 13455 return ret; 13456 } 13457 13458 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13459 NativeLibraryHelper.Handle handle = null; 13460 try { 13461 handle = NativeLibraryHelper.Handle.create(codeFile); 13462 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13463 abiOverride); 13464 } catch (IOException e) { 13465 Slog.e(TAG, "Copying native libraries failed", e); 13466 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13467 } finally { 13468 IoUtils.closeQuietly(handle); 13469 } 13470 13471 return ret; 13472 } 13473 13474 int doPreInstall(int status) { 13475 if (status != PackageManager.INSTALL_SUCCEEDED) { 13476 cleanUp(); 13477 } 13478 return status; 13479 } 13480 13481 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13482 if (status != PackageManager.INSTALL_SUCCEEDED) { 13483 cleanUp(); 13484 return false; 13485 } 13486 13487 final File targetDir = codeFile.getParentFile(); 13488 final File beforeCodeFile = codeFile; 13489 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13490 13491 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13492 try { 13493 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13494 } catch (ErrnoException e) { 13495 Slog.w(TAG, "Failed to rename", e); 13496 return false; 13497 } 13498 13499 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13500 Slog.w(TAG, "Failed to restorecon"); 13501 return false; 13502 } 13503 13504 // Reflect the rename internally 13505 codeFile = afterCodeFile; 13506 resourceFile = afterCodeFile; 13507 13508 // Reflect the rename in scanned details 13509 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13510 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13511 afterCodeFile, pkg.baseCodePath)); 13512 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13513 afterCodeFile, pkg.splitCodePaths)); 13514 13515 // Reflect the rename in app info 13516 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13517 pkg.setApplicationInfoCodePath(pkg.codePath); 13518 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13519 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13520 pkg.setApplicationInfoResourcePath(pkg.codePath); 13521 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13522 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13523 13524 return true; 13525 } 13526 13527 int doPostInstall(int status, int uid) { 13528 if (status != PackageManager.INSTALL_SUCCEEDED) { 13529 cleanUp(); 13530 } 13531 return status; 13532 } 13533 13534 @Override 13535 String getCodePath() { 13536 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13537 } 13538 13539 @Override 13540 String getResourcePath() { 13541 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13542 } 13543 13544 private boolean cleanUp() { 13545 if (codeFile == null || !codeFile.exists()) { 13546 return false; 13547 } 13548 13549 removeCodePathLI(codeFile); 13550 13551 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13552 resourceFile.delete(); 13553 } 13554 13555 return true; 13556 } 13557 13558 void cleanUpResourcesLI() { 13559 // Try enumerating all code paths before deleting 13560 List<String> allCodePaths = Collections.EMPTY_LIST; 13561 if (codeFile != null && codeFile.exists()) { 13562 try { 13563 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13564 allCodePaths = pkg.getAllCodePaths(); 13565 } catch (PackageParserException e) { 13566 // Ignored; we tried our best 13567 } 13568 } 13569 13570 cleanUp(); 13571 removeDexFiles(allCodePaths, instructionSets); 13572 } 13573 13574 boolean doPostDeleteLI(boolean delete) { 13575 // XXX err, shouldn't we respect the delete flag? 13576 cleanUpResourcesLI(); 13577 return true; 13578 } 13579 } 13580 13581 private boolean isAsecExternal(String cid) { 13582 final String asecPath = PackageHelper.getSdFilesystem(cid); 13583 return !asecPath.startsWith(mAsecInternalPath); 13584 } 13585 13586 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13587 PackageManagerException { 13588 if (copyRet < 0) { 13589 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13590 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13591 throw new PackageManagerException(copyRet, message); 13592 } 13593 } 13594 } 13595 13596 /** 13597 * Extract the MountService "container ID" from the full code path of an 13598 * .apk. 13599 */ 13600 static String cidFromCodePath(String fullCodePath) { 13601 int eidx = fullCodePath.lastIndexOf("/"); 13602 String subStr1 = fullCodePath.substring(0, eidx); 13603 int sidx = subStr1.lastIndexOf("/"); 13604 return subStr1.substring(sidx+1, eidx); 13605 } 13606 13607 /** 13608 * Logic to handle installation of ASEC applications, including copying and 13609 * renaming logic. 13610 */ 13611 class AsecInstallArgs extends InstallArgs { 13612 static final String RES_FILE_NAME = "pkg.apk"; 13613 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13614 13615 String cid; 13616 String packagePath; 13617 String resourcePath; 13618 13619 /** New install */ 13620 AsecInstallArgs(InstallParams params) { 13621 super(params.origin, params.move, params.observer, params.installFlags, 13622 params.installerPackageName, params.volumeUuid, 13623 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13624 params.grantedRuntimePermissions, 13625 params.traceMethod, params.traceCookie, params.certificates); 13626 } 13627 13628 /** Existing install */ 13629 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13630 boolean isExternal, boolean isForwardLocked) { 13631 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13632 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13633 instructionSets, null, null, null, 0, null /*certificates*/); 13634 // Hackily pretend we're still looking at a full code path 13635 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13636 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13637 } 13638 13639 // Extract cid from fullCodePath 13640 int eidx = fullCodePath.lastIndexOf("/"); 13641 String subStr1 = fullCodePath.substring(0, eidx); 13642 int sidx = subStr1.lastIndexOf("/"); 13643 cid = subStr1.substring(sidx+1, eidx); 13644 setMountPath(subStr1); 13645 } 13646 13647 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13648 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13649 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13650 instructionSets, null, null, null, 0, null /*certificates*/); 13651 this.cid = cid; 13652 setMountPath(PackageHelper.getSdDir(cid)); 13653 } 13654 13655 void createCopyFile() { 13656 cid = mInstallerService.allocateExternalStageCidLegacy(); 13657 } 13658 13659 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13660 if (origin.staged && origin.cid != null) { 13661 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13662 cid = origin.cid; 13663 setMountPath(PackageHelper.getSdDir(cid)); 13664 return PackageManager.INSTALL_SUCCEEDED; 13665 } 13666 13667 if (temp) { 13668 createCopyFile(); 13669 } else { 13670 /* 13671 * Pre-emptively destroy the container since it's destroyed if 13672 * copying fails due to it existing anyway. 13673 */ 13674 PackageHelper.destroySdDir(cid); 13675 } 13676 13677 final String newMountPath = imcs.copyPackageToContainer( 13678 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13679 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13680 13681 if (newMountPath != null) { 13682 setMountPath(newMountPath); 13683 return PackageManager.INSTALL_SUCCEEDED; 13684 } else { 13685 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13686 } 13687 } 13688 13689 @Override 13690 String getCodePath() { 13691 return packagePath; 13692 } 13693 13694 @Override 13695 String getResourcePath() { 13696 return resourcePath; 13697 } 13698 13699 int doPreInstall(int status) { 13700 if (status != PackageManager.INSTALL_SUCCEEDED) { 13701 // Destroy container 13702 PackageHelper.destroySdDir(cid); 13703 } else { 13704 boolean mounted = PackageHelper.isContainerMounted(cid); 13705 if (!mounted) { 13706 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13707 Process.SYSTEM_UID); 13708 if (newMountPath != null) { 13709 setMountPath(newMountPath); 13710 } else { 13711 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13712 } 13713 } 13714 } 13715 return status; 13716 } 13717 13718 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13719 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13720 String newMountPath = null; 13721 if (PackageHelper.isContainerMounted(cid)) { 13722 // Unmount the container 13723 if (!PackageHelper.unMountSdDir(cid)) { 13724 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13725 return false; 13726 } 13727 } 13728 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13729 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13730 " which might be stale. Will try to clean up."); 13731 // Clean up the stale container and proceed to recreate. 13732 if (!PackageHelper.destroySdDir(newCacheId)) { 13733 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13734 return false; 13735 } 13736 // Successfully cleaned up stale container. Try to rename again. 13737 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13738 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13739 + " inspite of cleaning it up."); 13740 return false; 13741 } 13742 } 13743 if (!PackageHelper.isContainerMounted(newCacheId)) { 13744 Slog.w(TAG, "Mounting container " + newCacheId); 13745 newMountPath = PackageHelper.mountSdDir(newCacheId, 13746 getEncryptKey(), Process.SYSTEM_UID); 13747 } else { 13748 newMountPath = PackageHelper.getSdDir(newCacheId); 13749 } 13750 if (newMountPath == null) { 13751 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13752 return false; 13753 } 13754 Log.i(TAG, "Succesfully renamed " + cid + 13755 " to " + newCacheId + 13756 " at new path: " + newMountPath); 13757 cid = newCacheId; 13758 13759 final File beforeCodeFile = new File(packagePath); 13760 setMountPath(newMountPath); 13761 final File afterCodeFile = new File(packagePath); 13762 13763 // Reflect the rename in scanned details 13764 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13765 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13766 afterCodeFile, pkg.baseCodePath)); 13767 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13768 afterCodeFile, pkg.splitCodePaths)); 13769 13770 // Reflect the rename in app info 13771 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13772 pkg.setApplicationInfoCodePath(pkg.codePath); 13773 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13774 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13775 pkg.setApplicationInfoResourcePath(pkg.codePath); 13776 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13777 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13778 13779 return true; 13780 } 13781 13782 private void setMountPath(String mountPath) { 13783 final File mountFile = new File(mountPath); 13784 13785 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13786 if (monolithicFile.exists()) { 13787 packagePath = monolithicFile.getAbsolutePath(); 13788 if (isFwdLocked()) { 13789 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13790 } else { 13791 resourcePath = packagePath; 13792 } 13793 } else { 13794 packagePath = mountFile.getAbsolutePath(); 13795 resourcePath = packagePath; 13796 } 13797 } 13798 13799 int doPostInstall(int status, int uid) { 13800 if (status != PackageManager.INSTALL_SUCCEEDED) { 13801 cleanUp(); 13802 } else { 13803 final int groupOwner; 13804 final String protectedFile; 13805 if (isFwdLocked()) { 13806 groupOwner = UserHandle.getSharedAppGid(uid); 13807 protectedFile = RES_FILE_NAME; 13808 } else { 13809 groupOwner = -1; 13810 protectedFile = null; 13811 } 13812 13813 if (uid < Process.FIRST_APPLICATION_UID 13814 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13815 Slog.e(TAG, "Failed to finalize " + cid); 13816 PackageHelper.destroySdDir(cid); 13817 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13818 } 13819 13820 boolean mounted = PackageHelper.isContainerMounted(cid); 13821 if (!mounted) { 13822 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13823 } 13824 } 13825 return status; 13826 } 13827 13828 private void cleanUp() { 13829 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13830 13831 // Destroy secure container 13832 PackageHelper.destroySdDir(cid); 13833 } 13834 13835 private List<String> getAllCodePaths() { 13836 final File codeFile = new File(getCodePath()); 13837 if (codeFile != null && codeFile.exists()) { 13838 try { 13839 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13840 return pkg.getAllCodePaths(); 13841 } catch (PackageParserException e) { 13842 // Ignored; we tried our best 13843 } 13844 } 13845 return Collections.EMPTY_LIST; 13846 } 13847 13848 void cleanUpResourcesLI() { 13849 // Enumerate all code paths before deleting 13850 cleanUpResourcesLI(getAllCodePaths()); 13851 } 13852 13853 private void cleanUpResourcesLI(List<String> allCodePaths) { 13854 cleanUp(); 13855 removeDexFiles(allCodePaths, instructionSets); 13856 } 13857 13858 String getPackageName() { 13859 return getAsecPackageName(cid); 13860 } 13861 13862 boolean doPostDeleteLI(boolean delete) { 13863 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13864 final List<String> allCodePaths = getAllCodePaths(); 13865 boolean mounted = PackageHelper.isContainerMounted(cid); 13866 if (mounted) { 13867 // Unmount first 13868 if (PackageHelper.unMountSdDir(cid)) { 13869 mounted = false; 13870 } 13871 } 13872 if (!mounted && delete) { 13873 cleanUpResourcesLI(allCodePaths); 13874 } 13875 return !mounted; 13876 } 13877 13878 @Override 13879 int doPreCopy() { 13880 if (isFwdLocked()) { 13881 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13882 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13883 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13884 } 13885 } 13886 13887 return PackageManager.INSTALL_SUCCEEDED; 13888 } 13889 13890 @Override 13891 int doPostCopy(int uid) { 13892 if (isFwdLocked()) { 13893 if (uid < Process.FIRST_APPLICATION_UID 13894 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13895 RES_FILE_NAME)) { 13896 Slog.e(TAG, "Failed to finalize " + cid); 13897 PackageHelper.destroySdDir(cid); 13898 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13899 } 13900 } 13901 13902 return PackageManager.INSTALL_SUCCEEDED; 13903 } 13904 } 13905 13906 /** 13907 * Logic to handle movement of existing installed applications. 13908 */ 13909 class MoveInstallArgs extends InstallArgs { 13910 private File codeFile; 13911 private File resourceFile; 13912 13913 /** New install */ 13914 MoveInstallArgs(InstallParams params) { 13915 super(params.origin, params.move, params.observer, params.installFlags, 13916 params.installerPackageName, params.volumeUuid, 13917 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13918 params.grantedRuntimePermissions, 13919 params.traceMethod, params.traceCookie, params.certificates); 13920 } 13921 13922 int copyApk(IMediaContainerService imcs, boolean temp) { 13923 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13924 + move.fromUuid + " to " + move.toUuid); 13925 synchronized (mInstaller) { 13926 try { 13927 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13928 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13929 } catch (InstallerException e) { 13930 Slog.w(TAG, "Failed to move app", e); 13931 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13932 } 13933 } 13934 13935 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13936 resourceFile = codeFile; 13937 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13938 13939 return PackageManager.INSTALL_SUCCEEDED; 13940 } 13941 13942 int doPreInstall(int status) { 13943 if (status != PackageManager.INSTALL_SUCCEEDED) { 13944 cleanUp(move.toUuid); 13945 } 13946 return status; 13947 } 13948 13949 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13950 if (status != PackageManager.INSTALL_SUCCEEDED) { 13951 cleanUp(move.toUuid); 13952 return false; 13953 } 13954 13955 // Reflect the move in app info 13956 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13957 pkg.setApplicationInfoCodePath(pkg.codePath); 13958 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13959 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13960 pkg.setApplicationInfoResourcePath(pkg.codePath); 13961 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13962 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13963 13964 return true; 13965 } 13966 13967 int doPostInstall(int status, int uid) { 13968 if (status == PackageManager.INSTALL_SUCCEEDED) { 13969 cleanUp(move.fromUuid); 13970 } else { 13971 cleanUp(move.toUuid); 13972 } 13973 return status; 13974 } 13975 13976 @Override 13977 String getCodePath() { 13978 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13979 } 13980 13981 @Override 13982 String getResourcePath() { 13983 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13984 } 13985 13986 private boolean cleanUp(String volumeUuid) { 13987 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13988 move.dataAppName); 13989 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13990 final int[] userIds = sUserManager.getUserIds(); 13991 synchronized (mInstallLock) { 13992 // Clean up both app data and code 13993 // All package moves are frozen until finished 13994 for (int userId : userIds) { 13995 try { 13996 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13997 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13998 } catch (InstallerException e) { 13999 Slog.w(TAG, String.valueOf(e)); 14000 } 14001 } 14002 removeCodePathLI(codeFile); 14003 } 14004 return true; 14005 } 14006 14007 void cleanUpResourcesLI() { 14008 throw new UnsupportedOperationException(); 14009 } 14010 14011 boolean doPostDeleteLI(boolean delete) { 14012 throw new UnsupportedOperationException(); 14013 } 14014 } 14015 14016 static String getAsecPackageName(String packageCid) { 14017 int idx = packageCid.lastIndexOf("-"); 14018 if (idx == -1) { 14019 return packageCid; 14020 } 14021 return packageCid.substring(0, idx); 14022 } 14023 14024 // Utility method used to create code paths based on package name and available index. 14025 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14026 String idxStr = ""; 14027 int idx = 1; 14028 // Fall back to default value of idx=1 if prefix is not 14029 // part of oldCodePath 14030 if (oldCodePath != null) { 14031 String subStr = oldCodePath; 14032 // Drop the suffix right away 14033 if (suffix != null && subStr.endsWith(suffix)) { 14034 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14035 } 14036 // If oldCodePath already contains prefix find out the 14037 // ending index to either increment or decrement. 14038 int sidx = subStr.lastIndexOf(prefix); 14039 if (sidx != -1) { 14040 subStr = subStr.substring(sidx + prefix.length()); 14041 if (subStr != null) { 14042 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14043 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14044 } 14045 try { 14046 idx = Integer.parseInt(subStr); 14047 if (idx <= 1) { 14048 idx++; 14049 } else { 14050 idx--; 14051 } 14052 } catch(NumberFormatException e) { 14053 } 14054 } 14055 } 14056 } 14057 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14058 return prefix + idxStr; 14059 } 14060 14061 private File getNextCodePath(File targetDir, String packageName) { 14062 int suffix = 1; 14063 File result; 14064 do { 14065 result = new File(targetDir, packageName + "-" + suffix); 14066 suffix++; 14067 } while (result.exists()); 14068 return result; 14069 } 14070 14071 // Utility method that returns the relative package path with respect 14072 // to the installation directory. Like say for /data/data/com.test-1.apk 14073 // string com.test-1 is returned. 14074 static String deriveCodePathName(String codePath) { 14075 if (codePath == null) { 14076 return null; 14077 } 14078 final File codeFile = new File(codePath); 14079 final String name = codeFile.getName(); 14080 if (codeFile.isDirectory()) { 14081 return name; 14082 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14083 final int lastDot = name.lastIndexOf('.'); 14084 return name.substring(0, lastDot); 14085 } else { 14086 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14087 return null; 14088 } 14089 } 14090 14091 static class PackageInstalledInfo { 14092 String name; 14093 int uid; 14094 // The set of users that originally had this package installed. 14095 int[] origUsers; 14096 // The set of users that now have this package installed. 14097 int[] newUsers; 14098 PackageParser.Package pkg; 14099 int returnCode; 14100 String returnMsg; 14101 PackageRemovedInfo removedInfo; 14102 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14103 14104 public void setError(int code, String msg) { 14105 setReturnCode(code); 14106 setReturnMessage(msg); 14107 Slog.w(TAG, msg); 14108 } 14109 14110 public void setError(String msg, PackageParserException e) { 14111 setReturnCode(e.error); 14112 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14113 Slog.w(TAG, msg, e); 14114 } 14115 14116 public void setError(String msg, PackageManagerException e) { 14117 returnCode = e.error; 14118 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14119 Slog.w(TAG, msg, e); 14120 } 14121 14122 public void setReturnCode(int returnCode) { 14123 this.returnCode = returnCode; 14124 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14125 for (int i = 0; i < childCount; i++) { 14126 addedChildPackages.valueAt(i).returnCode = returnCode; 14127 } 14128 } 14129 14130 private void setReturnMessage(String returnMsg) { 14131 this.returnMsg = returnMsg; 14132 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14133 for (int i = 0; i < childCount; i++) { 14134 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14135 } 14136 } 14137 14138 // In some error cases we want to convey more info back to the observer 14139 String origPackage; 14140 String origPermission; 14141 } 14142 14143 /* 14144 * Install a non-existing package. 14145 */ 14146 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14147 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14148 PackageInstalledInfo res) { 14149 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14150 14151 // Remember this for later, in case we need to rollback this install 14152 String pkgName = pkg.packageName; 14153 14154 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14155 14156 synchronized(mPackages) { 14157 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14158 // A package with the same name is already installed, though 14159 // it has been renamed to an older name. The package we 14160 // are trying to install should be installed as an update to 14161 // the existing one, but that has not been requested, so bail. 14162 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14163 + " without first uninstalling package running as " 14164 + mSettings.mRenamedPackages.get(pkgName)); 14165 return; 14166 } 14167 if (mPackages.containsKey(pkgName)) { 14168 // Don't allow installation over an existing package with the same name. 14169 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14170 + " without first uninstalling."); 14171 return; 14172 } 14173 } 14174 14175 try { 14176 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14177 System.currentTimeMillis(), user); 14178 14179 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14180 14181 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14182 prepareAppDataAfterInstallLIF(newPackage); 14183 14184 } else { 14185 // Remove package from internal structures, but keep around any 14186 // data that might have already existed 14187 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14188 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14189 } 14190 } catch (PackageManagerException e) { 14191 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14192 } 14193 14194 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14195 } 14196 14197 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14198 // Can't rotate keys during boot or if sharedUser. 14199 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14200 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14201 return false; 14202 } 14203 // app is using upgradeKeySets; make sure all are valid 14204 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14205 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14206 for (int i = 0; i < upgradeKeySets.length; i++) { 14207 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14208 Slog.wtf(TAG, "Package " 14209 + (oldPs.name != null ? oldPs.name : "<null>") 14210 + " contains upgrade-key-set reference to unknown key-set: " 14211 + upgradeKeySets[i] 14212 + " reverting to signatures check."); 14213 return false; 14214 } 14215 } 14216 return true; 14217 } 14218 14219 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14220 // Upgrade keysets are being used. Determine if new package has a superset of the 14221 // required keys. 14222 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14223 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14224 for (int i = 0; i < upgradeKeySets.length; i++) { 14225 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14226 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14227 return true; 14228 } 14229 } 14230 return false; 14231 } 14232 14233 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14234 try (DigestInputStream digestStream = 14235 new DigestInputStream(new FileInputStream(file), digest)) { 14236 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14237 } 14238 } 14239 14240 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14241 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14242 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14243 14244 final PackageParser.Package oldPackage; 14245 final String pkgName = pkg.packageName; 14246 final int[] allUsers; 14247 final int[] installedUsers; 14248 14249 synchronized(mPackages) { 14250 oldPackage = mPackages.get(pkgName); 14251 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14252 14253 // don't allow upgrade to target a release SDK from a pre-release SDK 14254 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14255 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14256 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14257 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14258 if (oldTargetsPreRelease 14259 && !newTargetsPreRelease 14260 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14261 Slog.w(TAG, "Can't install package targeting released sdk"); 14262 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14263 return; 14264 } 14265 14266 // don't allow an upgrade from full to ephemeral 14267 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14268 if (isEphemeral && !oldIsEphemeral) { 14269 // can't downgrade from full to ephemeral 14270 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14271 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14272 return; 14273 } 14274 14275 // verify signatures are valid 14276 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14277 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14278 if (!checkUpgradeKeySetLP(ps, pkg)) { 14279 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14280 "New package not signed by keys specified by upgrade-keysets: " 14281 + pkgName); 14282 return; 14283 } 14284 } else { 14285 // default to original signature matching 14286 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14287 != PackageManager.SIGNATURE_MATCH) { 14288 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14289 "New package has a different signature: " + pkgName); 14290 return; 14291 } 14292 } 14293 14294 // don't allow a system upgrade unless the upgrade hash matches 14295 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14296 byte[] digestBytes = null; 14297 try { 14298 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14299 updateDigest(digest, new File(pkg.baseCodePath)); 14300 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14301 for (String path : pkg.splitCodePaths) { 14302 updateDigest(digest, new File(path)); 14303 } 14304 } 14305 digestBytes = digest.digest(); 14306 } catch (NoSuchAlgorithmException | IOException e) { 14307 res.setError(INSTALL_FAILED_INVALID_APK, 14308 "Could not compute hash: " + pkgName); 14309 return; 14310 } 14311 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14312 res.setError(INSTALL_FAILED_INVALID_APK, 14313 "New package fails restrict-update check: " + pkgName); 14314 return; 14315 } 14316 // retain upgrade restriction 14317 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14318 } 14319 14320 // Check for shared user id changes 14321 String invalidPackageName = 14322 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14323 if (invalidPackageName != null) { 14324 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14325 "Package " + invalidPackageName + " tried to change user " 14326 + oldPackage.mSharedUserId); 14327 return; 14328 } 14329 14330 // In case of rollback, remember per-user/profile install state 14331 allUsers = sUserManager.getUserIds(); 14332 installedUsers = ps.queryInstalledUsers(allUsers, true); 14333 } 14334 14335 // Update what is removed 14336 res.removedInfo = new PackageRemovedInfo(); 14337 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14338 res.removedInfo.removedPackage = oldPackage.packageName; 14339 res.removedInfo.isUpdate = true; 14340 res.removedInfo.origUsers = installedUsers; 14341 final int childCount = (oldPackage.childPackages != null) 14342 ? oldPackage.childPackages.size() : 0; 14343 for (int i = 0; i < childCount; i++) { 14344 boolean childPackageUpdated = false; 14345 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14346 if (res.addedChildPackages != null) { 14347 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14348 if (childRes != null) { 14349 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14350 childRes.removedInfo.removedPackage = childPkg.packageName; 14351 childRes.removedInfo.isUpdate = true; 14352 childPackageUpdated = true; 14353 } 14354 } 14355 if (!childPackageUpdated) { 14356 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14357 childRemovedRes.removedPackage = childPkg.packageName; 14358 childRemovedRes.isUpdate = false; 14359 childRemovedRes.dataRemoved = true; 14360 synchronized (mPackages) { 14361 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14362 if (childPs != null) { 14363 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14364 } 14365 } 14366 if (res.removedInfo.removedChildPackages == null) { 14367 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14368 } 14369 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14370 } 14371 } 14372 14373 boolean sysPkg = (isSystemApp(oldPackage)); 14374 if (sysPkg) { 14375 // Set the system/privileged flags as needed 14376 final boolean privileged = 14377 (oldPackage.applicationInfo.privateFlags 14378 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14379 final int systemPolicyFlags = policyFlags 14380 | PackageParser.PARSE_IS_SYSTEM 14381 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14382 14383 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14384 user, allUsers, installerPackageName, res); 14385 } else { 14386 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14387 user, allUsers, installerPackageName, res); 14388 } 14389 } 14390 14391 public List<String> getPreviousCodePaths(String packageName) { 14392 final PackageSetting ps = mSettings.mPackages.get(packageName); 14393 final List<String> result = new ArrayList<String>(); 14394 if (ps != null && ps.oldCodePaths != null) { 14395 result.addAll(ps.oldCodePaths); 14396 } 14397 return result; 14398 } 14399 14400 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14401 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14402 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14403 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14404 + deletedPackage); 14405 14406 String pkgName = deletedPackage.packageName; 14407 boolean deletedPkg = true; 14408 boolean addedPkg = false; 14409 boolean updatedSettings = false; 14410 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14411 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14412 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14413 14414 final long origUpdateTime = (pkg.mExtras != null) 14415 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14416 14417 // First delete the existing package while retaining the data directory 14418 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14419 res.removedInfo, true, pkg)) { 14420 // If the existing package wasn't successfully deleted 14421 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14422 deletedPkg = false; 14423 } else { 14424 // Successfully deleted the old package; proceed with replace. 14425 14426 // If deleted package lived in a container, give users a chance to 14427 // relinquish resources before killing. 14428 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14429 if (DEBUG_INSTALL) { 14430 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14431 } 14432 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14433 final ArrayList<String> pkgList = new ArrayList<String>(1); 14434 pkgList.add(deletedPackage.applicationInfo.packageName); 14435 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14436 } 14437 14438 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14439 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14440 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14441 14442 try { 14443 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14444 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14445 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14446 14447 // Update the in-memory copy of the previous code paths. 14448 PackageSetting ps = mSettings.mPackages.get(pkgName); 14449 if (!killApp) { 14450 if (ps.oldCodePaths == null) { 14451 ps.oldCodePaths = new ArraySet<>(); 14452 } 14453 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14454 if (deletedPackage.splitCodePaths != null) { 14455 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14456 } 14457 } else { 14458 ps.oldCodePaths = null; 14459 } 14460 if (ps.childPackageNames != null) { 14461 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14462 final String childPkgName = ps.childPackageNames.get(i); 14463 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14464 childPs.oldCodePaths = ps.oldCodePaths; 14465 } 14466 } 14467 prepareAppDataAfterInstallLIF(newPackage); 14468 addedPkg = true; 14469 } catch (PackageManagerException e) { 14470 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14471 } 14472 } 14473 14474 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14475 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14476 14477 // Revert all internal state mutations and added folders for the failed install 14478 if (addedPkg) { 14479 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14480 res.removedInfo, true, null); 14481 } 14482 14483 // Restore the old package 14484 if (deletedPkg) { 14485 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14486 File restoreFile = new File(deletedPackage.codePath); 14487 // Parse old package 14488 boolean oldExternal = isExternal(deletedPackage); 14489 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14490 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14491 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14492 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14493 try { 14494 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14495 null); 14496 } catch (PackageManagerException e) { 14497 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14498 + e.getMessage()); 14499 return; 14500 } 14501 14502 synchronized (mPackages) { 14503 // Ensure the installer package name up to date 14504 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14505 14506 // Update permissions for restored package 14507 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14508 14509 mSettings.writeLPr(); 14510 } 14511 14512 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14513 } 14514 } else { 14515 synchronized (mPackages) { 14516 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14517 if (ps != null) { 14518 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14519 if (res.removedInfo.removedChildPackages != null) { 14520 final int childCount = res.removedInfo.removedChildPackages.size(); 14521 // Iterate in reverse as we may modify the collection 14522 for (int i = childCount - 1; i >= 0; i--) { 14523 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14524 if (res.addedChildPackages.containsKey(childPackageName)) { 14525 res.removedInfo.removedChildPackages.removeAt(i); 14526 } else { 14527 PackageRemovedInfo childInfo = res.removedInfo 14528 .removedChildPackages.valueAt(i); 14529 childInfo.removedForAllUsers = mPackages.get( 14530 childInfo.removedPackage) == null; 14531 } 14532 } 14533 } 14534 } 14535 } 14536 } 14537 } 14538 14539 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14540 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14541 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14542 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14543 + ", old=" + deletedPackage); 14544 14545 final boolean disabledSystem; 14546 14547 // Remove existing system package 14548 removePackageLI(deletedPackage, true); 14549 14550 synchronized (mPackages) { 14551 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14552 } 14553 if (!disabledSystem) { 14554 // We didn't need to disable the .apk as a current system package, 14555 // which means we are replacing another update that is already 14556 // installed. We need to make sure to delete the older one's .apk. 14557 res.removedInfo.args = createInstallArgsForExisting(0, 14558 deletedPackage.applicationInfo.getCodePath(), 14559 deletedPackage.applicationInfo.getResourcePath(), 14560 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14561 } else { 14562 res.removedInfo.args = null; 14563 } 14564 14565 // Successfully disabled the old package. Now proceed with re-installation 14566 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14567 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14568 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14569 14570 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14571 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14572 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14573 14574 PackageParser.Package newPackage = null; 14575 try { 14576 // Add the package to the internal data structures 14577 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14578 14579 // Set the update and install times 14580 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14581 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14582 System.currentTimeMillis()); 14583 14584 // Update the package dynamic state if succeeded 14585 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14586 // Now that the install succeeded make sure we remove data 14587 // directories for any child package the update removed. 14588 final int deletedChildCount = (deletedPackage.childPackages != null) 14589 ? deletedPackage.childPackages.size() : 0; 14590 final int newChildCount = (newPackage.childPackages != null) 14591 ? newPackage.childPackages.size() : 0; 14592 for (int i = 0; i < deletedChildCount; i++) { 14593 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14594 boolean childPackageDeleted = true; 14595 for (int j = 0; j < newChildCount; j++) { 14596 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14597 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14598 childPackageDeleted = false; 14599 break; 14600 } 14601 } 14602 if (childPackageDeleted) { 14603 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14604 deletedChildPkg.packageName); 14605 if (ps != null && res.removedInfo.removedChildPackages != null) { 14606 PackageRemovedInfo removedChildRes = res.removedInfo 14607 .removedChildPackages.get(deletedChildPkg.packageName); 14608 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14609 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14610 } 14611 } 14612 } 14613 14614 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14615 prepareAppDataAfterInstallLIF(newPackage); 14616 } 14617 } catch (PackageManagerException e) { 14618 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14619 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14620 } 14621 14622 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14623 // Re installation failed. Restore old information 14624 // Remove new pkg information 14625 if (newPackage != null) { 14626 removeInstalledPackageLI(newPackage, true); 14627 } 14628 // Add back the old system package 14629 try { 14630 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14631 } catch (PackageManagerException e) { 14632 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14633 } 14634 14635 synchronized (mPackages) { 14636 if (disabledSystem) { 14637 enableSystemPackageLPw(deletedPackage); 14638 } 14639 14640 // Ensure the installer package name up to date 14641 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14642 14643 // Update permissions for restored package 14644 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14645 14646 mSettings.writeLPr(); 14647 } 14648 14649 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14650 + " after failed upgrade"); 14651 } 14652 } 14653 14654 /** 14655 * Checks whether the parent or any of the child packages have a change shared 14656 * user. For a package to be a valid update the shred users of the parent and 14657 * the children should match. We may later support changing child shared users. 14658 * @param oldPkg The updated package. 14659 * @param newPkg The update package. 14660 * @return The shared user that change between the versions. 14661 */ 14662 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14663 PackageParser.Package newPkg) { 14664 // Check parent shared user 14665 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14666 return newPkg.packageName; 14667 } 14668 // Check child shared users 14669 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14670 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14671 for (int i = 0; i < newChildCount; i++) { 14672 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14673 // If this child was present, did it have the same shared user? 14674 for (int j = 0; j < oldChildCount; j++) { 14675 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14676 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14677 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14678 return newChildPkg.packageName; 14679 } 14680 } 14681 } 14682 return null; 14683 } 14684 14685 private void removeNativeBinariesLI(PackageSetting ps) { 14686 // Remove the lib path for the parent package 14687 if (ps != null) { 14688 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14689 // Remove the lib path for the child packages 14690 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14691 for (int i = 0; i < childCount; i++) { 14692 PackageSetting childPs = null; 14693 synchronized (mPackages) { 14694 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14695 } 14696 if (childPs != null) { 14697 NativeLibraryHelper.removeNativeBinariesLI(childPs 14698 .legacyNativeLibraryPathString); 14699 } 14700 } 14701 } 14702 } 14703 14704 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14705 // Enable the parent package 14706 mSettings.enableSystemPackageLPw(pkg.packageName); 14707 // Enable the child packages 14708 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14709 for (int i = 0; i < childCount; i++) { 14710 PackageParser.Package childPkg = pkg.childPackages.get(i); 14711 mSettings.enableSystemPackageLPw(childPkg.packageName); 14712 } 14713 } 14714 14715 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14716 PackageParser.Package newPkg) { 14717 // Disable the parent package (parent always replaced) 14718 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14719 // Disable the child packages 14720 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14721 for (int i = 0; i < childCount; i++) { 14722 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14723 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14724 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14725 } 14726 return disabled; 14727 } 14728 14729 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14730 String installerPackageName) { 14731 // Enable the parent package 14732 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14733 // Enable the child packages 14734 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14735 for (int i = 0; i < childCount; i++) { 14736 PackageParser.Package childPkg = pkg.childPackages.get(i); 14737 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14738 } 14739 } 14740 14741 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14742 // Collect all used permissions in the UID 14743 ArraySet<String> usedPermissions = new ArraySet<>(); 14744 final int packageCount = su.packages.size(); 14745 for (int i = 0; i < packageCount; i++) { 14746 PackageSetting ps = su.packages.valueAt(i); 14747 if (ps.pkg == null) { 14748 continue; 14749 } 14750 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14751 for (int j = 0; j < requestedPermCount; j++) { 14752 String permission = ps.pkg.requestedPermissions.get(j); 14753 BasePermission bp = mSettings.mPermissions.get(permission); 14754 if (bp != null) { 14755 usedPermissions.add(permission); 14756 } 14757 } 14758 } 14759 14760 PermissionsState permissionsState = su.getPermissionsState(); 14761 // Prune install permissions 14762 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14763 final int installPermCount = installPermStates.size(); 14764 for (int i = installPermCount - 1; i >= 0; i--) { 14765 PermissionState permissionState = installPermStates.get(i); 14766 if (!usedPermissions.contains(permissionState.getName())) { 14767 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14768 if (bp != null) { 14769 permissionsState.revokeInstallPermission(bp); 14770 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14771 PackageManager.MASK_PERMISSION_FLAGS, 0); 14772 } 14773 } 14774 } 14775 14776 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14777 14778 // Prune runtime permissions 14779 for (int userId : allUserIds) { 14780 List<PermissionState> runtimePermStates = permissionsState 14781 .getRuntimePermissionStates(userId); 14782 final int runtimePermCount = runtimePermStates.size(); 14783 for (int i = runtimePermCount - 1; i >= 0; i--) { 14784 PermissionState permissionState = runtimePermStates.get(i); 14785 if (!usedPermissions.contains(permissionState.getName())) { 14786 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14787 if (bp != null) { 14788 permissionsState.revokeRuntimePermission(bp, userId); 14789 permissionsState.updatePermissionFlags(bp, userId, 14790 PackageManager.MASK_PERMISSION_FLAGS, 0); 14791 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14792 runtimePermissionChangedUserIds, userId); 14793 } 14794 } 14795 } 14796 } 14797 14798 return runtimePermissionChangedUserIds; 14799 } 14800 14801 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14802 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14803 // Update the parent package setting 14804 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14805 res, user); 14806 // Update the child packages setting 14807 final int childCount = (newPackage.childPackages != null) 14808 ? newPackage.childPackages.size() : 0; 14809 for (int i = 0; i < childCount; i++) { 14810 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14811 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14812 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14813 childRes.origUsers, childRes, user); 14814 } 14815 } 14816 14817 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14818 String installerPackageName, int[] allUsers, int[] installedForUsers, 14819 PackageInstalledInfo res, UserHandle user) { 14820 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14821 14822 String pkgName = newPackage.packageName; 14823 synchronized (mPackages) { 14824 //write settings. the installStatus will be incomplete at this stage. 14825 //note that the new package setting would have already been 14826 //added to mPackages. It hasn't been persisted yet. 14827 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14828 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14829 mSettings.writeLPr(); 14830 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14831 } 14832 14833 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14834 synchronized (mPackages) { 14835 updatePermissionsLPw(newPackage.packageName, newPackage, 14836 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14837 ? UPDATE_PERMISSIONS_ALL : 0)); 14838 // For system-bundled packages, we assume that installing an upgraded version 14839 // of the package implies that the user actually wants to run that new code, 14840 // so we enable the package. 14841 PackageSetting ps = mSettings.mPackages.get(pkgName); 14842 final int userId = user.getIdentifier(); 14843 if (ps != null) { 14844 if (isSystemApp(newPackage)) { 14845 if (DEBUG_INSTALL) { 14846 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14847 } 14848 // Enable system package for requested users 14849 if (res.origUsers != null) { 14850 for (int origUserId : res.origUsers) { 14851 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14852 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14853 origUserId, installerPackageName); 14854 } 14855 } 14856 } 14857 // Also convey the prior install/uninstall state 14858 if (allUsers != null && installedForUsers != null) { 14859 for (int currentUserId : allUsers) { 14860 final boolean installed = ArrayUtils.contains( 14861 installedForUsers, currentUserId); 14862 if (DEBUG_INSTALL) { 14863 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14864 } 14865 ps.setInstalled(installed, currentUserId); 14866 } 14867 // these install state changes will be persisted in the 14868 // upcoming call to mSettings.writeLPr(). 14869 } 14870 } 14871 // It's implied that when a user requests installation, they want the app to be 14872 // installed and enabled. 14873 if (userId != UserHandle.USER_ALL) { 14874 ps.setInstalled(true, userId); 14875 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14876 } 14877 } 14878 res.name = pkgName; 14879 res.uid = newPackage.applicationInfo.uid; 14880 res.pkg = newPackage; 14881 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14882 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14883 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14884 //to update install status 14885 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14886 mSettings.writeLPr(); 14887 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14888 } 14889 14890 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14891 } 14892 14893 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14894 try { 14895 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14896 installPackageLI(args, res); 14897 } finally { 14898 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14899 } 14900 } 14901 14902 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14903 final int installFlags = args.installFlags; 14904 final String installerPackageName = args.installerPackageName; 14905 final String volumeUuid = args.volumeUuid; 14906 final File tmpPackageFile = new File(args.getCodePath()); 14907 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14908 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14909 || (args.volumeUuid != null)); 14910 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14911 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14912 boolean replace = false; 14913 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14914 if (args.move != null) { 14915 // moving a complete application; perform an initial scan on the new install location 14916 scanFlags |= SCAN_INITIAL; 14917 } 14918 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14919 scanFlags |= SCAN_DONT_KILL_APP; 14920 } 14921 14922 // Result object to be returned 14923 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14924 14925 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14926 14927 // Sanity check 14928 if (ephemeral && (forwardLocked || onExternal)) { 14929 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14930 + " external=" + onExternal); 14931 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14932 return; 14933 } 14934 14935 // Retrieve PackageSettings and parse package 14936 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14937 | PackageParser.PARSE_ENFORCE_CODE 14938 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14939 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14940 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14941 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14942 PackageParser pp = new PackageParser(); 14943 pp.setSeparateProcesses(mSeparateProcesses); 14944 pp.setDisplayMetrics(mMetrics); 14945 14946 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14947 final PackageParser.Package pkg; 14948 try { 14949 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14950 } catch (PackageParserException e) { 14951 res.setError("Failed parse during installPackageLI", e); 14952 return; 14953 } finally { 14954 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14955 } 14956 14957 // If we are installing a clustered package add results for the children 14958 if (pkg.childPackages != null) { 14959 synchronized (mPackages) { 14960 final int childCount = pkg.childPackages.size(); 14961 for (int i = 0; i < childCount; i++) { 14962 PackageParser.Package childPkg = pkg.childPackages.get(i); 14963 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14964 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14965 childRes.pkg = childPkg; 14966 childRes.name = childPkg.packageName; 14967 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14968 if (childPs != null) { 14969 childRes.origUsers = childPs.queryInstalledUsers( 14970 sUserManager.getUserIds(), true); 14971 } 14972 if ((mPackages.containsKey(childPkg.packageName))) { 14973 childRes.removedInfo = new PackageRemovedInfo(); 14974 childRes.removedInfo.removedPackage = childPkg.packageName; 14975 } 14976 if (res.addedChildPackages == null) { 14977 res.addedChildPackages = new ArrayMap<>(); 14978 } 14979 res.addedChildPackages.put(childPkg.packageName, childRes); 14980 } 14981 } 14982 } 14983 14984 // If package doesn't declare API override, mark that we have an install 14985 // time CPU ABI override. 14986 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14987 pkg.cpuAbiOverride = args.abiOverride; 14988 } 14989 14990 String pkgName = res.name = pkg.packageName; 14991 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14992 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14993 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14994 return; 14995 } 14996 } 14997 14998 try { 14999 // either use what we've been given or parse directly from the APK 15000 if (args.certificates != null) { 15001 try { 15002 PackageParser.populateCertificates(pkg, args.certificates); 15003 } catch (PackageParserException e) { 15004 // there was something wrong with the certificates we were given; 15005 // try to pull them from the APK 15006 PackageParser.collectCertificates(pkg, parseFlags); 15007 } 15008 } else { 15009 PackageParser.collectCertificates(pkg, parseFlags); 15010 } 15011 } catch (PackageParserException e) { 15012 res.setError("Failed collect during installPackageLI", e); 15013 return; 15014 } 15015 15016 // Get rid of all references to package scan path via parser. 15017 pp = null; 15018 String oldCodePath = null; 15019 boolean systemApp = false; 15020 synchronized (mPackages) { 15021 // Check if installing already existing package 15022 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15023 String oldName = mSettings.mRenamedPackages.get(pkgName); 15024 if (pkg.mOriginalPackages != null 15025 && pkg.mOriginalPackages.contains(oldName) 15026 && mPackages.containsKey(oldName)) { 15027 // This package is derived from an original package, 15028 // and this device has been updating from that original 15029 // name. We must continue using the original name, so 15030 // rename the new package here. 15031 pkg.setPackageName(oldName); 15032 pkgName = pkg.packageName; 15033 replace = true; 15034 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15035 + oldName + " pkgName=" + pkgName); 15036 } else if (mPackages.containsKey(pkgName)) { 15037 // This package, under its official name, already exists 15038 // on the device; we should replace it. 15039 replace = true; 15040 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15041 } 15042 15043 // Child packages are installed through the parent package 15044 if (pkg.parentPackage != null) { 15045 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15046 "Package " + pkg.packageName + " is child of package " 15047 + pkg.parentPackage.parentPackage + ". Child packages " 15048 + "can be updated only through the parent package."); 15049 return; 15050 } 15051 15052 if (replace) { 15053 // Prevent apps opting out from runtime permissions 15054 PackageParser.Package oldPackage = mPackages.get(pkgName); 15055 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15056 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15057 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15058 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15059 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15060 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15061 + " doesn't support runtime permissions but the old" 15062 + " target SDK " + oldTargetSdk + " does."); 15063 return; 15064 } 15065 15066 // Prevent installing of child packages 15067 if (oldPackage.parentPackage != null) { 15068 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15069 "Package " + pkg.packageName + " is child of package " 15070 + oldPackage.parentPackage + ". Child packages " 15071 + "can be updated only through the parent package."); 15072 return; 15073 } 15074 } 15075 } 15076 15077 PackageSetting ps = mSettings.mPackages.get(pkgName); 15078 if (ps != null) { 15079 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15080 15081 // Quick sanity check that we're signed correctly if updating; 15082 // we'll check this again later when scanning, but we want to 15083 // bail early here before tripping over redefined permissions. 15084 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15085 if (!checkUpgradeKeySetLP(ps, pkg)) { 15086 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15087 + pkg.packageName + " upgrade keys do not match the " 15088 + "previously installed version"); 15089 return; 15090 } 15091 } else { 15092 try { 15093 verifySignaturesLP(ps, pkg); 15094 } catch (PackageManagerException e) { 15095 res.setError(e.error, e.getMessage()); 15096 return; 15097 } 15098 } 15099 15100 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15101 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15102 systemApp = (ps.pkg.applicationInfo.flags & 15103 ApplicationInfo.FLAG_SYSTEM) != 0; 15104 } 15105 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15106 } 15107 15108 // Check whether the newly-scanned package wants to define an already-defined perm 15109 int N = pkg.permissions.size(); 15110 for (int i = N-1; i >= 0; i--) { 15111 PackageParser.Permission perm = pkg.permissions.get(i); 15112 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15113 if (bp != null) { 15114 // If the defining package is signed with our cert, it's okay. This 15115 // also includes the "updating the same package" case, of course. 15116 // "updating same package" could also involve key-rotation. 15117 final boolean sigsOk; 15118 if (bp.sourcePackage.equals(pkg.packageName) 15119 && (bp.packageSetting instanceof PackageSetting) 15120 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15121 scanFlags))) { 15122 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15123 } else { 15124 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15125 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15126 } 15127 if (!sigsOk) { 15128 // If the owning package is the system itself, we log but allow 15129 // install to proceed; we fail the install on all other permission 15130 // redefinitions. 15131 if (!bp.sourcePackage.equals("android")) { 15132 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15133 + pkg.packageName + " attempting to redeclare permission " 15134 + perm.info.name + " already owned by " + bp.sourcePackage); 15135 res.origPermission = perm.info.name; 15136 res.origPackage = bp.sourcePackage; 15137 return; 15138 } else { 15139 Slog.w(TAG, "Package " + pkg.packageName 15140 + " attempting to redeclare system permission " 15141 + perm.info.name + "; ignoring new declaration"); 15142 pkg.permissions.remove(i); 15143 } 15144 } 15145 } 15146 } 15147 } 15148 15149 if (systemApp) { 15150 if (onExternal) { 15151 // Abort update; system app can't be replaced with app on sdcard 15152 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15153 "Cannot install updates to system apps on sdcard"); 15154 return; 15155 } else if (ephemeral) { 15156 // Abort update; system app can't be replaced with an ephemeral app 15157 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15158 "Cannot update a system app with an ephemeral app"); 15159 return; 15160 } 15161 } 15162 15163 if (args.move != null) { 15164 // We did an in-place move, so dex is ready to roll 15165 scanFlags |= SCAN_NO_DEX; 15166 scanFlags |= SCAN_MOVE; 15167 15168 synchronized (mPackages) { 15169 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15170 if (ps == null) { 15171 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15172 "Missing settings for moved package " + pkgName); 15173 } 15174 15175 // We moved the entire application as-is, so bring over the 15176 // previously derived ABI information. 15177 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15178 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15179 } 15180 15181 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15182 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15183 scanFlags |= SCAN_NO_DEX; 15184 15185 try { 15186 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15187 args.abiOverride : pkg.cpuAbiOverride); 15188 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15189 true /* extract libs */); 15190 } catch (PackageManagerException pme) { 15191 Slog.e(TAG, "Error deriving application ABI", pme); 15192 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15193 return; 15194 } 15195 15196 // Shared libraries for the package need to be updated. 15197 synchronized (mPackages) { 15198 try { 15199 updateSharedLibrariesLPw(pkg, null); 15200 } catch (PackageManagerException e) { 15201 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15202 } 15203 } 15204 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15205 // Do not run PackageDexOptimizer through the local performDexOpt 15206 // method because `pkg` may not be in `mPackages` yet. 15207 // 15208 // Also, don't fail application installs if the dexopt step fails. 15209 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15210 null /* instructionSets */, false /* checkProfiles */, 15211 getCompilerFilterForReason(REASON_INSTALL)); 15212 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15213 15214 // Notify BackgroundDexOptService that the package has been changed. 15215 // If this is an update of a package which used to fail to compile, 15216 // BDOS will remove it from its blacklist. 15217 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15218 } 15219 15220 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15221 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15222 return; 15223 } 15224 15225 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15226 15227 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15228 "installPackageLI")) { 15229 if (replace) { 15230 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15231 installerPackageName, res); 15232 } else { 15233 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15234 args.user, installerPackageName, volumeUuid, res); 15235 } 15236 } 15237 synchronized (mPackages) { 15238 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15239 if (ps != null) { 15240 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15241 } 15242 15243 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15244 for (int i = 0; i < childCount; i++) { 15245 PackageParser.Package childPkg = pkg.childPackages.get(i); 15246 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15247 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15248 if (childPs != null) { 15249 childRes.newUsers = childPs.queryInstalledUsers( 15250 sUserManager.getUserIds(), true); 15251 } 15252 } 15253 } 15254 } 15255 15256 private void startIntentFilterVerifications(int userId, boolean replacing, 15257 PackageParser.Package pkg) { 15258 if (mIntentFilterVerifierComponent == null) { 15259 Slog.w(TAG, "No IntentFilter verification will not be done as " 15260 + "there is no IntentFilterVerifier available!"); 15261 return; 15262 } 15263 15264 final int verifierUid = getPackageUid( 15265 mIntentFilterVerifierComponent.getPackageName(), 15266 MATCH_DEBUG_TRIAGED_MISSING, 15267 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15268 15269 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15270 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15271 mHandler.sendMessage(msg); 15272 15273 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15274 for (int i = 0; i < childCount; i++) { 15275 PackageParser.Package childPkg = pkg.childPackages.get(i); 15276 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15277 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15278 mHandler.sendMessage(msg); 15279 } 15280 } 15281 15282 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15283 PackageParser.Package pkg) { 15284 int size = pkg.activities.size(); 15285 if (size == 0) { 15286 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15287 "No activity, so no need to verify any IntentFilter!"); 15288 return; 15289 } 15290 15291 final boolean hasDomainURLs = hasDomainURLs(pkg); 15292 if (!hasDomainURLs) { 15293 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15294 "No domain URLs, so no need to verify any IntentFilter!"); 15295 return; 15296 } 15297 15298 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15299 + " if any IntentFilter from the " + size 15300 + " Activities needs verification ..."); 15301 15302 int count = 0; 15303 final String packageName = pkg.packageName; 15304 15305 synchronized (mPackages) { 15306 // If this is a new install and we see that we've already run verification for this 15307 // package, we have nothing to do: it means the state was restored from backup. 15308 if (!replacing) { 15309 IntentFilterVerificationInfo ivi = 15310 mSettings.getIntentFilterVerificationLPr(packageName); 15311 if (ivi != null) { 15312 if (DEBUG_DOMAIN_VERIFICATION) { 15313 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15314 + ivi.getStatusString()); 15315 } 15316 return; 15317 } 15318 } 15319 15320 // If any filters need to be verified, then all need to be. 15321 boolean needToVerify = false; 15322 for (PackageParser.Activity a : pkg.activities) { 15323 for (ActivityIntentInfo filter : a.intents) { 15324 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15325 if (DEBUG_DOMAIN_VERIFICATION) { 15326 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15327 } 15328 needToVerify = true; 15329 break; 15330 } 15331 } 15332 } 15333 15334 if (needToVerify) { 15335 final int verificationId = mIntentFilterVerificationToken++; 15336 for (PackageParser.Activity a : pkg.activities) { 15337 for (ActivityIntentInfo filter : a.intents) { 15338 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15339 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15340 "Verification needed for IntentFilter:" + filter.toString()); 15341 mIntentFilterVerifier.addOneIntentFilterVerification( 15342 verifierUid, userId, verificationId, filter, packageName); 15343 count++; 15344 } 15345 } 15346 } 15347 } 15348 } 15349 15350 if (count > 0) { 15351 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15352 + " IntentFilter verification" + (count > 1 ? "s" : "") 15353 + " for userId:" + userId); 15354 mIntentFilterVerifier.startVerifications(userId); 15355 } else { 15356 if (DEBUG_DOMAIN_VERIFICATION) { 15357 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15358 } 15359 } 15360 } 15361 15362 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15363 final ComponentName cn = filter.activity.getComponentName(); 15364 final String packageName = cn.getPackageName(); 15365 15366 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15367 packageName); 15368 if (ivi == null) { 15369 return true; 15370 } 15371 int status = ivi.getStatus(); 15372 switch (status) { 15373 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15374 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15375 return true; 15376 15377 default: 15378 // Nothing to do 15379 return false; 15380 } 15381 } 15382 15383 private static boolean isMultiArch(ApplicationInfo info) { 15384 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15385 } 15386 15387 private static boolean isExternal(PackageParser.Package pkg) { 15388 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15389 } 15390 15391 private static boolean isExternal(PackageSetting ps) { 15392 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15393 } 15394 15395 private static boolean isEphemeral(PackageParser.Package pkg) { 15396 return pkg.applicationInfo.isEphemeralApp(); 15397 } 15398 15399 private static boolean isEphemeral(PackageSetting ps) { 15400 return ps.pkg != null && isEphemeral(ps.pkg); 15401 } 15402 15403 private static boolean isSystemApp(PackageParser.Package pkg) { 15404 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15405 } 15406 15407 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15408 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15409 } 15410 15411 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15412 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15413 } 15414 15415 private static boolean isSystemApp(PackageSetting ps) { 15416 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15417 } 15418 15419 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15420 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15421 } 15422 15423 private int packageFlagsToInstallFlags(PackageSetting ps) { 15424 int installFlags = 0; 15425 if (isEphemeral(ps)) { 15426 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15427 } 15428 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15429 // This existing package was an external ASEC install when we have 15430 // the external flag without a UUID 15431 installFlags |= PackageManager.INSTALL_EXTERNAL; 15432 } 15433 if (ps.isForwardLocked()) { 15434 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15435 } 15436 return installFlags; 15437 } 15438 15439 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15440 if (isExternal(pkg)) { 15441 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15442 return StorageManager.UUID_PRIMARY_PHYSICAL; 15443 } else { 15444 return pkg.volumeUuid; 15445 } 15446 } else { 15447 return StorageManager.UUID_PRIVATE_INTERNAL; 15448 } 15449 } 15450 15451 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15452 if (isExternal(pkg)) { 15453 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15454 return mSettings.getExternalVersion(); 15455 } else { 15456 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15457 } 15458 } else { 15459 return mSettings.getInternalVersion(); 15460 } 15461 } 15462 15463 private void deleteTempPackageFiles() { 15464 final FilenameFilter filter = new FilenameFilter() { 15465 public boolean accept(File dir, String name) { 15466 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15467 } 15468 }; 15469 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15470 file.delete(); 15471 } 15472 } 15473 15474 @Override 15475 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15476 int flags) { 15477 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15478 flags); 15479 } 15480 15481 @Override 15482 public void deletePackage(final String packageName, 15483 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15484 mContext.enforceCallingOrSelfPermission( 15485 android.Manifest.permission.DELETE_PACKAGES, null); 15486 Preconditions.checkNotNull(packageName); 15487 Preconditions.checkNotNull(observer); 15488 final int uid = Binder.getCallingUid(); 15489 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15490 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15491 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15492 mContext.enforceCallingOrSelfPermission( 15493 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15494 "deletePackage for user " + userId); 15495 } 15496 15497 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15498 try { 15499 observer.onPackageDeleted(packageName, 15500 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15501 } catch (RemoteException re) { 15502 } 15503 return; 15504 } 15505 15506 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15507 try { 15508 observer.onPackageDeleted(packageName, 15509 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15510 } catch (RemoteException re) { 15511 } 15512 return; 15513 } 15514 15515 if (DEBUG_REMOVE) { 15516 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15517 + " deleteAllUsers: " + deleteAllUsers ); 15518 } 15519 // Queue up an async operation since the package deletion may take a little while. 15520 mHandler.post(new Runnable() { 15521 public void run() { 15522 mHandler.removeCallbacks(this); 15523 int returnCode; 15524 if (!deleteAllUsers) { 15525 returnCode = deletePackageX(packageName, userId, deleteFlags); 15526 } else { 15527 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15528 // If nobody is blocking uninstall, proceed with delete for all users 15529 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15530 returnCode = deletePackageX(packageName, userId, deleteFlags); 15531 } else { 15532 // Otherwise uninstall individually for users with blockUninstalls=false 15533 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15534 for (int userId : users) { 15535 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15536 returnCode = deletePackageX(packageName, userId, userFlags); 15537 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15538 Slog.w(TAG, "Package delete failed for user " + userId 15539 + ", returnCode " + returnCode); 15540 } 15541 } 15542 } 15543 // The app has only been marked uninstalled for certain users. 15544 // We still need to report that delete was blocked 15545 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15546 } 15547 } 15548 try { 15549 observer.onPackageDeleted(packageName, returnCode, null); 15550 } catch (RemoteException e) { 15551 Log.i(TAG, "Observer no longer exists."); 15552 } //end catch 15553 } //end run 15554 }); 15555 } 15556 15557 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15558 int[] result = EMPTY_INT_ARRAY; 15559 for (int userId : userIds) { 15560 if (getBlockUninstallForUser(packageName, userId)) { 15561 result = ArrayUtils.appendInt(result, userId); 15562 } 15563 } 15564 return result; 15565 } 15566 15567 @Override 15568 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15569 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15570 } 15571 15572 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15573 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15574 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15575 try { 15576 if (dpm != null) { 15577 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15578 /* callingUserOnly =*/ false); 15579 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15580 : deviceOwnerComponentName.getPackageName(); 15581 // Does the package contains the device owner? 15582 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15583 // this check is probably not needed, since DO should be registered as a device 15584 // admin on some user too. (Original bug for this: b/17657954) 15585 if (packageName.equals(deviceOwnerPackageName)) { 15586 return true; 15587 } 15588 // Does it contain a device admin for any user? 15589 int[] users; 15590 if (userId == UserHandle.USER_ALL) { 15591 users = sUserManager.getUserIds(); 15592 } else { 15593 users = new int[]{userId}; 15594 } 15595 for (int i = 0; i < users.length; ++i) { 15596 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15597 return true; 15598 } 15599 } 15600 } 15601 } catch (RemoteException e) { 15602 } 15603 return false; 15604 } 15605 15606 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15607 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15608 } 15609 15610 /** 15611 * This method is an internal method that could be get invoked either 15612 * to delete an installed package or to clean up a failed installation. 15613 * After deleting an installed package, a broadcast is sent to notify any 15614 * listeners that the package has been removed. For cleaning up a failed 15615 * installation, the broadcast is not necessary since the package's 15616 * installation wouldn't have sent the initial broadcast either 15617 * The key steps in deleting a package are 15618 * deleting the package information in internal structures like mPackages, 15619 * deleting the packages base directories through installd 15620 * updating mSettings to reflect current status 15621 * persisting settings for later use 15622 * sending a broadcast if necessary 15623 */ 15624 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15625 final PackageRemovedInfo info = new PackageRemovedInfo(); 15626 final boolean res; 15627 15628 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15629 ? UserHandle.USER_ALL : userId; 15630 15631 if (isPackageDeviceAdmin(packageName, removeUser)) { 15632 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15633 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15634 } 15635 15636 PackageSetting uninstalledPs = null; 15637 15638 // for the uninstall-updates case and restricted profiles, remember the per- 15639 // user handle installed state 15640 int[] allUsers; 15641 synchronized (mPackages) { 15642 uninstalledPs = mSettings.mPackages.get(packageName); 15643 if (uninstalledPs == null) { 15644 Slog.w(TAG, "Not removing non-existent package " + packageName); 15645 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15646 } 15647 allUsers = sUserManager.getUserIds(); 15648 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15649 } 15650 15651 final int freezeUser; 15652 if (isUpdatedSystemApp(uninstalledPs) 15653 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15654 // We're downgrading a system app, which will apply to all users, so 15655 // freeze them all during the downgrade 15656 freezeUser = UserHandle.USER_ALL; 15657 } else { 15658 freezeUser = removeUser; 15659 } 15660 15661 synchronized (mInstallLock) { 15662 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15663 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15664 deleteFlags, "deletePackageX")) { 15665 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15666 deleteFlags | REMOVE_CHATTY, info, true, null); 15667 } 15668 synchronized (mPackages) { 15669 if (res) { 15670 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15671 } 15672 } 15673 } 15674 15675 if (res) { 15676 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15677 info.sendPackageRemovedBroadcasts(killApp); 15678 info.sendSystemPackageUpdatedBroadcasts(); 15679 info.sendSystemPackageAppearedBroadcasts(); 15680 } 15681 // Force a gc here. 15682 Runtime.getRuntime().gc(); 15683 // Delete the resources here after sending the broadcast to let 15684 // other processes clean up before deleting resources. 15685 if (info.args != null) { 15686 synchronized (mInstallLock) { 15687 info.args.doPostDeleteLI(true); 15688 } 15689 } 15690 15691 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15692 } 15693 15694 class PackageRemovedInfo { 15695 String removedPackage; 15696 int uid = -1; 15697 int removedAppId = -1; 15698 int[] origUsers; 15699 int[] removedUsers = null; 15700 boolean isRemovedPackageSystemUpdate = false; 15701 boolean isUpdate; 15702 boolean dataRemoved; 15703 boolean removedForAllUsers; 15704 // Clean up resources deleted packages. 15705 InstallArgs args = null; 15706 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15707 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15708 15709 void sendPackageRemovedBroadcasts(boolean killApp) { 15710 sendPackageRemovedBroadcastInternal(killApp); 15711 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15712 for (int i = 0; i < childCount; i++) { 15713 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15714 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15715 } 15716 } 15717 15718 void sendSystemPackageUpdatedBroadcasts() { 15719 if (isRemovedPackageSystemUpdate) { 15720 sendSystemPackageUpdatedBroadcastsInternal(); 15721 final int childCount = (removedChildPackages != null) 15722 ? removedChildPackages.size() : 0; 15723 for (int i = 0; i < childCount; i++) { 15724 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15725 if (childInfo.isRemovedPackageSystemUpdate) { 15726 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15727 } 15728 } 15729 } 15730 } 15731 15732 void sendSystemPackageAppearedBroadcasts() { 15733 final int packageCount = (appearedChildPackages != null) 15734 ? appearedChildPackages.size() : 0; 15735 for (int i = 0; i < packageCount; i++) { 15736 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15737 for (int userId : installedInfo.newUsers) { 15738 sendPackageAddedForUser(installedInfo.name, true, 15739 UserHandle.getAppId(installedInfo.uid), userId); 15740 } 15741 } 15742 } 15743 15744 private void sendSystemPackageUpdatedBroadcastsInternal() { 15745 Bundle extras = new Bundle(2); 15746 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15747 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15748 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15749 extras, 0, null, null, null); 15750 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15751 extras, 0, null, null, null); 15752 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15753 null, 0, removedPackage, null, null); 15754 } 15755 15756 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15757 Bundle extras = new Bundle(2); 15758 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15759 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15760 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15761 if (isUpdate || isRemovedPackageSystemUpdate) { 15762 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15763 } 15764 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15765 if (removedPackage != null) { 15766 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15767 extras, 0, null, null, removedUsers); 15768 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15769 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15770 removedPackage, extras, 0, null, null, removedUsers); 15771 } 15772 } 15773 if (removedAppId >= 0) { 15774 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15775 removedUsers); 15776 } 15777 } 15778 } 15779 15780 /* 15781 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15782 * flag is not set, the data directory is removed as well. 15783 * make sure this flag is set for partially installed apps. If not its meaningless to 15784 * delete a partially installed application. 15785 */ 15786 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15787 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15788 String packageName = ps.name; 15789 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15790 // Retrieve object to delete permissions for shared user later on 15791 final PackageParser.Package deletedPkg; 15792 final PackageSetting deletedPs; 15793 // reader 15794 synchronized (mPackages) { 15795 deletedPkg = mPackages.get(packageName); 15796 deletedPs = mSettings.mPackages.get(packageName); 15797 if (outInfo != null) { 15798 outInfo.removedPackage = packageName; 15799 outInfo.removedUsers = deletedPs != null 15800 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15801 : null; 15802 } 15803 } 15804 15805 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15806 15807 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15808 final PackageParser.Package resolvedPkg; 15809 if (deletedPkg != null) { 15810 resolvedPkg = deletedPkg; 15811 } else { 15812 // We don't have a parsed package when it lives on an ejected 15813 // adopted storage device, so fake something together 15814 resolvedPkg = new PackageParser.Package(ps.name); 15815 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15816 } 15817 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15818 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15819 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15820 if (outInfo != null) { 15821 outInfo.dataRemoved = true; 15822 } 15823 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15824 } 15825 15826 // writer 15827 synchronized (mPackages) { 15828 if (deletedPs != null) { 15829 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15830 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15831 clearDefaultBrowserIfNeeded(packageName); 15832 if (outInfo != null) { 15833 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15834 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15835 } 15836 updatePermissionsLPw(deletedPs.name, null, 0); 15837 if (deletedPs.sharedUser != null) { 15838 // Remove permissions associated with package. Since runtime 15839 // permissions are per user we have to kill the removed package 15840 // or packages running under the shared user of the removed 15841 // package if revoking the permissions requested only by the removed 15842 // package is successful and this causes a change in gids. 15843 for (int userId : UserManagerService.getInstance().getUserIds()) { 15844 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15845 userId); 15846 if (userIdToKill == UserHandle.USER_ALL 15847 || userIdToKill >= UserHandle.USER_SYSTEM) { 15848 // If gids changed for this user, kill all affected packages. 15849 mHandler.post(new Runnable() { 15850 @Override 15851 public void run() { 15852 // This has to happen with no lock held. 15853 killApplication(deletedPs.name, deletedPs.appId, 15854 KILL_APP_REASON_GIDS_CHANGED); 15855 } 15856 }); 15857 break; 15858 } 15859 } 15860 } 15861 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15862 } 15863 // make sure to preserve per-user disabled state if this removal was just 15864 // a downgrade of a system app to the factory package 15865 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15866 if (DEBUG_REMOVE) { 15867 Slog.d(TAG, "Propagating install state across downgrade"); 15868 } 15869 for (int userId : allUserHandles) { 15870 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15871 if (DEBUG_REMOVE) { 15872 Slog.d(TAG, " user " + userId + " => " + installed); 15873 } 15874 ps.setInstalled(installed, userId); 15875 } 15876 } 15877 } 15878 // can downgrade to reader 15879 if (writeSettings) { 15880 // Save settings now 15881 mSettings.writeLPr(); 15882 } 15883 } 15884 if (outInfo != null) { 15885 // A user ID was deleted here. Go through all users and remove it 15886 // from KeyStore. 15887 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15888 } 15889 } 15890 15891 static boolean locationIsPrivileged(File path) { 15892 try { 15893 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15894 .getCanonicalPath(); 15895 return path.getCanonicalPath().startsWith(privilegedAppDir); 15896 } catch (IOException e) { 15897 Slog.e(TAG, "Unable to access code path " + path); 15898 } 15899 return false; 15900 } 15901 15902 /* 15903 * Tries to delete system package. 15904 */ 15905 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15906 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15907 boolean writeSettings) { 15908 if (deletedPs.parentPackageName != null) { 15909 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15910 return false; 15911 } 15912 15913 final boolean applyUserRestrictions 15914 = (allUserHandles != null) && (outInfo.origUsers != null); 15915 final PackageSetting disabledPs; 15916 // Confirm if the system package has been updated 15917 // An updated system app can be deleted. This will also have to restore 15918 // the system pkg from system partition 15919 // reader 15920 synchronized (mPackages) { 15921 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15922 } 15923 15924 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15925 + " disabledPs=" + disabledPs); 15926 15927 if (disabledPs == null) { 15928 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15929 return false; 15930 } else if (DEBUG_REMOVE) { 15931 Slog.d(TAG, "Deleting system pkg from data partition"); 15932 } 15933 15934 if (DEBUG_REMOVE) { 15935 if (applyUserRestrictions) { 15936 Slog.d(TAG, "Remembering install states:"); 15937 for (int userId : allUserHandles) { 15938 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15939 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15940 } 15941 } 15942 } 15943 15944 // Delete the updated package 15945 outInfo.isRemovedPackageSystemUpdate = true; 15946 if (outInfo.removedChildPackages != null) { 15947 final int childCount = (deletedPs.childPackageNames != null) 15948 ? deletedPs.childPackageNames.size() : 0; 15949 for (int i = 0; i < childCount; i++) { 15950 String childPackageName = deletedPs.childPackageNames.get(i); 15951 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15952 .contains(childPackageName)) { 15953 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15954 childPackageName); 15955 if (childInfo != null) { 15956 childInfo.isRemovedPackageSystemUpdate = true; 15957 } 15958 } 15959 } 15960 } 15961 15962 if (disabledPs.versionCode < deletedPs.versionCode) { 15963 // Delete data for downgrades 15964 flags &= ~PackageManager.DELETE_KEEP_DATA; 15965 } else { 15966 // Preserve data by setting flag 15967 flags |= PackageManager.DELETE_KEEP_DATA; 15968 } 15969 15970 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15971 outInfo, writeSettings, disabledPs.pkg); 15972 if (!ret) { 15973 return false; 15974 } 15975 15976 // writer 15977 synchronized (mPackages) { 15978 // Reinstate the old system package 15979 enableSystemPackageLPw(disabledPs.pkg); 15980 // Remove any native libraries from the upgraded package. 15981 removeNativeBinariesLI(deletedPs); 15982 } 15983 15984 // Install the system package 15985 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15986 int parseFlags = mDefParseFlags 15987 | PackageParser.PARSE_MUST_BE_APK 15988 | PackageParser.PARSE_IS_SYSTEM 15989 | PackageParser.PARSE_IS_SYSTEM_DIR; 15990 if (locationIsPrivileged(disabledPs.codePath)) { 15991 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15992 } 15993 15994 final PackageParser.Package newPkg; 15995 try { 15996 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15997 } catch (PackageManagerException e) { 15998 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15999 + e.getMessage()); 16000 return false; 16001 } 16002 16003 prepareAppDataAfterInstallLIF(newPkg); 16004 16005 // writer 16006 synchronized (mPackages) { 16007 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16008 16009 // Propagate the permissions state as we do not want to drop on the floor 16010 // runtime permissions. The update permissions method below will take 16011 // care of removing obsolete permissions and grant install permissions. 16012 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16013 updatePermissionsLPw(newPkg.packageName, newPkg, 16014 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16015 16016 if (applyUserRestrictions) { 16017 if (DEBUG_REMOVE) { 16018 Slog.d(TAG, "Propagating install state across reinstall"); 16019 } 16020 for (int userId : allUserHandles) { 16021 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16022 if (DEBUG_REMOVE) { 16023 Slog.d(TAG, " user " + userId + " => " + installed); 16024 } 16025 ps.setInstalled(installed, userId); 16026 16027 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16028 } 16029 // Regardless of writeSettings we need to ensure that this restriction 16030 // state propagation is persisted 16031 mSettings.writeAllUsersPackageRestrictionsLPr(); 16032 } 16033 // can downgrade to reader here 16034 if (writeSettings) { 16035 mSettings.writeLPr(); 16036 } 16037 } 16038 return true; 16039 } 16040 16041 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16042 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16043 PackageRemovedInfo outInfo, boolean writeSettings, 16044 PackageParser.Package replacingPackage) { 16045 synchronized (mPackages) { 16046 if (outInfo != null) { 16047 outInfo.uid = ps.appId; 16048 } 16049 16050 if (outInfo != null && outInfo.removedChildPackages != null) { 16051 final int childCount = (ps.childPackageNames != null) 16052 ? ps.childPackageNames.size() : 0; 16053 for (int i = 0; i < childCount; i++) { 16054 String childPackageName = ps.childPackageNames.get(i); 16055 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16056 if (childPs == null) { 16057 return false; 16058 } 16059 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16060 childPackageName); 16061 if (childInfo != null) { 16062 childInfo.uid = childPs.appId; 16063 } 16064 } 16065 } 16066 } 16067 16068 // Delete package data from internal structures and also remove data if flag is set 16069 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16070 16071 // Delete the child packages data 16072 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16073 for (int i = 0; i < childCount; i++) { 16074 PackageSetting childPs; 16075 synchronized (mPackages) { 16076 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16077 } 16078 if (childPs != null) { 16079 PackageRemovedInfo childOutInfo = (outInfo != null 16080 && outInfo.removedChildPackages != null) 16081 ? outInfo.removedChildPackages.get(childPs.name) : null; 16082 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16083 && (replacingPackage != null 16084 && !replacingPackage.hasChildPackage(childPs.name)) 16085 ? flags & ~DELETE_KEEP_DATA : flags; 16086 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16087 deleteFlags, writeSettings); 16088 } 16089 } 16090 16091 // Delete application code and resources only for parent packages 16092 if (ps.parentPackageName == null) { 16093 if (deleteCodeAndResources && (outInfo != null)) { 16094 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16095 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16096 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16097 } 16098 } 16099 16100 return true; 16101 } 16102 16103 @Override 16104 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16105 int userId) { 16106 mContext.enforceCallingOrSelfPermission( 16107 android.Manifest.permission.DELETE_PACKAGES, null); 16108 synchronized (mPackages) { 16109 PackageSetting ps = mSettings.mPackages.get(packageName); 16110 if (ps == null) { 16111 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16112 return false; 16113 } 16114 if (!ps.getInstalled(userId)) { 16115 // Can't block uninstall for an app that is not installed or enabled. 16116 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16117 return false; 16118 } 16119 ps.setBlockUninstall(blockUninstall, userId); 16120 mSettings.writePackageRestrictionsLPr(userId); 16121 } 16122 return true; 16123 } 16124 16125 @Override 16126 public boolean getBlockUninstallForUser(String packageName, int userId) { 16127 synchronized (mPackages) { 16128 PackageSetting ps = mSettings.mPackages.get(packageName); 16129 if (ps == null) { 16130 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16131 return false; 16132 } 16133 return ps.getBlockUninstall(userId); 16134 } 16135 } 16136 16137 @Override 16138 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16139 int callingUid = Binder.getCallingUid(); 16140 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16141 throw new SecurityException( 16142 "setRequiredForSystemUser can only be run by the system or root"); 16143 } 16144 synchronized (mPackages) { 16145 PackageSetting ps = mSettings.mPackages.get(packageName); 16146 if (ps == null) { 16147 Log.w(TAG, "Package doesn't exist: " + packageName); 16148 return false; 16149 } 16150 if (systemUserApp) { 16151 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16152 } else { 16153 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16154 } 16155 mSettings.writeLPr(); 16156 } 16157 return true; 16158 } 16159 16160 /* 16161 * This method handles package deletion in general 16162 */ 16163 private boolean deletePackageLIF(String packageName, UserHandle user, 16164 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16165 PackageRemovedInfo outInfo, boolean writeSettings, 16166 PackageParser.Package replacingPackage) { 16167 if (packageName == null) { 16168 Slog.w(TAG, "Attempt to delete null packageName."); 16169 return false; 16170 } 16171 16172 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16173 16174 PackageSetting ps; 16175 16176 synchronized (mPackages) { 16177 ps = mSettings.mPackages.get(packageName); 16178 if (ps == null) { 16179 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16180 return false; 16181 } 16182 16183 if (ps.parentPackageName != null && (!isSystemApp(ps) 16184 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16185 if (DEBUG_REMOVE) { 16186 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16187 + ((user == null) ? UserHandle.USER_ALL : user)); 16188 } 16189 final int removedUserId = (user != null) ? user.getIdentifier() 16190 : UserHandle.USER_ALL; 16191 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16192 return false; 16193 } 16194 markPackageUninstalledForUserLPw(ps, user); 16195 scheduleWritePackageRestrictionsLocked(user); 16196 return true; 16197 } 16198 } 16199 16200 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16201 && user.getIdentifier() != UserHandle.USER_ALL)) { 16202 // The caller is asking that the package only be deleted for a single 16203 // user. To do this, we just mark its uninstalled state and delete 16204 // its data. If this is a system app, we only allow this to happen if 16205 // they have set the special DELETE_SYSTEM_APP which requests different 16206 // semantics than normal for uninstalling system apps. 16207 markPackageUninstalledForUserLPw(ps, user); 16208 16209 if (!isSystemApp(ps)) { 16210 // Do not uninstall the APK if an app should be cached 16211 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16212 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16213 // Other user still have this package installed, so all 16214 // we need to do is clear this user's data and save that 16215 // it is uninstalled. 16216 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16217 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16218 return false; 16219 } 16220 scheduleWritePackageRestrictionsLocked(user); 16221 return true; 16222 } else { 16223 // We need to set it back to 'installed' so the uninstall 16224 // broadcasts will be sent correctly. 16225 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16226 ps.setInstalled(true, user.getIdentifier()); 16227 } 16228 } else { 16229 // This is a system app, so we assume that the 16230 // other users still have this package installed, so all 16231 // we need to do is clear this user's data and save that 16232 // it is uninstalled. 16233 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16234 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16235 return false; 16236 } 16237 scheduleWritePackageRestrictionsLocked(user); 16238 return true; 16239 } 16240 } 16241 16242 // If we are deleting a composite package for all users, keep track 16243 // of result for each child. 16244 if (ps.childPackageNames != null && outInfo != null) { 16245 synchronized (mPackages) { 16246 final int childCount = ps.childPackageNames.size(); 16247 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16248 for (int i = 0; i < childCount; i++) { 16249 String childPackageName = ps.childPackageNames.get(i); 16250 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16251 childInfo.removedPackage = childPackageName; 16252 outInfo.removedChildPackages.put(childPackageName, childInfo); 16253 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16254 if (childPs != null) { 16255 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16256 } 16257 } 16258 } 16259 } 16260 16261 boolean ret = false; 16262 if (isSystemApp(ps)) { 16263 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16264 // When an updated system application is deleted we delete the existing resources 16265 // as well and fall back to existing code in system partition 16266 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16267 } else { 16268 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16269 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16270 outInfo, writeSettings, replacingPackage); 16271 } 16272 16273 // Take a note whether we deleted the package for all users 16274 if (outInfo != null) { 16275 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16276 if (outInfo.removedChildPackages != null) { 16277 synchronized (mPackages) { 16278 final int childCount = outInfo.removedChildPackages.size(); 16279 for (int i = 0; i < childCount; i++) { 16280 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16281 if (childInfo != null) { 16282 childInfo.removedForAllUsers = mPackages.get( 16283 childInfo.removedPackage) == null; 16284 } 16285 } 16286 } 16287 } 16288 // If we uninstalled an update to a system app there may be some 16289 // child packages that appeared as they are declared in the system 16290 // app but were not declared in the update. 16291 if (isSystemApp(ps)) { 16292 synchronized (mPackages) { 16293 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16294 final int childCount = (updatedPs.childPackageNames != null) 16295 ? updatedPs.childPackageNames.size() : 0; 16296 for (int i = 0; i < childCount; i++) { 16297 String childPackageName = updatedPs.childPackageNames.get(i); 16298 if (outInfo.removedChildPackages == null 16299 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16300 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16301 if (childPs == null) { 16302 continue; 16303 } 16304 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16305 installRes.name = childPackageName; 16306 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16307 installRes.pkg = mPackages.get(childPackageName); 16308 installRes.uid = childPs.pkg.applicationInfo.uid; 16309 if (outInfo.appearedChildPackages == null) { 16310 outInfo.appearedChildPackages = new ArrayMap<>(); 16311 } 16312 outInfo.appearedChildPackages.put(childPackageName, installRes); 16313 } 16314 } 16315 } 16316 } 16317 } 16318 16319 return ret; 16320 } 16321 16322 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16323 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16324 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16325 for (int nextUserId : userIds) { 16326 if (DEBUG_REMOVE) { 16327 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16328 } 16329 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16330 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16331 false /*hidden*/, false /*suspended*/, null, null, null, 16332 false /*blockUninstall*/, 16333 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16334 } 16335 } 16336 16337 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16338 PackageRemovedInfo outInfo) { 16339 final PackageParser.Package pkg; 16340 synchronized (mPackages) { 16341 pkg = mPackages.get(ps.name); 16342 } 16343 16344 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16345 : new int[] {userId}; 16346 for (int nextUserId : userIds) { 16347 if (DEBUG_REMOVE) { 16348 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16349 + nextUserId); 16350 } 16351 16352 destroyAppDataLIF(pkg, userId, 16353 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16354 destroyAppProfilesLIF(pkg, userId); 16355 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16356 schedulePackageCleaning(ps.name, nextUserId, false); 16357 synchronized (mPackages) { 16358 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16359 scheduleWritePackageRestrictionsLocked(nextUserId); 16360 } 16361 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16362 } 16363 } 16364 16365 if (outInfo != null) { 16366 outInfo.removedPackage = ps.name; 16367 outInfo.removedAppId = ps.appId; 16368 outInfo.removedUsers = userIds; 16369 } 16370 16371 return true; 16372 } 16373 16374 private final class ClearStorageConnection implements ServiceConnection { 16375 IMediaContainerService mContainerService; 16376 16377 @Override 16378 public void onServiceConnected(ComponentName name, IBinder service) { 16379 synchronized (this) { 16380 mContainerService = IMediaContainerService.Stub.asInterface(service); 16381 notifyAll(); 16382 } 16383 } 16384 16385 @Override 16386 public void onServiceDisconnected(ComponentName name) { 16387 } 16388 } 16389 16390 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16391 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16392 16393 final boolean mounted; 16394 if (Environment.isExternalStorageEmulated()) { 16395 mounted = true; 16396 } else { 16397 final String status = Environment.getExternalStorageState(); 16398 16399 mounted = status.equals(Environment.MEDIA_MOUNTED) 16400 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16401 } 16402 16403 if (!mounted) { 16404 return; 16405 } 16406 16407 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16408 int[] users; 16409 if (userId == UserHandle.USER_ALL) { 16410 users = sUserManager.getUserIds(); 16411 } else { 16412 users = new int[] { userId }; 16413 } 16414 final ClearStorageConnection conn = new ClearStorageConnection(); 16415 if (mContext.bindServiceAsUser( 16416 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16417 try { 16418 for (int curUser : users) { 16419 long timeout = SystemClock.uptimeMillis() + 5000; 16420 synchronized (conn) { 16421 long now; 16422 while (conn.mContainerService == null && 16423 (now = SystemClock.uptimeMillis()) < timeout) { 16424 try { 16425 conn.wait(timeout - now); 16426 } catch (InterruptedException e) { 16427 } 16428 } 16429 } 16430 if (conn.mContainerService == null) { 16431 return; 16432 } 16433 16434 final UserEnvironment userEnv = new UserEnvironment(curUser); 16435 clearDirectory(conn.mContainerService, 16436 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16437 if (allData) { 16438 clearDirectory(conn.mContainerService, 16439 userEnv.buildExternalStorageAppDataDirs(packageName)); 16440 clearDirectory(conn.mContainerService, 16441 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16442 } 16443 } 16444 } finally { 16445 mContext.unbindService(conn); 16446 } 16447 } 16448 } 16449 16450 @Override 16451 public void clearApplicationProfileData(String packageName) { 16452 enforceSystemOrRoot("Only the system can clear all profile data"); 16453 16454 final PackageParser.Package pkg; 16455 synchronized (mPackages) { 16456 pkg = mPackages.get(packageName); 16457 } 16458 16459 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16460 synchronized (mInstallLock) { 16461 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16462 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16463 true /* removeBaseMarker */); 16464 } 16465 } 16466 } 16467 16468 @Override 16469 public void clearApplicationUserData(final String packageName, 16470 final IPackageDataObserver observer, final int userId) { 16471 mContext.enforceCallingOrSelfPermission( 16472 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16473 16474 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16475 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16476 16477 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16478 throw new SecurityException("Cannot clear data for a protected package: " 16479 + packageName); 16480 } 16481 // Queue up an async operation since the package deletion may take a little while. 16482 mHandler.post(new Runnable() { 16483 public void run() { 16484 mHandler.removeCallbacks(this); 16485 final boolean succeeded; 16486 try (PackageFreezer freezer = freezePackage(packageName, 16487 "clearApplicationUserData")) { 16488 synchronized (mInstallLock) { 16489 succeeded = clearApplicationUserDataLIF(packageName, userId); 16490 } 16491 clearExternalStorageDataSync(packageName, userId, true); 16492 } 16493 if (succeeded) { 16494 // invoke DeviceStorageMonitor's update method to clear any notifications 16495 DeviceStorageMonitorInternal dsm = LocalServices 16496 .getService(DeviceStorageMonitorInternal.class); 16497 if (dsm != null) { 16498 dsm.checkMemory(); 16499 } 16500 } 16501 if(observer != null) { 16502 try { 16503 observer.onRemoveCompleted(packageName, succeeded); 16504 } catch (RemoteException e) { 16505 Log.i(TAG, "Observer no longer exists."); 16506 } 16507 } //end if observer 16508 } //end run 16509 }); 16510 } 16511 16512 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16513 if (packageName == null) { 16514 Slog.w(TAG, "Attempt to delete null packageName."); 16515 return false; 16516 } 16517 16518 // Try finding details about the requested package 16519 PackageParser.Package pkg; 16520 synchronized (mPackages) { 16521 pkg = mPackages.get(packageName); 16522 if (pkg == null) { 16523 final PackageSetting ps = mSettings.mPackages.get(packageName); 16524 if (ps != null) { 16525 pkg = ps.pkg; 16526 } 16527 } 16528 16529 if (pkg == null) { 16530 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16531 return false; 16532 } 16533 16534 PackageSetting ps = (PackageSetting) pkg.mExtras; 16535 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16536 } 16537 16538 clearAppDataLIF(pkg, userId, 16539 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16540 16541 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16542 removeKeystoreDataIfNeeded(userId, appId); 16543 16544 UserManagerInternal umInternal = getUserManagerInternal(); 16545 final int flags; 16546 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16547 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16548 } else if (umInternal.isUserRunning(userId)) { 16549 flags = StorageManager.FLAG_STORAGE_DE; 16550 } else { 16551 flags = 0; 16552 } 16553 prepareAppDataContentsLIF(pkg, userId, flags); 16554 16555 return true; 16556 } 16557 16558 /** 16559 * Reverts user permission state changes (permissions and flags) in 16560 * all packages for a given user. 16561 * 16562 * @param userId The device user for which to do a reset. 16563 */ 16564 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16565 final int packageCount = mPackages.size(); 16566 for (int i = 0; i < packageCount; i++) { 16567 PackageParser.Package pkg = mPackages.valueAt(i); 16568 PackageSetting ps = (PackageSetting) pkg.mExtras; 16569 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16570 } 16571 } 16572 16573 private void resetNetworkPolicies(int userId) { 16574 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16575 } 16576 16577 /** 16578 * Reverts user permission state changes (permissions and flags). 16579 * 16580 * @param ps The package for which to reset. 16581 * @param userId The device user for which to do a reset. 16582 */ 16583 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16584 final PackageSetting ps, final int userId) { 16585 if (ps.pkg == null) { 16586 return; 16587 } 16588 16589 // These are flags that can change base on user actions. 16590 final int userSettableMask = FLAG_PERMISSION_USER_SET 16591 | FLAG_PERMISSION_USER_FIXED 16592 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16593 | FLAG_PERMISSION_REVIEW_REQUIRED; 16594 16595 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16596 | FLAG_PERMISSION_POLICY_FIXED; 16597 16598 boolean writeInstallPermissions = false; 16599 boolean writeRuntimePermissions = false; 16600 16601 final int permissionCount = ps.pkg.requestedPermissions.size(); 16602 for (int i = 0; i < permissionCount; i++) { 16603 String permission = ps.pkg.requestedPermissions.get(i); 16604 16605 BasePermission bp = mSettings.mPermissions.get(permission); 16606 if (bp == null) { 16607 continue; 16608 } 16609 16610 // If shared user we just reset the state to which only this app contributed. 16611 if (ps.sharedUser != null) { 16612 boolean used = false; 16613 final int packageCount = ps.sharedUser.packages.size(); 16614 for (int j = 0; j < packageCount; j++) { 16615 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16616 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16617 && pkg.pkg.requestedPermissions.contains(permission)) { 16618 used = true; 16619 break; 16620 } 16621 } 16622 if (used) { 16623 continue; 16624 } 16625 } 16626 16627 PermissionsState permissionsState = ps.getPermissionsState(); 16628 16629 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16630 16631 // Always clear the user settable flags. 16632 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16633 bp.name) != null; 16634 // If permission review is enabled and this is a legacy app, mark the 16635 // permission as requiring a review as this is the initial state. 16636 int flags = 0; 16637 if (Build.PERMISSIONS_REVIEW_REQUIRED 16638 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16639 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16640 } 16641 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16642 if (hasInstallState) { 16643 writeInstallPermissions = true; 16644 } else { 16645 writeRuntimePermissions = true; 16646 } 16647 } 16648 16649 // Below is only runtime permission handling. 16650 if (!bp.isRuntime()) { 16651 continue; 16652 } 16653 16654 // Never clobber system or policy. 16655 if ((oldFlags & policyOrSystemFlags) != 0) { 16656 continue; 16657 } 16658 16659 // If this permission was granted by default, make sure it is. 16660 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16661 if (permissionsState.grantRuntimePermission(bp, userId) 16662 != PERMISSION_OPERATION_FAILURE) { 16663 writeRuntimePermissions = true; 16664 } 16665 // If permission review is enabled the permissions for a legacy apps 16666 // are represented as constantly granted runtime ones, so don't revoke. 16667 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16668 // Otherwise, reset the permission. 16669 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16670 switch (revokeResult) { 16671 case PERMISSION_OPERATION_SUCCESS: 16672 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16673 writeRuntimePermissions = true; 16674 final int appId = ps.appId; 16675 mHandler.post(new Runnable() { 16676 @Override 16677 public void run() { 16678 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16679 } 16680 }); 16681 } break; 16682 } 16683 } 16684 } 16685 16686 // Synchronously write as we are taking permissions away. 16687 if (writeRuntimePermissions) { 16688 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16689 } 16690 16691 // Synchronously write as we are taking permissions away. 16692 if (writeInstallPermissions) { 16693 mSettings.writeLPr(); 16694 } 16695 } 16696 16697 /** 16698 * Remove entries from the keystore daemon. Will only remove it if the 16699 * {@code appId} is valid. 16700 */ 16701 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16702 if (appId < 0) { 16703 return; 16704 } 16705 16706 final KeyStore keyStore = KeyStore.getInstance(); 16707 if (keyStore != null) { 16708 if (userId == UserHandle.USER_ALL) { 16709 for (final int individual : sUserManager.getUserIds()) { 16710 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16711 } 16712 } else { 16713 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16714 } 16715 } else { 16716 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16717 } 16718 } 16719 16720 @Override 16721 public void deleteApplicationCacheFiles(final String packageName, 16722 final IPackageDataObserver observer) { 16723 final int userId = UserHandle.getCallingUserId(); 16724 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16725 } 16726 16727 @Override 16728 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16729 final IPackageDataObserver observer) { 16730 mContext.enforceCallingOrSelfPermission( 16731 android.Manifest.permission.DELETE_CACHE_FILES, null); 16732 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16733 /* requireFullPermission= */ true, /* checkShell= */ false, 16734 "delete application cache files"); 16735 16736 final PackageParser.Package pkg; 16737 synchronized (mPackages) { 16738 pkg = mPackages.get(packageName); 16739 } 16740 16741 // Queue up an async operation since the package deletion may take a little while. 16742 mHandler.post(new Runnable() { 16743 public void run() { 16744 synchronized (mInstallLock) { 16745 final int flags = StorageManager.FLAG_STORAGE_DE 16746 | StorageManager.FLAG_STORAGE_CE; 16747 // We're only clearing cache files, so we don't care if the 16748 // app is unfrozen and still able to run 16749 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16750 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16751 } 16752 clearExternalStorageDataSync(packageName, userId, false); 16753 if (observer != null) { 16754 try { 16755 observer.onRemoveCompleted(packageName, true); 16756 } catch (RemoteException e) { 16757 Log.i(TAG, "Observer no longer exists."); 16758 } 16759 } 16760 } 16761 }); 16762 } 16763 16764 @Override 16765 public void getPackageSizeInfo(final String packageName, int userHandle, 16766 final IPackageStatsObserver observer) { 16767 mContext.enforceCallingOrSelfPermission( 16768 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16769 if (packageName == null) { 16770 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16771 } 16772 16773 PackageStats stats = new PackageStats(packageName, userHandle); 16774 16775 /* 16776 * Queue up an async operation since the package measurement may take a 16777 * little while. 16778 */ 16779 Message msg = mHandler.obtainMessage(INIT_COPY); 16780 msg.obj = new MeasureParams(stats, observer); 16781 mHandler.sendMessage(msg); 16782 } 16783 16784 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16785 final PackageSetting ps; 16786 synchronized (mPackages) { 16787 ps = mSettings.mPackages.get(packageName); 16788 if (ps == null) { 16789 Slog.w(TAG, "Failed to find settings for " + packageName); 16790 return false; 16791 } 16792 } 16793 try { 16794 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16795 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16796 ps.getCeDataInode(userId), ps.codePathString, stats); 16797 } catch (InstallerException e) { 16798 Slog.w(TAG, String.valueOf(e)); 16799 return false; 16800 } 16801 16802 // For now, ignore code size of packages on system partition 16803 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16804 stats.codeSize = 0; 16805 } 16806 16807 return true; 16808 } 16809 16810 private int getUidTargetSdkVersionLockedLPr(int uid) { 16811 Object obj = mSettings.getUserIdLPr(uid); 16812 if (obj instanceof SharedUserSetting) { 16813 final SharedUserSetting sus = (SharedUserSetting) obj; 16814 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16815 final Iterator<PackageSetting> it = sus.packages.iterator(); 16816 while (it.hasNext()) { 16817 final PackageSetting ps = it.next(); 16818 if (ps.pkg != null) { 16819 int v = ps.pkg.applicationInfo.targetSdkVersion; 16820 if (v < vers) vers = v; 16821 } 16822 } 16823 return vers; 16824 } else if (obj instanceof PackageSetting) { 16825 final PackageSetting ps = (PackageSetting) obj; 16826 if (ps.pkg != null) { 16827 return ps.pkg.applicationInfo.targetSdkVersion; 16828 } 16829 } 16830 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16831 } 16832 16833 @Override 16834 public void addPreferredActivity(IntentFilter filter, int match, 16835 ComponentName[] set, ComponentName activity, int userId) { 16836 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16837 "Adding preferred"); 16838 } 16839 16840 private void addPreferredActivityInternal(IntentFilter filter, int match, 16841 ComponentName[] set, ComponentName activity, boolean always, int userId, 16842 String opname) { 16843 // writer 16844 int callingUid = Binder.getCallingUid(); 16845 enforceCrossUserPermission(callingUid, userId, 16846 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16847 if (filter.countActions() == 0) { 16848 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16849 return; 16850 } 16851 synchronized (mPackages) { 16852 if (mContext.checkCallingOrSelfPermission( 16853 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16854 != PackageManager.PERMISSION_GRANTED) { 16855 if (getUidTargetSdkVersionLockedLPr(callingUid) 16856 < Build.VERSION_CODES.FROYO) { 16857 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16858 + callingUid); 16859 return; 16860 } 16861 mContext.enforceCallingOrSelfPermission( 16862 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16863 } 16864 16865 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16866 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16867 + userId + ":"); 16868 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16869 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16870 scheduleWritePackageRestrictionsLocked(userId); 16871 } 16872 } 16873 16874 @Override 16875 public void replacePreferredActivity(IntentFilter filter, int match, 16876 ComponentName[] set, ComponentName activity, int userId) { 16877 if (filter.countActions() != 1) { 16878 throw new IllegalArgumentException( 16879 "replacePreferredActivity expects filter to have only 1 action."); 16880 } 16881 if (filter.countDataAuthorities() != 0 16882 || filter.countDataPaths() != 0 16883 || filter.countDataSchemes() > 1 16884 || filter.countDataTypes() != 0) { 16885 throw new IllegalArgumentException( 16886 "replacePreferredActivity expects filter to have no data authorities, " + 16887 "paths, or types; and at most one scheme."); 16888 } 16889 16890 final int callingUid = Binder.getCallingUid(); 16891 enforceCrossUserPermission(callingUid, userId, 16892 true /* requireFullPermission */, false /* checkShell */, 16893 "replace preferred activity"); 16894 synchronized (mPackages) { 16895 if (mContext.checkCallingOrSelfPermission( 16896 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16897 != PackageManager.PERMISSION_GRANTED) { 16898 if (getUidTargetSdkVersionLockedLPr(callingUid) 16899 < Build.VERSION_CODES.FROYO) { 16900 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16901 + Binder.getCallingUid()); 16902 return; 16903 } 16904 mContext.enforceCallingOrSelfPermission( 16905 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16906 } 16907 16908 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16909 if (pir != null) { 16910 // Get all of the existing entries that exactly match this filter. 16911 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16912 if (existing != null && existing.size() == 1) { 16913 PreferredActivity cur = existing.get(0); 16914 if (DEBUG_PREFERRED) { 16915 Slog.i(TAG, "Checking replace of preferred:"); 16916 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16917 if (!cur.mPref.mAlways) { 16918 Slog.i(TAG, " -- CUR; not mAlways!"); 16919 } else { 16920 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16921 Slog.i(TAG, " -- CUR: mSet=" 16922 + Arrays.toString(cur.mPref.mSetComponents)); 16923 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16924 Slog.i(TAG, " -- NEW: mMatch=" 16925 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16926 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16927 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16928 } 16929 } 16930 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16931 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16932 && cur.mPref.sameSet(set)) { 16933 // Setting the preferred activity to what it happens to be already 16934 if (DEBUG_PREFERRED) { 16935 Slog.i(TAG, "Replacing with same preferred activity " 16936 + cur.mPref.mShortComponent + " for user " 16937 + userId + ":"); 16938 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16939 } 16940 return; 16941 } 16942 } 16943 16944 if (existing != null) { 16945 if (DEBUG_PREFERRED) { 16946 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16947 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16948 } 16949 for (int i = 0; i < existing.size(); i++) { 16950 PreferredActivity pa = existing.get(i); 16951 if (DEBUG_PREFERRED) { 16952 Slog.i(TAG, "Removing existing preferred activity " 16953 + pa.mPref.mComponent + ":"); 16954 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16955 } 16956 pir.removeFilter(pa); 16957 } 16958 } 16959 } 16960 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16961 "Replacing preferred"); 16962 } 16963 } 16964 16965 @Override 16966 public void clearPackagePreferredActivities(String packageName) { 16967 final int uid = Binder.getCallingUid(); 16968 // writer 16969 synchronized (mPackages) { 16970 PackageParser.Package pkg = mPackages.get(packageName); 16971 if (pkg == null || pkg.applicationInfo.uid != uid) { 16972 if (mContext.checkCallingOrSelfPermission( 16973 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16974 != PackageManager.PERMISSION_GRANTED) { 16975 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16976 < Build.VERSION_CODES.FROYO) { 16977 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16978 + Binder.getCallingUid()); 16979 return; 16980 } 16981 mContext.enforceCallingOrSelfPermission( 16982 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16983 } 16984 } 16985 16986 int user = UserHandle.getCallingUserId(); 16987 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16988 scheduleWritePackageRestrictionsLocked(user); 16989 } 16990 } 16991 } 16992 16993 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16994 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16995 ArrayList<PreferredActivity> removed = null; 16996 boolean changed = false; 16997 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16998 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16999 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17000 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17001 continue; 17002 } 17003 Iterator<PreferredActivity> it = pir.filterIterator(); 17004 while (it.hasNext()) { 17005 PreferredActivity pa = it.next(); 17006 // Mark entry for removal only if it matches the package name 17007 // and the entry is of type "always". 17008 if (packageName == null || 17009 (pa.mPref.mComponent.getPackageName().equals(packageName) 17010 && pa.mPref.mAlways)) { 17011 if (removed == null) { 17012 removed = new ArrayList<PreferredActivity>(); 17013 } 17014 removed.add(pa); 17015 } 17016 } 17017 if (removed != null) { 17018 for (int j=0; j<removed.size(); j++) { 17019 PreferredActivity pa = removed.get(j); 17020 pir.removeFilter(pa); 17021 } 17022 changed = true; 17023 } 17024 } 17025 return changed; 17026 } 17027 17028 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17029 private void clearIntentFilterVerificationsLPw(int userId) { 17030 final int packageCount = mPackages.size(); 17031 for (int i = 0; i < packageCount; i++) { 17032 PackageParser.Package pkg = mPackages.valueAt(i); 17033 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17034 } 17035 } 17036 17037 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17038 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17039 if (userId == UserHandle.USER_ALL) { 17040 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17041 sUserManager.getUserIds())) { 17042 for (int oneUserId : sUserManager.getUserIds()) { 17043 scheduleWritePackageRestrictionsLocked(oneUserId); 17044 } 17045 } 17046 } else { 17047 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17048 scheduleWritePackageRestrictionsLocked(userId); 17049 } 17050 } 17051 } 17052 17053 void clearDefaultBrowserIfNeeded(String packageName) { 17054 for (int oneUserId : sUserManager.getUserIds()) { 17055 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17056 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17057 if (packageName.equals(defaultBrowserPackageName)) { 17058 setDefaultBrowserPackageName(null, oneUserId); 17059 } 17060 } 17061 } 17062 17063 @Override 17064 public void resetApplicationPreferences(int userId) { 17065 mContext.enforceCallingOrSelfPermission( 17066 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17067 final long identity = Binder.clearCallingIdentity(); 17068 // writer 17069 try { 17070 synchronized (mPackages) { 17071 clearPackagePreferredActivitiesLPw(null, userId); 17072 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17073 // TODO: We have to reset the default SMS and Phone. This requires 17074 // significant refactoring to keep all default apps in the package 17075 // manager (cleaner but more work) or have the services provide 17076 // callbacks to the package manager to request a default app reset. 17077 applyFactoryDefaultBrowserLPw(userId); 17078 clearIntentFilterVerificationsLPw(userId); 17079 primeDomainVerificationsLPw(userId); 17080 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17081 scheduleWritePackageRestrictionsLocked(userId); 17082 } 17083 resetNetworkPolicies(userId); 17084 } finally { 17085 Binder.restoreCallingIdentity(identity); 17086 } 17087 } 17088 17089 @Override 17090 public int getPreferredActivities(List<IntentFilter> outFilters, 17091 List<ComponentName> outActivities, String packageName) { 17092 17093 int num = 0; 17094 final int userId = UserHandle.getCallingUserId(); 17095 // reader 17096 synchronized (mPackages) { 17097 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17098 if (pir != null) { 17099 final Iterator<PreferredActivity> it = pir.filterIterator(); 17100 while (it.hasNext()) { 17101 final PreferredActivity pa = it.next(); 17102 if (packageName == null 17103 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17104 && pa.mPref.mAlways)) { 17105 if (outFilters != null) { 17106 outFilters.add(new IntentFilter(pa)); 17107 } 17108 if (outActivities != null) { 17109 outActivities.add(pa.mPref.mComponent); 17110 } 17111 } 17112 } 17113 } 17114 } 17115 17116 return num; 17117 } 17118 17119 @Override 17120 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17121 int userId) { 17122 int callingUid = Binder.getCallingUid(); 17123 if (callingUid != Process.SYSTEM_UID) { 17124 throw new SecurityException( 17125 "addPersistentPreferredActivity can only be run by the system"); 17126 } 17127 if (filter.countActions() == 0) { 17128 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17129 return; 17130 } 17131 synchronized (mPackages) { 17132 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17133 ":"); 17134 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17135 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17136 new PersistentPreferredActivity(filter, activity)); 17137 scheduleWritePackageRestrictionsLocked(userId); 17138 } 17139 } 17140 17141 @Override 17142 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17143 int callingUid = Binder.getCallingUid(); 17144 if (callingUid != Process.SYSTEM_UID) { 17145 throw new SecurityException( 17146 "clearPackagePersistentPreferredActivities can only be run by the system"); 17147 } 17148 ArrayList<PersistentPreferredActivity> removed = null; 17149 boolean changed = false; 17150 synchronized (mPackages) { 17151 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17152 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17153 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17154 .valueAt(i); 17155 if (userId != thisUserId) { 17156 continue; 17157 } 17158 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17159 while (it.hasNext()) { 17160 PersistentPreferredActivity ppa = it.next(); 17161 // Mark entry for removal only if it matches the package name. 17162 if (ppa.mComponent.getPackageName().equals(packageName)) { 17163 if (removed == null) { 17164 removed = new ArrayList<PersistentPreferredActivity>(); 17165 } 17166 removed.add(ppa); 17167 } 17168 } 17169 if (removed != null) { 17170 for (int j=0; j<removed.size(); j++) { 17171 PersistentPreferredActivity ppa = removed.get(j); 17172 ppir.removeFilter(ppa); 17173 } 17174 changed = true; 17175 } 17176 } 17177 17178 if (changed) { 17179 scheduleWritePackageRestrictionsLocked(userId); 17180 } 17181 } 17182 } 17183 17184 /** 17185 * Common machinery for picking apart a restored XML blob and passing 17186 * it to a caller-supplied functor to be applied to the running system. 17187 */ 17188 private void restoreFromXml(XmlPullParser parser, int userId, 17189 String expectedStartTag, BlobXmlRestorer functor) 17190 throws IOException, XmlPullParserException { 17191 int type; 17192 while ((type = parser.next()) != XmlPullParser.START_TAG 17193 && type != XmlPullParser.END_DOCUMENT) { 17194 } 17195 if (type != XmlPullParser.START_TAG) { 17196 // oops didn't find a start tag?! 17197 if (DEBUG_BACKUP) { 17198 Slog.e(TAG, "Didn't find start tag during restore"); 17199 } 17200 return; 17201 } 17202Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17203 // this is supposed to be TAG_PREFERRED_BACKUP 17204 if (!expectedStartTag.equals(parser.getName())) { 17205 if (DEBUG_BACKUP) { 17206 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17207 } 17208 return; 17209 } 17210 17211 // skip interfering stuff, then we're aligned with the backing implementation 17212 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17213Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17214 functor.apply(parser, userId); 17215 } 17216 17217 private interface BlobXmlRestorer { 17218 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17219 } 17220 17221 /** 17222 * Non-Binder method, support for the backup/restore mechanism: write the 17223 * full set of preferred activities in its canonical XML format. Returns the 17224 * XML output as a byte array, or null if there is none. 17225 */ 17226 @Override 17227 public byte[] getPreferredActivityBackup(int userId) { 17228 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17229 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17230 } 17231 17232 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17233 try { 17234 final XmlSerializer serializer = new FastXmlSerializer(); 17235 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17236 serializer.startDocument(null, true); 17237 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17238 17239 synchronized (mPackages) { 17240 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17241 } 17242 17243 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17244 serializer.endDocument(); 17245 serializer.flush(); 17246 } catch (Exception e) { 17247 if (DEBUG_BACKUP) { 17248 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17249 } 17250 return null; 17251 } 17252 17253 return dataStream.toByteArray(); 17254 } 17255 17256 @Override 17257 public void restorePreferredActivities(byte[] backup, int userId) { 17258 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17259 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17260 } 17261 17262 try { 17263 final XmlPullParser parser = Xml.newPullParser(); 17264 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17265 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17266 new BlobXmlRestorer() { 17267 @Override 17268 public void apply(XmlPullParser parser, int userId) 17269 throws XmlPullParserException, IOException { 17270 synchronized (mPackages) { 17271 mSettings.readPreferredActivitiesLPw(parser, userId); 17272 } 17273 } 17274 } ); 17275 } catch (Exception e) { 17276 if (DEBUG_BACKUP) { 17277 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17278 } 17279 } 17280 } 17281 17282 /** 17283 * Non-Binder method, support for the backup/restore mechanism: write the 17284 * default browser (etc) settings in its canonical XML format. Returns the default 17285 * browser XML representation as a byte array, or null if there is none. 17286 */ 17287 @Override 17288 public byte[] getDefaultAppsBackup(int userId) { 17289 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17290 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17291 } 17292 17293 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17294 try { 17295 final XmlSerializer serializer = new FastXmlSerializer(); 17296 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17297 serializer.startDocument(null, true); 17298 serializer.startTag(null, TAG_DEFAULT_APPS); 17299 17300 synchronized (mPackages) { 17301 mSettings.writeDefaultAppsLPr(serializer, userId); 17302 } 17303 17304 serializer.endTag(null, TAG_DEFAULT_APPS); 17305 serializer.endDocument(); 17306 serializer.flush(); 17307 } catch (Exception e) { 17308 if (DEBUG_BACKUP) { 17309 Slog.e(TAG, "Unable to write default apps for backup", e); 17310 } 17311 return null; 17312 } 17313 17314 return dataStream.toByteArray(); 17315 } 17316 17317 @Override 17318 public void restoreDefaultApps(byte[] backup, int userId) { 17319 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17320 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17321 } 17322 17323 try { 17324 final XmlPullParser parser = Xml.newPullParser(); 17325 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17326 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17327 new BlobXmlRestorer() { 17328 @Override 17329 public void apply(XmlPullParser parser, int userId) 17330 throws XmlPullParserException, IOException { 17331 synchronized (mPackages) { 17332 mSettings.readDefaultAppsLPw(parser, userId); 17333 } 17334 } 17335 } ); 17336 } catch (Exception e) { 17337 if (DEBUG_BACKUP) { 17338 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17339 } 17340 } 17341 } 17342 17343 @Override 17344 public byte[] getIntentFilterVerificationBackup(int userId) { 17345 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17346 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17347 } 17348 17349 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17350 try { 17351 final XmlSerializer serializer = new FastXmlSerializer(); 17352 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17353 serializer.startDocument(null, true); 17354 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17355 17356 synchronized (mPackages) { 17357 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17358 } 17359 17360 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17361 serializer.endDocument(); 17362 serializer.flush(); 17363 } catch (Exception e) { 17364 if (DEBUG_BACKUP) { 17365 Slog.e(TAG, "Unable to write default apps for backup", e); 17366 } 17367 return null; 17368 } 17369 17370 return dataStream.toByteArray(); 17371 } 17372 17373 @Override 17374 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17375 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17376 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17377 } 17378 17379 try { 17380 final XmlPullParser parser = Xml.newPullParser(); 17381 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17382 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17383 new BlobXmlRestorer() { 17384 @Override 17385 public void apply(XmlPullParser parser, int userId) 17386 throws XmlPullParserException, IOException { 17387 synchronized (mPackages) { 17388 mSettings.readAllDomainVerificationsLPr(parser, userId); 17389 mSettings.writeLPr(); 17390 } 17391 } 17392 } ); 17393 } catch (Exception e) { 17394 if (DEBUG_BACKUP) { 17395 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17396 } 17397 } 17398 } 17399 17400 @Override 17401 public byte[] getPermissionGrantBackup(int userId) { 17402 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17403 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17404 } 17405 17406 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17407 try { 17408 final XmlSerializer serializer = new FastXmlSerializer(); 17409 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17410 serializer.startDocument(null, true); 17411 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17412 17413 synchronized (mPackages) { 17414 serializeRuntimePermissionGrantsLPr(serializer, userId); 17415 } 17416 17417 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17418 serializer.endDocument(); 17419 serializer.flush(); 17420 } catch (Exception e) { 17421 if (DEBUG_BACKUP) { 17422 Slog.e(TAG, "Unable to write default apps for backup", e); 17423 } 17424 return null; 17425 } 17426 17427 return dataStream.toByteArray(); 17428 } 17429 17430 @Override 17431 public void restorePermissionGrants(byte[] backup, int userId) { 17432 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17433 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17434 } 17435 17436 try { 17437 final XmlPullParser parser = Xml.newPullParser(); 17438 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17439 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17440 new BlobXmlRestorer() { 17441 @Override 17442 public void apply(XmlPullParser parser, int userId) 17443 throws XmlPullParserException, IOException { 17444 synchronized (mPackages) { 17445 processRestoredPermissionGrantsLPr(parser, userId); 17446 } 17447 } 17448 } ); 17449 } catch (Exception e) { 17450 if (DEBUG_BACKUP) { 17451 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17452 } 17453 } 17454 } 17455 17456 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17457 throws IOException { 17458 serializer.startTag(null, TAG_ALL_GRANTS); 17459 17460 final int N = mSettings.mPackages.size(); 17461 for (int i = 0; i < N; i++) { 17462 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17463 boolean pkgGrantsKnown = false; 17464 17465 PermissionsState packagePerms = ps.getPermissionsState(); 17466 17467 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17468 final int grantFlags = state.getFlags(); 17469 // only look at grants that are not system/policy fixed 17470 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17471 final boolean isGranted = state.isGranted(); 17472 // And only back up the user-twiddled state bits 17473 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17474 final String packageName = mSettings.mPackages.keyAt(i); 17475 if (!pkgGrantsKnown) { 17476 serializer.startTag(null, TAG_GRANT); 17477 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17478 pkgGrantsKnown = true; 17479 } 17480 17481 final boolean userSet = 17482 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17483 final boolean userFixed = 17484 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17485 final boolean revoke = 17486 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17487 17488 serializer.startTag(null, TAG_PERMISSION); 17489 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17490 if (isGranted) { 17491 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17492 } 17493 if (userSet) { 17494 serializer.attribute(null, ATTR_USER_SET, "true"); 17495 } 17496 if (userFixed) { 17497 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17498 } 17499 if (revoke) { 17500 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17501 } 17502 serializer.endTag(null, TAG_PERMISSION); 17503 } 17504 } 17505 } 17506 17507 if (pkgGrantsKnown) { 17508 serializer.endTag(null, TAG_GRANT); 17509 } 17510 } 17511 17512 serializer.endTag(null, TAG_ALL_GRANTS); 17513 } 17514 17515 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17516 throws XmlPullParserException, IOException { 17517 String pkgName = null; 17518 int outerDepth = parser.getDepth(); 17519 int type; 17520 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17521 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17522 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17523 continue; 17524 } 17525 17526 final String tagName = parser.getName(); 17527 if (tagName.equals(TAG_GRANT)) { 17528 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17529 if (DEBUG_BACKUP) { 17530 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17531 } 17532 } else if (tagName.equals(TAG_PERMISSION)) { 17533 17534 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17535 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17536 17537 int newFlagSet = 0; 17538 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17539 newFlagSet |= FLAG_PERMISSION_USER_SET; 17540 } 17541 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17542 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17543 } 17544 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17545 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17546 } 17547 if (DEBUG_BACKUP) { 17548 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17549 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17550 } 17551 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17552 if (ps != null) { 17553 // Already installed so we apply the grant immediately 17554 if (DEBUG_BACKUP) { 17555 Slog.v(TAG, " + already installed; applying"); 17556 } 17557 PermissionsState perms = ps.getPermissionsState(); 17558 BasePermission bp = mSettings.mPermissions.get(permName); 17559 if (bp != null) { 17560 if (isGranted) { 17561 perms.grantRuntimePermission(bp, userId); 17562 } 17563 if (newFlagSet != 0) { 17564 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17565 } 17566 } 17567 } else { 17568 // Need to wait for post-restore install to apply the grant 17569 if (DEBUG_BACKUP) { 17570 Slog.v(TAG, " - not yet installed; saving for later"); 17571 } 17572 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17573 isGranted, newFlagSet, userId); 17574 } 17575 } else { 17576 PackageManagerService.reportSettingsProblem(Log.WARN, 17577 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17578 XmlUtils.skipCurrentTag(parser); 17579 } 17580 } 17581 17582 scheduleWriteSettingsLocked(); 17583 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17584 } 17585 17586 @Override 17587 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17588 int sourceUserId, int targetUserId, int flags) { 17589 mContext.enforceCallingOrSelfPermission( 17590 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17591 int callingUid = Binder.getCallingUid(); 17592 enforceOwnerRights(ownerPackage, callingUid); 17593 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17594 if (intentFilter.countActions() == 0) { 17595 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17596 return; 17597 } 17598 synchronized (mPackages) { 17599 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17600 ownerPackage, targetUserId, flags); 17601 CrossProfileIntentResolver resolver = 17602 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17603 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17604 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17605 if (existing != null) { 17606 int size = existing.size(); 17607 for (int i = 0; i < size; i++) { 17608 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17609 return; 17610 } 17611 } 17612 } 17613 resolver.addFilter(newFilter); 17614 scheduleWritePackageRestrictionsLocked(sourceUserId); 17615 } 17616 } 17617 17618 @Override 17619 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17620 mContext.enforceCallingOrSelfPermission( 17621 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17622 int callingUid = Binder.getCallingUid(); 17623 enforceOwnerRights(ownerPackage, callingUid); 17624 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17625 synchronized (mPackages) { 17626 CrossProfileIntentResolver resolver = 17627 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17628 ArraySet<CrossProfileIntentFilter> set = 17629 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17630 for (CrossProfileIntentFilter filter : set) { 17631 if (filter.getOwnerPackage().equals(ownerPackage)) { 17632 resolver.removeFilter(filter); 17633 } 17634 } 17635 scheduleWritePackageRestrictionsLocked(sourceUserId); 17636 } 17637 } 17638 17639 // Enforcing that callingUid is owning pkg on userId 17640 private void enforceOwnerRights(String pkg, int callingUid) { 17641 // The system owns everything. 17642 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17643 return; 17644 } 17645 int callingUserId = UserHandle.getUserId(callingUid); 17646 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17647 if (pi == null) { 17648 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17649 + callingUserId); 17650 } 17651 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17652 throw new SecurityException("Calling uid " + callingUid 17653 + " does not own package " + pkg); 17654 } 17655 } 17656 17657 @Override 17658 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17659 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17660 } 17661 17662 private Intent getHomeIntent() { 17663 Intent intent = new Intent(Intent.ACTION_MAIN); 17664 intent.addCategory(Intent.CATEGORY_HOME); 17665 return intent; 17666 } 17667 17668 private IntentFilter getHomeFilter() { 17669 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17670 filter.addCategory(Intent.CATEGORY_HOME); 17671 filter.addCategory(Intent.CATEGORY_DEFAULT); 17672 return filter; 17673 } 17674 17675 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17676 int userId) { 17677 Intent intent = getHomeIntent(); 17678 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17679 PackageManager.GET_META_DATA, userId); 17680 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17681 true, false, false, userId); 17682 17683 allHomeCandidates.clear(); 17684 if (list != null) { 17685 for (ResolveInfo ri : list) { 17686 allHomeCandidates.add(ri); 17687 } 17688 } 17689 return (preferred == null || preferred.activityInfo == null) 17690 ? null 17691 : new ComponentName(preferred.activityInfo.packageName, 17692 preferred.activityInfo.name); 17693 } 17694 17695 @Override 17696 public void setHomeActivity(ComponentName comp, int userId) { 17697 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17698 getHomeActivitiesAsUser(homeActivities, userId); 17699 17700 boolean found = false; 17701 17702 final int size = homeActivities.size(); 17703 final ComponentName[] set = new ComponentName[size]; 17704 for (int i = 0; i < size; i++) { 17705 final ResolveInfo candidate = homeActivities.get(i); 17706 final ActivityInfo info = candidate.activityInfo; 17707 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17708 set[i] = activityName; 17709 if (!found && activityName.equals(comp)) { 17710 found = true; 17711 } 17712 } 17713 if (!found) { 17714 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17715 + userId); 17716 } 17717 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17718 set, comp, userId); 17719 } 17720 17721 private @Nullable String getSetupWizardPackageName() { 17722 final Intent intent = new Intent(Intent.ACTION_MAIN); 17723 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17724 17725 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17726 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17727 | MATCH_DISABLED_COMPONENTS, 17728 UserHandle.myUserId()); 17729 if (matches.size() == 1) { 17730 return matches.get(0).getComponentInfo().packageName; 17731 } else { 17732 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17733 + ": matches=" + matches); 17734 return null; 17735 } 17736 } 17737 17738 @Override 17739 public void setApplicationEnabledSetting(String appPackageName, 17740 int newState, int flags, int userId, String callingPackage) { 17741 if (!sUserManager.exists(userId)) return; 17742 if (callingPackage == null) { 17743 callingPackage = Integer.toString(Binder.getCallingUid()); 17744 } 17745 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17746 } 17747 17748 @Override 17749 public void setComponentEnabledSetting(ComponentName componentName, 17750 int newState, int flags, int userId) { 17751 if (!sUserManager.exists(userId)) return; 17752 setEnabledSetting(componentName.getPackageName(), 17753 componentName.getClassName(), newState, flags, userId, null); 17754 } 17755 17756 private void setEnabledSetting(final String packageName, String className, int newState, 17757 final int flags, int userId, String callingPackage) { 17758 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17759 || newState == COMPONENT_ENABLED_STATE_ENABLED 17760 || newState == COMPONENT_ENABLED_STATE_DISABLED 17761 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17762 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17763 throw new IllegalArgumentException("Invalid new component state: " 17764 + newState); 17765 } 17766 PackageSetting pkgSetting; 17767 final int uid = Binder.getCallingUid(); 17768 final int permission; 17769 if (uid == Process.SYSTEM_UID) { 17770 permission = PackageManager.PERMISSION_GRANTED; 17771 } else { 17772 permission = mContext.checkCallingOrSelfPermission( 17773 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17774 } 17775 enforceCrossUserPermission(uid, userId, 17776 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17777 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17778 boolean sendNow = false; 17779 boolean isApp = (className == null); 17780 String componentName = isApp ? packageName : className; 17781 int packageUid = -1; 17782 ArrayList<String> components; 17783 17784 // writer 17785 synchronized (mPackages) { 17786 pkgSetting = mSettings.mPackages.get(packageName); 17787 if (pkgSetting == null) { 17788 if (className == null) { 17789 throw new IllegalArgumentException("Unknown package: " + packageName); 17790 } 17791 throw new IllegalArgumentException( 17792 "Unknown component: " + packageName + "/" + className); 17793 } 17794 } 17795 17796 // Limit who can change which apps 17797 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17798 // Don't allow apps that don't have permission to modify other apps 17799 if (!allowedByPermission) { 17800 throw new SecurityException( 17801 "Permission Denial: attempt to change component state from pid=" 17802 + Binder.getCallingPid() 17803 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17804 } 17805 // Don't allow changing protected packages. 17806 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17807 throw new SecurityException("Cannot disable a protected package: " + packageName); 17808 } 17809 } 17810 17811 synchronized (mPackages) { 17812 if (uid == Process.SHELL_UID) { 17813 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17814 int oldState = pkgSetting.getEnabled(userId); 17815 if (className == null 17816 && 17817 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17818 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17819 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17820 && 17821 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17822 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17823 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17824 // ok 17825 } else { 17826 throw new SecurityException( 17827 "Shell cannot change component state for " + packageName + "/" 17828 + className + " to " + newState); 17829 } 17830 } 17831 if (className == null) { 17832 // We're dealing with an application/package level state change 17833 if (pkgSetting.getEnabled(userId) == newState) { 17834 // Nothing to do 17835 return; 17836 } 17837 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17838 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17839 // Don't care about who enables an app. 17840 callingPackage = null; 17841 } 17842 pkgSetting.setEnabled(newState, userId, callingPackage); 17843 // pkgSetting.pkg.mSetEnabled = newState; 17844 } else { 17845 // We're dealing with a component level state change 17846 // First, verify that this is a valid class name. 17847 PackageParser.Package pkg = pkgSetting.pkg; 17848 if (pkg == null || !pkg.hasComponentClassName(className)) { 17849 if (pkg != null && 17850 pkg.applicationInfo.targetSdkVersion >= 17851 Build.VERSION_CODES.JELLY_BEAN) { 17852 throw new IllegalArgumentException("Component class " + className 17853 + " does not exist in " + packageName); 17854 } else { 17855 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17856 + className + " does not exist in " + packageName); 17857 } 17858 } 17859 switch (newState) { 17860 case COMPONENT_ENABLED_STATE_ENABLED: 17861 if (!pkgSetting.enableComponentLPw(className, userId)) { 17862 return; 17863 } 17864 break; 17865 case COMPONENT_ENABLED_STATE_DISABLED: 17866 if (!pkgSetting.disableComponentLPw(className, userId)) { 17867 return; 17868 } 17869 break; 17870 case COMPONENT_ENABLED_STATE_DEFAULT: 17871 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17872 return; 17873 } 17874 break; 17875 default: 17876 Slog.e(TAG, "Invalid new component state: " + newState); 17877 return; 17878 } 17879 } 17880 scheduleWritePackageRestrictionsLocked(userId); 17881 components = mPendingBroadcasts.get(userId, packageName); 17882 final boolean newPackage = components == null; 17883 if (newPackage) { 17884 components = new ArrayList<String>(); 17885 } 17886 if (!components.contains(componentName)) { 17887 components.add(componentName); 17888 } 17889 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17890 sendNow = true; 17891 // Purge entry from pending broadcast list if another one exists already 17892 // since we are sending one right away. 17893 mPendingBroadcasts.remove(userId, packageName); 17894 } else { 17895 if (newPackage) { 17896 mPendingBroadcasts.put(userId, packageName, components); 17897 } 17898 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17899 // Schedule a message 17900 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17901 } 17902 } 17903 } 17904 17905 long callingId = Binder.clearCallingIdentity(); 17906 try { 17907 if (sendNow) { 17908 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17909 sendPackageChangedBroadcast(packageName, 17910 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17911 } 17912 } finally { 17913 Binder.restoreCallingIdentity(callingId); 17914 } 17915 } 17916 17917 @Override 17918 public void flushPackageRestrictionsAsUser(int userId) { 17919 if (!sUserManager.exists(userId)) { 17920 return; 17921 } 17922 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17923 false /* checkShell */, "flushPackageRestrictions"); 17924 synchronized (mPackages) { 17925 mSettings.writePackageRestrictionsLPr(userId); 17926 mDirtyUsers.remove(userId); 17927 if (mDirtyUsers.isEmpty()) { 17928 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17929 } 17930 } 17931 } 17932 17933 private void sendPackageChangedBroadcast(String packageName, 17934 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17935 if (DEBUG_INSTALL) 17936 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17937 + componentNames); 17938 Bundle extras = new Bundle(4); 17939 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17940 String nameList[] = new String[componentNames.size()]; 17941 componentNames.toArray(nameList); 17942 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17943 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17944 extras.putInt(Intent.EXTRA_UID, packageUid); 17945 // If this is not reporting a change of the overall package, then only send it 17946 // to registered receivers. We don't want to launch a swath of apps for every 17947 // little component state change. 17948 final int flags = !componentNames.contains(packageName) 17949 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17950 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17951 new int[] {UserHandle.getUserId(packageUid)}); 17952 } 17953 17954 @Override 17955 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17956 if (!sUserManager.exists(userId)) return; 17957 final int uid = Binder.getCallingUid(); 17958 final int permission = mContext.checkCallingOrSelfPermission( 17959 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17960 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17961 enforceCrossUserPermission(uid, userId, 17962 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17963 // writer 17964 synchronized (mPackages) { 17965 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17966 allowedByPermission, uid, userId)) { 17967 scheduleWritePackageRestrictionsLocked(userId); 17968 } 17969 } 17970 } 17971 17972 @Override 17973 public String getInstallerPackageName(String packageName) { 17974 // reader 17975 synchronized (mPackages) { 17976 return mSettings.getInstallerPackageNameLPr(packageName); 17977 } 17978 } 17979 17980 public boolean isOrphaned(String packageName) { 17981 // reader 17982 synchronized (mPackages) { 17983 return mSettings.isOrphaned(packageName); 17984 } 17985 } 17986 17987 @Override 17988 public int getApplicationEnabledSetting(String packageName, int userId) { 17989 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17990 int uid = Binder.getCallingUid(); 17991 enforceCrossUserPermission(uid, userId, 17992 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17993 // reader 17994 synchronized (mPackages) { 17995 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17996 } 17997 } 17998 17999 @Override 18000 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18001 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18002 int uid = Binder.getCallingUid(); 18003 enforceCrossUserPermission(uid, userId, 18004 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18005 // reader 18006 synchronized (mPackages) { 18007 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18008 } 18009 } 18010 18011 @Override 18012 public void enterSafeMode() { 18013 enforceSystemOrRoot("Only the system can request entering safe mode"); 18014 18015 if (!mSystemReady) { 18016 mSafeMode = true; 18017 } 18018 } 18019 18020 @Override 18021 public void systemReady() { 18022 mSystemReady = true; 18023 18024 // Read the compatibilty setting when the system is ready. 18025 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18026 mContext.getContentResolver(), 18027 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18028 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18029 if (DEBUG_SETTINGS) { 18030 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18031 } 18032 18033 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18034 18035 synchronized (mPackages) { 18036 // Verify that all of the preferred activity components actually 18037 // exist. It is possible for applications to be updated and at 18038 // that point remove a previously declared activity component that 18039 // had been set as a preferred activity. We try to clean this up 18040 // the next time we encounter that preferred activity, but it is 18041 // possible for the user flow to never be able to return to that 18042 // situation so here we do a sanity check to make sure we haven't 18043 // left any junk around. 18044 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18045 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18046 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18047 removed.clear(); 18048 for (PreferredActivity pa : pir.filterSet()) { 18049 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18050 removed.add(pa); 18051 } 18052 } 18053 if (removed.size() > 0) { 18054 for (int r=0; r<removed.size(); r++) { 18055 PreferredActivity pa = removed.get(r); 18056 Slog.w(TAG, "Removing dangling preferred activity: " 18057 + pa.mPref.mComponent); 18058 pir.removeFilter(pa); 18059 } 18060 mSettings.writePackageRestrictionsLPr( 18061 mSettings.mPreferredActivities.keyAt(i)); 18062 } 18063 } 18064 18065 for (int userId : UserManagerService.getInstance().getUserIds()) { 18066 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18067 grantPermissionsUserIds = ArrayUtils.appendInt( 18068 grantPermissionsUserIds, userId); 18069 } 18070 } 18071 } 18072 sUserManager.systemReady(); 18073 18074 // If we upgraded grant all default permissions before kicking off. 18075 for (int userId : grantPermissionsUserIds) { 18076 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18077 } 18078 18079 // Kick off any messages waiting for system ready 18080 if (mPostSystemReadyMessages != null) { 18081 for (Message msg : mPostSystemReadyMessages) { 18082 msg.sendToTarget(); 18083 } 18084 mPostSystemReadyMessages = null; 18085 } 18086 18087 // Watch for external volumes that come and go over time 18088 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18089 storage.registerListener(mStorageListener); 18090 18091 mInstallerService.systemReady(); 18092 mPackageDexOptimizer.systemReady(); 18093 18094 MountServiceInternal mountServiceInternal = LocalServices.getService( 18095 MountServiceInternal.class); 18096 mountServiceInternal.addExternalStoragePolicy( 18097 new MountServiceInternal.ExternalStorageMountPolicy() { 18098 @Override 18099 public int getMountMode(int uid, String packageName) { 18100 if (Process.isIsolated(uid)) { 18101 return Zygote.MOUNT_EXTERNAL_NONE; 18102 } 18103 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18104 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18105 } 18106 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18107 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18108 } 18109 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18110 return Zygote.MOUNT_EXTERNAL_READ; 18111 } 18112 return Zygote.MOUNT_EXTERNAL_WRITE; 18113 } 18114 18115 @Override 18116 public boolean hasExternalStorage(int uid, String packageName) { 18117 return true; 18118 } 18119 }); 18120 18121 // Now that we're mostly running, clean up stale users and apps 18122 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18123 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18124 } 18125 18126 @Override 18127 public boolean isSafeMode() { 18128 return mSafeMode; 18129 } 18130 18131 @Override 18132 public boolean hasSystemUidErrors() { 18133 return mHasSystemUidErrors; 18134 } 18135 18136 static String arrayToString(int[] array) { 18137 StringBuffer buf = new StringBuffer(128); 18138 buf.append('['); 18139 if (array != null) { 18140 for (int i=0; i<array.length; i++) { 18141 if (i > 0) buf.append(", "); 18142 buf.append(array[i]); 18143 } 18144 } 18145 buf.append(']'); 18146 return buf.toString(); 18147 } 18148 18149 static class DumpState { 18150 public static final int DUMP_LIBS = 1 << 0; 18151 public static final int DUMP_FEATURES = 1 << 1; 18152 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18153 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18154 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18155 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18156 public static final int DUMP_PERMISSIONS = 1 << 6; 18157 public static final int DUMP_PACKAGES = 1 << 7; 18158 public static final int DUMP_SHARED_USERS = 1 << 8; 18159 public static final int DUMP_MESSAGES = 1 << 9; 18160 public static final int DUMP_PROVIDERS = 1 << 10; 18161 public static final int DUMP_VERIFIERS = 1 << 11; 18162 public static final int DUMP_PREFERRED = 1 << 12; 18163 public static final int DUMP_PREFERRED_XML = 1 << 13; 18164 public static final int DUMP_KEYSETS = 1 << 14; 18165 public static final int DUMP_VERSION = 1 << 15; 18166 public static final int DUMP_INSTALLS = 1 << 16; 18167 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18168 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18169 public static final int DUMP_FROZEN = 1 << 19; 18170 public static final int DUMP_DEXOPT = 1 << 20; 18171 18172 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18173 18174 private int mTypes; 18175 18176 private int mOptions; 18177 18178 private boolean mTitlePrinted; 18179 18180 private SharedUserSetting mSharedUser; 18181 18182 public boolean isDumping(int type) { 18183 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18184 return true; 18185 } 18186 18187 return (mTypes & type) != 0; 18188 } 18189 18190 public void setDump(int type) { 18191 mTypes |= type; 18192 } 18193 18194 public boolean isOptionEnabled(int option) { 18195 return (mOptions & option) != 0; 18196 } 18197 18198 public void setOptionEnabled(int option) { 18199 mOptions |= option; 18200 } 18201 18202 public boolean onTitlePrinted() { 18203 final boolean printed = mTitlePrinted; 18204 mTitlePrinted = true; 18205 return printed; 18206 } 18207 18208 public boolean getTitlePrinted() { 18209 return mTitlePrinted; 18210 } 18211 18212 public void setTitlePrinted(boolean enabled) { 18213 mTitlePrinted = enabled; 18214 } 18215 18216 public SharedUserSetting getSharedUser() { 18217 return mSharedUser; 18218 } 18219 18220 public void setSharedUser(SharedUserSetting user) { 18221 mSharedUser = user; 18222 } 18223 } 18224 18225 @Override 18226 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18227 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18228 (new PackageManagerShellCommand(this)).exec( 18229 this, in, out, err, args, resultReceiver); 18230 } 18231 18232 @Override 18233 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18234 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18235 != PackageManager.PERMISSION_GRANTED) { 18236 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18237 + Binder.getCallingPid() 18238 + ", uid=" + Binder.getCallingUid() 18239 + " without permission " 18240 + android.Manifest.permission.DUMP); 18241 return; 18242 } 18243 18244 DumpState dumpState = new DumpState(); 18245 boolean fullPreferred = false; 18246 boolean checkin = false; 18247 18248 String packageName = null; 18249 ArraySet<String> permissionNames = null; 18250 18251 int opti = 0; 18252 while (opti < args.length) { 18253 String opt = args[opti]; 18254 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18255 break; 18256 } 18257 opti++; 18258 18259 if ("-a".equals(opt)) { 18260 // Right now we only know how to print all. 18261 } else if ("-h".equals(opt)) { 18262 pw.println("Package manager dump options:"); 18263 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18264 pw.println(" --checkin: dump for a checkin"); 18265 pw.println(" -f: print details of intent filters"); 18266 pw.println(" -h: print this help"); 18267 pw.println(" cmd may be one of:"); 18268 pw.println(" l[ibraries]: list known shared libraries"); 18269 pw.println(" f[eatures]: list device features"); 18270 pw.println(" k[eysets]: print known keysets"); 18271 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18272 pw.println(" perm[issions]: dump permissions"); 18273 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18274 pw.println(" pref[erred]: print preferred package settings"); 18275 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18276 pw.println(" prov[iders]: dump content providers"); 18277 pw.println(" p[ackages]: dump installed packages"); 18278 pw.println(" s[hared-users]: dump shared user IDs"); 18279 pw.println(" m[essages]: print collected runtime messages"); 18280 pw.println(" v[erifiers]: print package verifier info"); 18281 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18282 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18283 pw.println(" version: print database version info"); 18284 pw.println(" write: write current settings now"); 18285 pw.println(" installs: details about install sessions"); 18286 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18287 pw.println(" dexopt: dump dexopt state"); 18288 pw.println(" <package.name>: info about given package"); 18289 return; 18290 } else if ("--checkin".equals(opt)) { 18291 checkin = true; 18292 } else if ("-f".equals(opt)) { 18293 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18294 } else { 18295 pw.println("Unknown argument: " + opt + "; use -h for help"); 18296 } 18297 } 18298 18299 // Is the caller requesting to dump a particular piece of data? 18300 if (opti < args.length) { 18301 String cmd = args[opti]; 18302 opti++; 18303 // Is this a package name? 18304 if ("android".equals(cmd) || cmd.contains(".")) { 18305 packageName = cmd; 18306 // When dumping a single package, we always dump all of its 18307 // filter information since the amount of data will be reasonable. 18308 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18309 } else if ("check-permission".equals(cmd)) { 18310 if (opti >= args.length) { 18311 pw.println("Error: check-permission missing permission argument"); 18312 return; 18313 } 18314 String perm = args[opti]; 18315 opti++; 18316 if (opti >= args.length) { 18317 pw.println("Error: check-permission missing package argument"); 18318 return; 18319 } 18320 String pkg = args[opti]; 18321 opti++; 18322 int user = UserHandle.getUserId(Binder.getCallingUid()); 18323 if (opti < args.length) { 18324 try { 18325 user = Integer.parseInt(args[opti]); 18326 } catch (NumberFormatException e) { 18327 pw.println("Error: check-permission user argument is not a number: " 18328 + args[opti]); 18329 return; 18330 } 18331 } 18332 pw.println(checkPermission(perm, pkg, user)); 18333 return; 18334 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18335 dumpState.setDump(DumpState.DUMP_LIBS); 18336 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18337 dumpState.setDump(DumpState.DUMP_FEATURES); 18338 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18339 if (opti >= args.length) { 18340 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18341 | DumpState.DUMP_SERVICE_RESOLVERS 18342 | DumpState.DUMP_RECEIVER_RESOLVERS 18343 | DumpState.DUMP_CONTENT_RESOLVERS); 18344 } else { 18345 while (opti < args.length) { 18346 String name = args[opti]; 18347 if ("a".equals(name) || "activity".equals(name)) { 18348 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18349 } else if ("s".equals(name) || "service".equals(name)) { 18350 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18351 } else if ("r".equals(name) || "receiver".equals(name)) { 18352 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18353 } else if ("c".equals(name) || "content".equals(name)) { 18354 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18355 } else { 18356 pw.println("Error: unknown resolver table type: " + name); 18357 return; 18358 } 18359 opti++; 18360 } 18361 } 18362 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18363 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18364 } else if ("permission".equals(cmd)) { 18365 if (opti >= args.length) { 18366 pw.println("Error: permission requires permission name"); 18367 return; 18368 } 18369 permissionNames = new ArraySet<>(); 18370 while (opti < args.length) { 18371 permissionNames.add(args[opti]); 18372 opti++; 18373 } 18374 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18375 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18376 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18377 dumpState.setDump(DumpState.DUMP_PREFERRED); 18378 } else if ("preferred-xml".equals(cmd)) { 18379 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18380 if (opti < args.length && "--full".equals(args[opti])) { 18381 fullPreferred = true; 18382 opti++; 18383 } 18384 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18385 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18386 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18387 dumpState.setDump(DumpState.DUMP_PACKAGES); 18388 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18389 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18390 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18391 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18392 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18393 dumpState.setDump(DumpState.DUMP_MESSAGES); 18394 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18395 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18396 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18397 || "intent-filter-verifiers".equals(cmd)) { 18398 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18399 } else if ("version".equals(cmd)) { 18400 dumpState.setDump(DumpState.DUMP_VERSION); 18401 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18402 dumpState.setDump(DumpState.DUMP_KEYSETS); 18403 } else if ("installs".equals(cmd)) { 18404 dumpState.setDump(DumpState.DUMP_INSTALLS); 18405 } else if ("frozen".equals(cmd)) { 18406 dumpState.setDump(DumpState.DUMP_FROZEN); 18407 } else if ("dexopt".equals(cmd)) { 18408 dumpState.setDump(DumpState.DUMP_DEXOPT); 18409 } else if ("write".equals(cmd)) { 18410 synchronized (mPackages) { 18411 mSettings.writeLPr(); 18412 pw.println("Settings written."); 18413 return; 18414 } 18415 } 18416 } 18417 18418 if (checkin) { 18419 pw.println("vers,1"); 18420 } 18421 18422 // reader 18423 synchronized (mPackages) { 18424 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18425 if (!checkin) { 18426 if (dumpState.onTitlePrinted()) 18427 pw.println(); 18428 pw.println("Database versions:"); 18429 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18430 } 18431 } 18432 18433 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18434 if (!checkin) { 18435 if (dumpState.onTitlePrinted()) 18436 pw.println(); 18437 pw.println("Verifiers:"); 18438 pw.print(" Required: "); 18439 pw.print(mRequiredVerifierPackage); 18440 pw.print(" (uid="); 18441 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18442 UserHandle.USER_SYSTEM)); 18443 pw.println(")"); 18444 } else if (mRequiredVerifierPackage != null) { 18445 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18446 pw.print(","); 18447 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18448 UserHandle.USER_SYSTEM)); 18449 } 18450 } 18451 18452 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18453 packageName == null) { 18454 if (mIntentFilterVerifierComponent != null) { 18455 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18456 if (!checkin) { 18457 if (dumpState.onTitlePrinted()) 18458 pw.println(); 18459 pw.println("Intent Filter Verifier:"); 18460 pw.print(" Using: "); 18461 pw.print(verifierPackageName); 18462 pw.print(" (uid="); 18463 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18464 UserHandle.USER_SYSTEM)); 18465 pw.println(")"); 18466 } else if (verifierPackageName != null) { 18467 pw.print("ifv,"); pw.print(verifierPackageName); 18468 pw.print(","); 18469 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18470 UserHandle.USER_SYSTEM)); 18471 } 18472 } else { 18473 pw.println(); 18474 pw.println("No Intent Filter Verifier available!"); 18475 } 18476 } 18477 18478 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18479 boolean printedHeader = false; 18480 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18481 while (it.hasNext()) { 18482 String name = it.next(); 18483 SharedLibraryEntry ent = mSharedLibraries.get(name); 18484 if (!checkin) { 18485 if (!printedHeader) { 18486 if (dumpState.onTitlePrinted()) 18487 pw.println(); 18488 pw.println("Libraries:"); 18489 printedHeader = true; 18490 } 18491 pw.print(" "); 18492 } else { 18493 pw.print("lib,"); 18494 } 18495 pw.print(name); 18496 if (!checkin) { 18497 pw.print(" -> "); 18498 } 18499 if (ent.path != null) { 18500 if (!checkin) { 18501 pw.print("(jar) "); 18502 pw.print(ent.path); 18503 } else { 18504 pw.print(",jar,"); 18505 pw.print(ent.path); 18506 } 18507 } else { 18508 if (!checkin) { 18509 pw.print("(apk) "); 18510 pw.print(ent.apk); 18511 } else { 18512 pw.print(",apk,"); 18513 pw.print(ent.apk); 18514 } 18515 } 18516 pw.println(); 18517 } 18518 } 18519 18520 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18521 if (dumpState.onTitlePrinted()) 18522 pw.println(); 18523 if (!checkin) { 18524 pw.println("Features:"); 18525 } 18526 18527 for (FeatureInfo feat : mAvailableFeatures.values()) { 18528 if (checkin) { 18529 pw.print("feat,"); 18530 pw.print(feat.name); 18531 pw.print(","); 18532 pw.println(feat.version); 18533 } else { 18534 pw.print(" "); 18535 pw.print(feat.name); 18536 if (feat.version > 0) { 18537 pw.print(" version="); 18538 pw.print(feat.version); 18539 } 18540 pw.println(); 18541 } 18542 } 18543 } 18544 18545 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18546 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18547 : "Activity Resolver Table:", " ", packageName, 18548 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18549 dumpState.setTitlePrinted(true); 18550 } 18551 } 18552 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18553 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18554 : "Receiver Resolver Table:", " ", packageName, 18555 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18556 dumpState.setTitlePrinted(true); 18557 } 18558 } 18559 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18560 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18561 : "Service Resolver Table:", " ", packageName, 18562 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18563 dumpState.setTitlePrinted(true); 18564 } 18565 } 18566 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18567 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18568 : "Provider Resolver Table:", " ", packageName, 18569 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18570 dumpState.setTitlePrinted(true); 18571 } 18572 } 18573 18574 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18575 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18576 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18577 int user = mSettings.mPreferredActivities.keyAt(i); 18578 if (pir.dump(pw, 18579 dumpState.getTitlePrinted() 18580 ? "\nPreferred Activities User " + user + ":" 18581 : "Preferred Activities User " + user + ":", " ", 18582 packageName, true, false)) { 18583 dumpState.setTitlePrinted(true); 18584 } 18585 } 18586 } 18587 18588 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18589 pw.flush(); 18590 FileOutputStream fout = new FileOutputStream(fd); 18591 BufferedOutputStream str = new BufferedOutputStream(fout); 18592 XmlSerializer serializer = new FastXmlSerializer(); 18593 try { 18594 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18595 serializer.startDocument(null, true); 18596 serializer.setFeature( 18597 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18598 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18599 serializer.endDocument(); 18600 serializer.flush(); 18601 } catch (IllegalArgumentException e) { 18602 pw.println("Failed writing: " + e); 18603 } catch (IllegalStateException e) { 18604 pw.println("Failed writing: " + e); 18605 } catch (IOException e) { 18606 pw.println("Failed writing: " + e); 18607 } 18608 } 18609 18610 if (!checkin 18611 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18612 && packageName == null) { 18613 pw.println(); 18614 int count = mSettings.mPackages.size(); 18615 if (count == 0) { 18616 pw.println("No applications!"); 18617 pw.println(); 18618 } else { 18619 final String prefix = " "; 18620 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18621 if (allPackageSettings.size() == 0) { 18622 pw.println("No domain preferred apps!"); 18623 pw.println(); 18624 } else { 18625 pw.println("App verification status:"); 18626 pw.println(); 18627 count = 0; 18628 for (PackageSetting ps : allPackageSettings) { 18629 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18630 if (ivi == null || ivi.getPackageName() == null) continue; 18631 pw.println(prefix + "Package: " + ivi.getPackageName()); 18632 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18633 pw.println(prefix + "Status: " + ivi.getStatusString()); 18634 pw.println(); 18635 count++; 18636 } 18637 if (count == 0) { 18638 pw.println(prefix + "No app verification established."); 18639 pw.println(); 18640 } 18641 for (int userId : sUserManager.getUserIds()) { 18642 pw.println("App linkages for user " + userId + ":"); 18643 pw.println(); 18644 count = 0; 18645 for (PackageSetting ps : allPackageSettings) { 18646 final long status = ps.getDomainVerificationStatusForUser(userId); 18647 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18648 continue; 18649 } 18650 pw.println(prefix + "Package: " + ps.name); 18651 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18652 String statusStr = IntentFilterVerificationInfo. 18653 getStatusStringFromValue(status); 18654 pw.println(prefix + "Status: " + statusStr); 18655 pw.println(); 18656 count++; 18657 } 18658 if (count == 0) { 18659 pw.println(prefix + "No configured app linkages."); 18660 pw.println(); 18661 } 18662 } 18663 } 18664 } 18665 } 18666 18667 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18668 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18669 if (packageName == null && permissionNames == null) { 18670 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18671 if (iperm == 0) { 18672 if (dumpState.onTitlePrinted()) 18673 pw.println(); 18674 pw.println("AppOp Permissions:"); 18675 } 18676 pw.print(" AppOp Permission "); 18677 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18678 pw.println(":"); 18679 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18680 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18681 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18682 } 18683 } 18684 } 18685 } 18686 18687 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18688 boolean printedSomething = false; 18689 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18690 if (packageName != null && !packageName.equals(p.info.packageName)) { 18691 continue; 18692 } 18693 if (!printedSomething) { 18694 if (dumpState.onTitlePrinted()) 18695 pw.println(); 18696 pw.println("Registered ContentProviders:"); 18697 printedSomething = true; 18698 } 18699 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18700 pw.print(" "); pw.println(p.toString()); 18701 } 18702 printedSomething = false; 18703 for (Map.Entry<String, PackageParser.Provider> entry : 18704 mProvidersByAuthority.entrySet()) { 18705 PackageParser.Provider p = entry.getValue(); 18706 if (packageName != null && !packageName.equals(p.info.packageName)) { 18707 continue; 18708 } 18709 if (!printedSomething) { 18710 if (dumpState.onTitlePrinted()) 18711 pw.println(); 18712 pw.println("ContentProvider Authorities:"); 18713 printedSomething = true; 18714 } 18715 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18716 pw.print(" "); pw.println(p.toString()); 18717 if (p.info != null && p.info.applicationInfo != null) { 18718 final String appInfo = p.info.applicationInfo.toString(); 18719 pw.print(" applicationInfo="); pw.println(appInfo); 18720 } 18721 } 18722 } 18723 18724 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18725 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18726 } 18727 18728 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18729 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18730 } 18731 18732 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18733 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18734 } 18735 18736 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18737 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18738 } 18739 18740 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18741 // XXX should handle packageName != null by dumping only install data that 18742 // the given package is involved with. 18743 if (dumpState.onTitlePrinted()) pw.println(); 18744 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18745 } 18746 18747 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18748 // XXX should handle packageName != null by dumping only install data that 18749 // the given package is involved with. 18750 if (dumpState.onTitlePrinted()) pw.println(); 18751 18752 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18753 ipw.println(); 18754 ipw.println("Frozen packages:"); 18755 ipw.increaseIndent(); 18756 if (mFrozenPackages.size() == 0) { 18757 ipw.println("(none)"); 18758 } else { 18759 for (int i = 0; i < mFrozenPackages.size(); i++) { 18760 ipw.println(mFrozenPackages.valueAt(i)); 18761 } 18762 } 18763 ipw.decreaseIndent(); 18764 } 18765 18766 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18767 if (dumpState.onTitlePrinted()) pw.println(); 18768 dumpDexoptStateLPr(pw, packageName); 18769 } 18770 18771 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18772 if (dumpState.onTitlePrinted()) pw.println(); 18773 mSettings.dumpReadMessagesLPr(pw, dumpState); 18774 18775 pw.println(); 18776 pw.println("Package warning messages:"); 18777 BufferedReader in = null; 18778 String line = null; 18779 try { 18780 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18781 while ((line = in.readLine()) != null) { 18782 if (line.contains("ignored: updated version")) continue; 18783 pw.println(line); 18784 } 18785 } catch (IOException ignored) { 18786 } finally { 18787 IoUtils.closeQuietly(in); 18788 } 18789 } 18790 18791 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18792 BufferedReader in = null; 18793 String line = null; 18794 try { 18795 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18796 while ((line = in.readLine()) != null) { 18797 if (line.contains("ignored: updated version")) continue; 18798 pw.print("msg,"); 18799 pw.println(line); 18800 } 18801 } catch (IOException ignored) { 18802 } finally { 18803 IoUtils.closeQuietly(in); 18804 } 18805 } 18806 } 18807 } 18808 18809 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18810 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18811 ipw.println(); 18812 ipw.println("Dexopt state:"); 18813 ipw.increaseIndent(); 18814 Collection<PackageParser.Package> packages = null; 18815 if (packageName != null) { 18816 PackageParser.Package targetPackage = mPackages.get(packageName); 18817 if (targetPackage != null) { 18818 packages = Collections.singletonList(targetPackage); 18819 } else { 18820 ipw.println("Unable to find package: " + packageName); 18821 return; 18822 } 18823 } else { 18824 packages = mPackages.values(); 18825 } 18826 18827 for (PackageParser.Package pkg : packages) { 18828 ipw.println("[" + pkg.packageName + "]"); 18829 ipw.increaseIndent(); 18830 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18831 ipw.decreaseIndent(); 18832 } 18833 } 18834 18835 private String dumpDomainString(String packageName) { 18836 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18837 .getList(); 18838 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18839 18840 ArraySet<String> result = new ArraySet<>(); 18841 if (iviList.size() > 0) { 18842 for (IntentFilterVerificationInfo ivi : iviList) { 18843 for (String host : ivi.getDomains()) { 18844 result.add(host); 18845 } 18846 } 18847 } 18848 if (filters != null && filters.size() > 0) { 18849 for (IntentFilter filter : filters) { 18850 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18851 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18852 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18853 result.addAll(filter.getHostsList()); 18854 } 18855 } 18856 } 18857 18858 StringBuilder sb = new StringBuilder(result.size() * 16); 18859 for (String domain : result) { 18860 if (sb.length() > 0) sb.append(" "); 18861 sb.append(domain); 18862 } 18863 return sb.toString(); 18864 } 18865 18866 // ------- apps on sdcard specific code ------- 18867 static final boolean DEBUG_SD_INSTALL = false; 18868 18869 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18870 18871 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18872 18873 private boolean mMediaMounted = false; 18874 18875 static String getEncryptKey() { 18876 try { 18877 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18878 SD_ENCRYPTION_KEYSTORE_NAME); 18879 if (sdEncKey == null) { 18880 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18881 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18882 if (sdEncKey == null) { 18883 Slog.e(TAG, "Failed to create encryption keys"); 18884 return null; 18885 } 18886 } 18887 return sdEncKey; 18888 } catch (NoSuchAlgorithmException nsae) { 18889 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18890 return null; 18891 } catch (IOException ioe) { 18892 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18893 return null; 18894 } 18895 } 18896 18897 /* 18898 * Update media status on PackageManager. 18899 */ 18900 @Override 18901 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18902 int callingUid = Binder.getCallingUid(); 18903 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18904 throw new SecurityException("Media status can only be updated by the system"); 18905 } 18906 // reader; this apparently protects mMediaMounted, but should probably 18907 // be a different lock in that case. 18908 synchronized (mPackages) { 18909 Log.i(TAG, "Updating external media status from " 18910 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18911 + (mediaStatus ? "mounted" : "unmounted")); 18912 if (DEBUG_SD_INSTALL) 18913 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18914 + ", mMediaMounted=" + mMediaMounted); 18915 if (mediaStatus == mMediaMounted) { 18916 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18917 : 0, -1); 18918 mHandler.sendMessage(msg); 18919 return; 18920 } 18921 mMediaMounted = mediaStatus; 18922 } 18923 // Queue up an async operation since the package installation may take a 18924 // little while. 18925 mHandler.post(new Runnable() { 18926 public void run() { 18927 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18928 } 18929 }); 18930 } 18931 18932 /** 18933 * Called by MountService when the initial ASECs to scan are available. 18934 * Should block until all the ASEC containers are finished being scanned. 18935 */ 18936 public void scanAvailableAsecs() { 18937 updateExternalMediaStatusInner(true, false, false); 18938 } 18939 18940 /* 18941 * Collect information of applications on external media, map them against 18942 * existing containers and update information based on current mount status. 18943 * Please note that we always have to report status if reportStatus has been 18944 * set to true especially when unloading packages. 18945 */ 18946 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18947 boolean externalStorage) { 18948 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18949 int[] uidArr = EmptyArray.INT; 18950 18951 final String[] list = PackageHelper.getSecureContainerList(); 18952 if (ArrayUtils.isEmpty(list)) { 18953 Log.i(TAG, "No secure containers found"); 18954 } else { 18955 // Process list of secure containers and categorize them 18956 // as active or stale based on their package internal state. 18957 18958 // reader 18959 synchronized (mPackages) { 18960 for (String cid : list) { 18961 // Leave stages untouched for now; installer service owns them 18962 if (PackageInstallerService.isStageName(cid)) continue; 18963 18964 if (DEBUG_SD_INSTALL) 18965 Log.i(TAG, "Processing container " + cid); 18966 String pkgName = getAsecPackageName(cid); 18967 if (pkgName == null) { 18968 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18969 continue; 18970 } 18971 if (DEBUG_SD_INSTALL) 18972 Log.i(TAG, "Looking for pkg : " + pkgName); 18973 18974 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18975 if (ps == null) { 18976 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18977 continue; 18978 } 18979 18980 /* 18981 * Skip packages that are not external if we're unmounting 18982 * external storage. 18983 */ 18984 if (externalStorage && !isMounted && !isExternal(ps)) { 18985 continue; 18986 } 18987 18988 final AsecInstallArgs args = new AsecInstallArgs(cid, 18989 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18990 // The package status is changed only if the code path 18991 // matches between settings and the container id. 18992 if (ps.codePathString != null 18993 && ps.codePathString.startsWith(args.getCodePath())) { 18994 if (DEBUG_SD_INSTALL) { 18995 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18996 + " at code path: " + ps.codePathString); 18997 } 18998 18999 // We do have a valid package installed on sdcard 19000 processCids.put(args, ps.codePathString); 19001 final int uid = ps.appId; 19002 if (uid != -1) { 19003 uidArr = ArrayUtils.appendInt(uidArr, uid); 19004 } 19005 } else { 19006 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19007 + ps.codePathString); 19008 } 19009 } 19010 } 19011 19012 Arrays.sort(uidArr); 19013 } 19014 19015 // Process packages with valid entries. 19016 if (isMounted) { 19017 if (DEBUG_SD_INSTALL) 19018 Log.i(TAG, "Loading packages"); 19019 loadMediaPackages(processCids, uidArr, externalStorage); 19020 startCleaningPackages(); 19021 mInstallerService.onSecureContainersAvailable(); 19022 } else { 19023 if (DEBUG_SD_INSTALL) 19024 Log.i(TAG, "Unloading packages"); 19025 unloadMediaPackages(processCids, uidArr, reportStatus); 19026 } 19027 } 19028 19029 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19030 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19031 final int size = infos.size(); 19032 final String[] packageNames = new String[size]; 19033 final int[] packageUids = new int[size]; 19034 for (int i = 0; i < size; i++) { 19035 final ApplicationInfo info = infos.get(i); 19036 packageNames[i] = info.packageName; 19037 packageUids[i] = info.uid; 19038 } 19039 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19040 finishedReceiver); 19041 } 19042 19043 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19044 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19045 sendResourcesChangedBroadcast(mediaStatus, replacing, 19046 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19047 } 19048 19049 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19050 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19051 int size = pkgList.length; 19052 if (size > 0) { 19053 // Send broadcasts here 19054 Bundle extras = new Bundle(); 19055 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19056 if (uidArr != null) { 19057 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19058 } 19059 if (replacing) { 19060 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19061 } 19062 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19063 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19064 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19065 } 19066 } 19067 19068 /* 19069 * Look at potentially valid container ids from processCids If package 19070 * information doesn't match the one on record or package scanning fails, 19071 * the cid is added to list of removeCids. We currently don't delete stale 19072 * containers. 19073 */ 19074 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19075 boolean externalStorage) { 19076 ArrayList<String> pkgList = new ArrayList<String>(); 19077 Set<AsecInstallArgs> keys = processCids.keySet(); 19078 19079 for (AsecInstallArgs args : keys) { 19080 String codePath = processCids.get(args); 19081 if (DEBUG_SD_INSTALL) 19082 Log.i(TAG, "Loading container : " + args.cid); 19083 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19084 try { 19085 // Make sure there are no container errors first. 19086 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19087 Slog.e(TAG, "Failed to mount cid : " + args.cid 19088 + " when installing from sdcard"); 19089 continue; 19090 } 19091 // Check code path here. 19092 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19093 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19094 + " does not match one in settings " + codePath); 19095 continue; 19096 } 19097 // Parse package 19098 int parseFlags = mDefParseFlags; 19099 if (args.isExternalAsec()) { 19100 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19101 } 19102 if (args.isFwdLocked()) { 19103 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19104 } 19105 19106 synchronized (mInstallLock) { 19107 PackageParser.Package pkg = null; 19108 try { 19109 // Sadly we don't know the package name yet to freeze it 19110 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19111 SCAN_IGNORE_FROZEN, 0, null); 19112 } catch (PackageManagerException e) { 19113 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19114 } 19115 // Scan the package 19116 if (pkg != null) { 19117 /* 19118 * TODO why is the lock being held? doPostInstall is 19119 * called in other places without the lock. This needs 19120 * to be straightened out. 19121 */ 19122 // writer 19123 synchronized (mPackages) { 19124 retCode = PackageManager.INSTALL_SUCCEEDED; 19125 pkgList.add(pkg.packageName); 19126 // Post process args 19127 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19128 pkg.applicationInfo.uid); 19129 } 19130 } else { 19131 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19132 } 19133 } 19134 19135 } finally { 19136 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19137 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19138 } 19139 } 19140 } 19141 // writer 19142 synchronized (mPackages) { 19143 // If the platform SDK has changed since the last time we booted, 19144 // we need to re-grant app permission to catch any new ones that 19145 // appear. This is really a hack, and means that apps can in some 19146 // cases get permissions that the user didn't initially explicitly 19147 // allow... it would be nice to have some better way to handle 19148 // this situation. 19149 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19150 : mSettings.getInternalVersion(); 19151 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19152 : StorageManager.UUID_PRIVATE_INTERNAL; 19153 19154 int updateFlags = UPDATE_PERMISSIONS_ALL; 19155 if (ver.sdkVersion != mSdkVersion) { 19156 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19157 + mSdkVersion + "; regranting permissions for external"); 19158 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19159 } 19160 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19161 19162 // Yay, everything is now upgraded 19163 ver.forceCurrent(); 19164 19165 // can downgrade to reader 19166 // Persist settings 19167 mSettings.writeLPr(); 19168 } 19169 // Send a broadcast to let everyone know we are done processing 19170 if (pkgList.size() > 0) { 19171 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19172 } 19173 } 19174 19175 /* 19176 * Utility method to unload a list of specified containers 19177 */ 19178 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19179 // Just unmount all valid containers. 19180 for (AsecInstallArgs arg : cidArgs) { 19181 synchronized (mInstallLock) { 19182 arg.doPostDeleteLI(false); 19183 } 19184 } 19185 } 19186 19187 /* 19188 * Unload packages mounted on external media. This involves deleting package 19189 * data from internal structures, sending broadcasts about disabled packages, 19190 * gc'ing to free up references, unmounting all secure containers 19191 * corresponding to packages on external media, and posting a 19192 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19193 * that we always have to post this message if status has been requested no 19194 * matter what. 19195 */ 19196 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19197 final boolean reportStatus) { 19198 if (DEBUG_SD_INSTALL) 19199 Log.i(TAG, "unloading media packages"); 19200 ArrayList<String> pkgList = new ArrayList<String>(); 19201 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19202 final Set<AsecInstallArgs> keys = processCids.keySet(); 19203 for (AsecInstallArgs args : keys) { 19204 String pkgName = args.getPackageName(); 19205 if (DEBUG_SD_INSTALL) 19206 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19207 // Delete package internally 19208 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19209 synchronized (mInstallLock) { 19210 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19211 final boolean res; 19212 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19213 "unloadMediaPackages")) { 19214 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19215 null); 19216 } 19217 if (res) { 19218 pkgList.add(pkgName); 19219 } else { 19220 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19221 failedList.add(args); 19222 } 19223 } 19224 } 19225 19226 // reader 19227 synchronized (mPackages) { 19228 // We didn't update the settings after removing each package; 19229 // write them now for all packages. 19230 mSettings.writeLPr(); 19231 } 19232 19233 // We have to absolutely send UPDATED_MEDIA_STATUS only 19234 // after confirming that all the receivers processed the ordered 19235 // broadcast when packages get disabled, force a gc to clean things up. 19236 // and unload all the containers. 19237 if (pkgList.size() > 0) { 19238 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19239 new IIntentReceiver.Stub() { 19240 public void performReceive(Intent intent, int resultCode, String data, 19241 Bundle extras, boolean ordered, boolean sticky, 19242 int sendingUser) throws RemoteException { 19243 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19244 reportStatus ? 1 : 0, 1, keys); 19245 mHandler.sendMessage(msg); 19246 } 19247 }); 19248 } else { 19249 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19250 keys); 19251 mHandler.sendMessage(msg); 19252 } 19253 } 19254 19255 private void loadPrivatePackages(final VolumeInfo vol) { 19256 mHandler.post(new Runnable() { 19257 @Override 19258 public void run() { 19259 loadPrivatePackagesInner(vol); 19260 } 19261 }); 19262 } 19263 19264 private void loadPrivatePackagesInner(VolumeInfo vol) { 19265 final String volumeUuid = vol.fsUuid; 19266 if (TextUtils.isEmpty(volumeUuid)) { 19267 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19268 return; 19269 } 19270 19271 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19272 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19273 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19274 19275 final VersionInfo ver; 19276 final List<PackageSetting> packages; 19277 synchronized (mPackages) { 19278 ver = mSettings.findOrCreateVersion(volumeUuid); 19279 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19280 } 19281 19282 for (PackageSetting ps : packages) { 19283 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19284 synchronized (mInstallLock) { 19285 final PackageParser.Package pkg; 19286 try { 19287 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19288 loaded.add(pkg.applicationInfo); 19289 19290 } catch (PackageManagerException e) { 19291 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19292 } 19293 19294 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19295 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19296 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19297 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19298 } 19299 } 19300 } 19301 19302 // Reconcile app data for all started/unlocked users 19303 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19304 final UserManager um = mContext.getSystemService(UserManager.class); 19305 UserManagerInternal umInternal = getUserManagerInternal(); 19306 for (UserInfo user : um.getUsers()) { 19307 final int flags; 19308 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19309 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19310 } else if (umInternal.isUserRunning(user.id)) { 19311 flags = StorageManager.FLAG_STORAGE_DE; 19312 } else { 19313 continue; 19314 } 19315 19316 try { 19317 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19318 synchronized (mInstallLock) { 19319 reconcileAppsDataLI(volumeUuid, user.id, flags); 19320 } 19321 } catch (IllegalStateException e) { 19322 // Device was probably ejected, and we'll process that event momentarily 19323 Slog.w(TAG, "Failed to prepare storage: " + e); 19324 } 19325 } 19326 19327 synchronized (mPackages) { 19328 int updateFlags = UPDATE_PERMISSIONS_ALL; 19329 if (ver.sdkVersion != mSdkVersion) { 19330 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19331 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19332 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19333 } 19334 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19335 19336 // Yay, everything is now upgraded 19337 ver.forceCurrent(); 19338 19339 mSettings.writeLPr(); 19340 } 19341 19342 for (PackageFreezer freezer : freezers) { 19343 freezer.close(); 19344 } 19345 19346 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19347 sendResourcesChangedBroadcast(true, false, loaded, null); 19348 } 19349 19350 private void unloadPrivatePackages(final VolumeInfo vol) { 19351 mHandler.post(new Runnable() { 19352 @Override 19353 public void run() { 19354 unloadPrivatePackagesInner(vol); 19355 } 19356 }); 19357 } 19358 19359 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19360 final String volumeUuid = vol.fsUuid; 19361 if (TextUtils.isEmpty(volumeUuid)) { 19362 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19363 return; 19364 } 19365 19366 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19367 synchronized (mInstallLock) { 19368 synchronized (mPackages) { 19369 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19370 for (PackageSetting ps : packages) { 19371 if (ps.pkg == null) continue; 19372 19373 final ApplicationInfo info = ps.pkg.applicationInfo; 19374 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19375 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19376 19377 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19378 "unloadPrivatePackagesInner")) { 19379 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19380 false, null)) { 19381 unloaded.add(info); 19382 } else { 19383 Slog.w(TAG, "Failed to unload " + ps.codePath); 19384 } 19385 } 19386 19387 // Try very hard to release any references to this package 19388 // so we don't risk the system server being killed due to 19389 // open FDs 19390 AttributeCache.instance().removePackage(ps.name); 19391 } 19392 19393 mSettings.writeLPr(); 19394 } 19395 } 19396 19397 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19398 sendResourcesChangedBroadcast(false, false, unloaded, null); 19399 19400 // Try very hard to release any references to this path so we don't risk 19401 // the system server being killed due to open FDs 19402 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19403 19404 for (int i = 0; i < 3; i++) { 19405 System.gc(); 19406 System.runFinalization(); 19407 } 19408 } 19409 19410 /** 19411 * Prepare storage areas for given user on all mounted devices. 19412 */ 19413 void prepareUserData(int userId, int userSerial, int flags) { 19414 synchronized (mInstallLock) { 19415 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19416 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19417 final String volumeUuid = vol.getFsUuid(); 19418 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19419 } 19420 } 19421 } 19422 19423 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19424 boolean allowRecover) { 19425 // Prepare storage and verify that serial numbers are consistent; if 19426 // there's a mismatch we need to destroy to avoid leaking data 19427 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19428 try { 19429 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19430 19431 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19432 UserManagerService.enforceSerialNumber( 19433 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19434 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19435 UserManagerService.enforceSerialNumber( 19436 Environment.getDataSystemDeDirectory(userId), userSerial); 19437 } 19438 } 19439 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19440 UserManagerService.enforceSerialNumber( 19441 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19442 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19443 UserManagerService.enforceSerialNumber( 19444 Environment.getDataSystemCeDirectory(userId), userSerial); 19445 } 19446 } 19447 19448 synchronized (mInstallLock) { 19449 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19450 } 19451 } catch (Exception e) { 19452 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19453 + " because we failed to prepare: " + e); 19454 destroyUserDataLI(volumeUuid, userId, 19455 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19456 19457 if (allowRecover) { 19458 // Try one last time; if we fail again we're really in trouble 19459 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19460 } 19461 } 19462 } 19463 19464 /** 19465 * Destroy storage areas for given user on all mounted devices. 19466 */ 19467 void destroyUserData(int userId, int flags) { 19468 synchronized (mInstallLock) { 19469 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19470 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19471 final String volumeUuid = vol.getFsUuid(); 19472 destroyUserDataLI(volumeUuid, userId, flags); 19473 } 19474 } 19475 } 19476 19477 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19478 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19479 try { 19480 // Clean up app data, profile data, and media data 19481 mInstaller.destroyUserData(volumeUuid, userId, flags); 19482 19483 // Clean up system data 19484 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19485 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19486 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19487 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19488 } 19489 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19490 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19491 } 19492 } 19493 19494 // Data with special labels is now gone, so finish the job 19495 storage.destroyUserStorage(volumeUuid, userId, flags); 19496 19497 } catch (Exception e) { 19498 logCriticalInfo(Log.WARN, 19499 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19500 } 19501 } 19502 19503 /** 19504 * Examine all users present on given mounted volume, and destroy data 19505 * belonging to users that are no longer valid, or whose user ID has been 19506 * recycled. 19507 */ 19508 private void reconcileUsers(String volumeUuid) { 19509 final List<File> files = new ArrayList<>(); 19510 Collections.addAll(files, FileUtils 19511 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19512 Collections.addAll(files, FileUtils 19513 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19514 Collections.addAll(files, FileUtils 19515 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19516 Collections.addAll(files, FileUtils 19517 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19518 for (File file : files) { 19519 if (!file.isDirectory()) continue; 19520 19521 final int userId; 19522 final UserInfo info; 19523 try { 19524 userId = Integer.parseInt(file.getName()); 19525 info = sUserManager.getUserInfo(userId); 19526 } catch (NumberFormatException e) { 19527 Slog.w(TAG, "Invalid user directory " + file); 19528 continue; 19529 } 19530 19531 boolean destroyUser = false; 19532 if (info == null) { 19533 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19534 + " because no matching user was found"); 19535 destroyUser = true; 19536 } else if (!mOnlyCore) { 19537 try { 19538 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19539 } catch (IOException e) { 19540 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19541 + " because we failed to enforce serial number: " + e); 19542 destroyUser = true; 19543 } 19544 } 19545 19546 if (destroyUser) { 19547 synchronized (mInstallLock) { 19548 destroyUserDataLI(volumeUuid, userId, 19549 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19550 } 19551 } 19552 } 19553 } 19554 19555 private void assertPackageKnown(String volumeUuid, String packageName) 19556 throws PackageManagerException { 19557 synchronized (mPackages) { 19558 final PackageSetting ps = mSettings.mPackages.get(packageName); 19559 if (ps == null) { 19560 throw new PackageManagerException("Package " + packageName + " is unknown"); 19561 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19562 throw new PackageManagerException( 19563 "Package " + packageName + " found on unknown volume " + volumeUuid 19564 + "; expected volume " + ps.volumeUuid); 19565 } 19566 } 19567 } 19568 19569 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19570 throws PackageManagerException { 19571 synchronized (mPackages) { 19572 final PackageSetting ps = mSettings.mPackages.get(packageName); 19573 if (ps == null) { 19574 throw new PackageManagerException("Package " + packageName + " is unknown"); 19575 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19576 throw new PackageManagerException( 19577 "Package " + packageName + " found on unknown volume " + volumeUuid 19578 + "; expected volume " + ps.volumeUuid); 19579 } else if (!ps.getInstalled(userId)) { 19580 throw new PackageManagerException( 19581 "Package " + packageName + " not installed for user " + userId); 19582 } 19583 } 19584 } 19585 19586 /** 19587 * Examine all apps present on given mounted volume, and destroy apps that 19588 * aren't expected, either due to uninstallation or reinstallation on 19589 * another volume. 19590 */ 19591 private void reconcileApps(String volumeUuid) { 19592 final File[] files = FileUtils 19593 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19594 for (File file : files) { 19595 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19596 && !PackageInstallerService.isStageName(file.getName()); 19597 if (!isPackage) { 19598 // Ignore entries which are not packages 19599 continue; 19600 } 19601 19602 try { 19603 final PackageLite pkg = PackageParser.parsePackageLite(file, 19604 PackageParser.PARSE_MUST_BE_APK); 19605 assertPackageKnown(volumeUuid, pkg.packageName); 19606 19607 } catch (PackageParserException | PackageManagerException e) { 19608 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19609 synchronized (mInstallLock) { 19610 removeCodePathLI(file); 19611 } 19612 } 19613 } 19614 } 19615 19616 /** 19617 * Reconcile all app data for the given user. 19618 * <p> 19619 * Verifies that directories exist and that ownership and labeling is 19620 * correct for all installed apps on all mounted volumes. 19621 */ 19622 void reconcileAppsData(int userId, int flags) { 19623 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19624 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19625 final String volumeUuid = vol.getFsUuid(); 19626 synchronized (mInstallLock) { 19627 reconcileAppsDataLI(volumeUuid, userId, flags); 19628 } 19629 } 19630 } 19631 19632 /** 19633 * Reconcile all app data on given mounted volume. 19634 * <p> 19635 * Destroys app data that isn't expected, either due to uninstallation or 19636 * reinstallation on another volume. 19637 * <p> 19638 * Verifies that directories exist and that ownership and labeling is 19639 * correct for all installed apps. 19640 */ 19641 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19642 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19643 + Integer.toHexString(flags)); 19644 19645 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19646 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19647 19648 boolean restoreconNeeded = false; 19649 19650 // First look for stale data that doesn't belong, and check if things 19651 // have changed since we did our last restorecon 19652 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19653 if (StorageManager.isFileEncryptedNativeOrEmulated() 19654 && !StorageManager.isUserKeyUnlocked(userId)) { 19655 throw new RuntimeException( 19656 "Yikes, someone asked us to reconcile CE storage while " + userId 19657 + " was still locked; this would have caused massive data loss!"); 19658 } 19659 19660 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19661 19662 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19663 for (File file : files) { 19664 final String packageName = file.getName(); 19665 try { 19666 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19667 } catch (PackageManagerException e) { 19668 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19669 try { 19670 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19671 StorageManager.FLAG_STORAGE_CE, 0); 19672 } catch (InstallerException e2) { 19673 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19674 } 19675 } 19676 } 19677 } 19678 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19679 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19680 19681 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19682 for (File file : files) { 19683 final String packageName = file.getName(); 19684 try { 19685 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19686 } catch (PackageManagerException e) { 19687 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19688 try { 19689 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19690 StorageManager.FLAG_STORAGE_DE, 0); 19691 } catch (InstallerException e2) { 19692 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19693 } 19694 } 19695 } 19696 } 19697 19698 // Ensure that data directories are ready to roll for all packages 19699 // installed for this volume and user 19700 final List<PackageSetting> packages; 19701 synchronized (mPackages) { 19702 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19703 } 19704 int preparedCount = 0; 19705 for (PackageSetting ps : packages) { 19706 final String packageName = ps.name; 19707 if (ps.pkg == null) { 19708 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19709 // TODO: might be due to legacy ASEC apps; we should circle back 19710 // and reconcile again once they're scanned 19711 continue; 19712 } 19713 19714 if (ps.getInstalled(userId)) { 19715 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19716 19717 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19718 // We may have just shuffled around app data directories, so 19719 // prepare them one more time 19720 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19721 } 19722 19723 preparedCount++; 19724 } 19725 } 19726 19727 if (restoreconNeeded) { 19728 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19729 SELinuxMMAC.setRestoreconDone(ceDir); 19730 } 19731 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19732 SELinuxMMAC.setRestoreconDone(deDir); 19733 } 19734 } 19735 19736 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19737 + " packages; restoreconNeeded was " + restoreconNeeded); 19738 } 19739 19740 /** 19741 * Prepare app data for the given app just after it was installed or 19742 * upgraded. This method carefully only touches users that it's installed 19743 * for, and it forces a restorecon to handle any seinfo changes. 19744 * <p> 19745 * Verifies that directories exist and that ownership and labeling is 19746 * correct for all installed apps. If there is an ownership mismatch, it 19747 * will try recovering system apps by wiping data; third-party app data is 19748 * left intact. 19749 * <p> 19750 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19751 */ 19752 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19753 final PackageSetting ps; 19754 synchronized (mPackages) { 19755 ps = mSettings.mPackages.get(pkg.packageName); 19756 mSettings.writeKernelMappingLPr(ps); 19757 } 19758 19759 final UserManager um = mContext.getSystemService(UserManager.class); 19760 UserManagerInternal umInternal = getUserManagerInternal(); 19761 for (UserInfo user : um.getUsers()) { 19762 final int flags; 19763 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19764 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19765 } else if (umInternal.isUserRunning(user.id)) { 19766 flags = StorageManager.FLAG_STORAGE_DE; 19767 } else { 19768 continue; 19769 } 19770 19771 if (ps.getInstalled(user.id)) { 19772 // Whenever an app changes, force a restorecon of its data 19773 // TODO: when user data is locked, mark that we're still dirty 19774 prepareAppDataLIF(pkg, user.id, flags, true); 19775 } 19776 } 19777 } 19778 19779 /** 19780 * Prepare app data for the given app. 19781 * <p> 19782 * Verifies that directories exist and that ownership and labeling is 19783 * correct for all installed apps. If there is an ownership mismatch, this 19784 * will try recovering system apps by wiping data; third-party app data is 19785 * left intact. 19786 */ 19787 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19788 boolean restoreconNeeded) { 19789 if (pkg == null) { 19790 Slog.wtf(TAG, "Package was null!", new Throwable()); 19791 return; 19792 } 19793 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19794 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19795 for (int i = 0; i < childCount; i++) { 19796 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19797 } 19798 } 19799 19800 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19801 boolean restoreconNeeded) { 19802 if (DEBUG_APP_DATA) { 19803 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19804 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19805 } 19806 19807 final String volumeUuid = pkg.volumeUuid; 19808 final String packageName = pkg.packageName; 19809 final ApplicationInfo app = pkg.applicationInfo; 19810 final int appId = UserHandle.getAppId(app.uid); 19811 19812 Preconditions.checkNotNull(app.seinfo); 19813 19814 try { 19815 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19816 appId, app.seinfo, app.targetSdkVersion); 19817 } catch (InstallerException e) { 19818 if (app.isSystemApp()) { 19819 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19820 + ", but trying to recover: " + e); 19821 destroyAppDataLeafLIF(pkg, userId, flags); 19822 try { 19823 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19824 appId, app.seinfo, app.targetSdkVersion); 19825 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19826 } catch (InstallerException e2) { 19827 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19828 } 19829 } else { 19830 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19831 } 19832 } 19833 19834 if (restoreconNeeded) { 19835 try { 19836 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19837 app.seinfo); 19838 } catch (InstallerException e) { 19839 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19840 } 19841 } 19842 19843 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19844 try { 19845 // CE storage is unlocked right now, so read out the inode and 19846 // remember for use later when it's locked 19847 // TODO: mark this structure as dirty so we persist it! 19848 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19849 StorageManager.FLAG_STORAGE_CE); 19850 synchronized (mPackages) { 19851 final PackageSetting ps = mSettings.mPackages.get(packageName); 19852 if (ps != null) { 19853 ps.setCeDataInode(ceDataInode, userId); 19854 } 19855 } 19856 } catch (InstallerException e) { 19857 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19858 } 19859 } 19860 19861 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19862 } 19863 19864 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19865 if (pkg == null) { 19866 Slog.wtf(TAG, "Package was null!", new Throwable()); 19867 return; 19868 } 19869 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19870 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19871 for (int i = 0; i < childCount; i++) { 19872 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19873 } 19874 } 19875 19876 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19877 final String volumeUuid = pkg.volumeUuid; 19878 final String packageName = pkg.packageName; 19879 final ApplicationInfo app = pkg.applicationInfo; 19880 19881 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19882 // Create a native library symlink only if we have native libraries 19883 // and if the native libraries are 32 bit libraries. We do not provide 19884 // this symlink for 64 bit libraries. 19885 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19886 final String nativeLibPath = app.nativeLibraryDir; 19887 try { 19888 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19889 nativeLibPath, userId); 19890 } catch (InstallerException e) { 19891 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19892 } 19893 } 19894 } 19895 } 19896 19897 /** 19898 * For system apps on non-FBE devices, this method migrates any existing 19899 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19900 * requested by the app. 19901 */ 19902 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19903 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19904 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19905 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19906 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19907 try { 19908 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19909 storageTarget); 19910 } catch (InstallerException e) { 19911 logCriticalInfo(Log.WARN, 19912 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19913 } 19914 return true; 19915 } else { 19916 return false; 19917 } 19918 } 19919 19920 public PackageFreezer freezePackage(String packageName, String killReason) { 19921 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 19922 } 19923 19924 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 19925 return new PackageFreezer(packageName, userId, killReason); 19926 } 19927 19928 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19929 String killReason) { 19930 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 19931 } 19932 19933 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 19934 String killReason) { 19935 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19936 return new PackageFreezer(); 19937 } else { 19938 return freezePackage(packageName, userId, killReason); 19939 } 19940 } 19941 19942 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19943 String killReason) { 19944 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 19945 } 19946 19947 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 19948 String killReason) { 19949 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19950 return new PackageFreezer(); 19951 } else { 19952 return freezePackage(packageName, userId, killReason); 19953 } 19954 } 19955 19956 /** 19957 * Class that freezes and kills the given package upon creation, and 19958 * unfreezes it upon closing. This is typically used when doing surgery on 19959 * app code/data to prevent the app from running while you're working. 19960 */ 19961 private class PackageFreezer implements AutoCloseable { 19962 private final String mPackageName; 19963 private final PackageFreezer[] mChildren; 19964 19965 private final boolean mWeFroze; 19966 19967 private final AtomicBoolean mClosed = new AtomicBoolean(); 19968 private final CloseGuard mCloseGuard = CloseGuard.get(); 19969 19970 /** 19971 * Create and return a stub freezer that doesn't actually do anything, 19972 * typically used when someone requested 19973 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19974 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19975 */ 19976 public PackageFreezer() { 19977 mPackageName = null; 19978 mChildren = null; 19979 mWeFroze = false; 19980 mCloseGuard.open("close"); 19981 } 19982 19983 public PackageFreezer(String packageName, int userId, String killReason) { 19984 synchronized (mPackages) { 19985 mPackageName = packageName; 19986 mWeFroze = mFrozenPackages.add(mPackageName); 19987 19988 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19989 if (ps != null) { 19990 killApplication(ps.name, ps.appId, userId, killReason); 19991 } 19992 19993 final PackageParser.Package p = mPackages.get(packageName); 19994 if (p != null && p.childPackages != null) { 19995 final int N = p.childPackages.size(); 19996 mChildren = new PackageFreezer[N]; 19997 for (int i = 0; i < N; i++) { 19998 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19999 userId, killReason); 20000 } 20001 } else { 20002 mChildren = null; 20003 } 20004 } 20005 mCloseGuard.open("close"); 20006 } 20007 20008 @Override 20009 protected void finalize() throws Throwable { 20010 try { 20011 mCloseGuard.warnIfOpen(); 20012 close(); 20013 } finally { 20014 super.finalize(); 20015 } 20016 } 20017 20018 @Override 20019 public void close() { 20020 mCloseGuard.close(); 20021 if (mClosed.compareAndSet(false, true)) { 20022 synchronized (mPackages) { 20023 if (mWeFroze) { 20024 mFrozenPackages.remove(mPackageName); 20025 } 20026 20027 if (mChildren != null) { 20028 for (PackageFreezer freezer : mChildren) { 20029 freezer.close(); 20030 } 20031 } 20032 } 20033 } 20034 } 20035 } 20036 20037 /** 20038 * Verify that given package is currently frozen. 20039 */ 20040 private void checkPackageFrozen(String packageName) { 20041 synchronized (mPackages) { 20042 if (!mFrozenPackages.contains(packageName)) { 20043 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20044 } 20045 } 20046 } 20047 20048 @Override 20049 public int movePackage(final String packageName, final String volumeUuid) { 20050 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20051 20052 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20053 final int moveId = mNextMoveId.getAndIncrement(); 20054 mHandler.post(new Runnable() { 20055 @Override 20056 public void run() { 20057 try { 20058 movePackageInternal(packageName, volumeUuid, moveId, user); 20059 } catch (PackageManagerException e) { 20060 Slog.w(TAG, "Failed to move " + packageName, e); 20061 mMoveCallbacks.notifyStatusChanged(moveId, 20062 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20063 } 20064 } 20065 }); 20066 return moveId; 20067 } 20068 20069 private void movePackageInternal(final String packageName, final String volumeUuid, 20070 final int moveId, UserHandle user) throws PackageManagerException { 20071 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20072 final PackageManager pm = mContext.getPackageManager(); 20073 20074 final boolean currentAsec; 20075 final String currentVolumeUuid; 20076 final File codeFile; 20077 final String installerPackageName; 20078 final String packageAbiOverride; 20079 final int appId; 20080 final String seinfo; 20081 final String label; 20082 final int targetSdkVersion; 20083 final PackageFreezer freezer; 20084 final int[] installedUserIds; 20085 20086 // reader 20087 synchronized (mPackages) { 20088 final PackageParser.Package pkg = mPackages.get(packageName); 20089 final PackageSetting ps = mSettings.mPackages.get(packageName); 20090 if (pkg == null || ps == null) { 20091 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20092 } 20093 20094 if (pkg.applicationInfo.isSystemApp()) { 20095 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20096 "Cannot move system application"); 20097 } 20098 20099 if (pkg.applicationInfo.isExternalAsec()) { 20100 currentAsec = true; 20101 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20102 } else if (pkg.applicationInfo.isForwardLocked()) { 20103 currentAsec = true; 20104 currentVolumeUuid = "forward_locked"; 20105 } else { 20106 currentAsec = false; 20107 currentVolumeUuid = ps.volumeUuid; 20108 20109 final File probe = new File(pkg.codePath); 20110 final File probeOat = new File(probe, "oat"); 20111 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20112 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20113 "Move only supported for modern cluster style installs"); 20114 } 20115 } 20116 20117 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20118 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20119 "Package already moved to " + volumeUuid); 20120 } 20121 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20122 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20123 "Device admin cannot be moved"); 20124 } 20125 20126 if (mFrozenPackages.contains(packageName)) { 20127 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20128 "Failed to move already frozen package"); 20129 } 20130 20131 codeFile = new File(pkg.codePath); 20132 installerPackageName = ps.installerPackageName; 20133 packageAbiOverride = ps.cpuAbiOverrideString; 20134 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20135 seinfo = pkg.applicationInfo.seinfo; 20136 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20137 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20138 freezer = freezePackage(packageName, "movePackageInternal"); 20139 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20140 } 20141 20142 final Bundle extras = new Bundle(); 20143 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20144 extras.putString(Intent.EXTRA_TITLE, label); 20145 mMoveCallbacks.notifyCreated(moveId, extras); 20146 20147 int installFlags; 20148 final boolean moveCompleteApp; 20149 final File measurePath; 20150 20151 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20152 installFlags = INSTALL_INTERNAL; 20153 moveCompleteApp = !currentAsec; 20154 measurePath = Environment.getDataAppDirectory(volumeUuid); 20155 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20156 installFlags = INSTALL_EXTERNAL; 20157 moveCompleteApp = false; 20158 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20159 } else { 20160 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20161 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20162 || !volume.isMountedWritable()) { 20163 freezer.close(); 20164 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20165 "Move location not mounted private volume"); 20166 } 20167 20168 Preconditions.checkState(!currentAsec); 20169 20170 installFlags = INSTALL_INTERNAL; 20171 moveCompleteApp = true; 20172 measurePath = Environment.getDataAppDirectory(volumeUuid); 20173 } 20174 20175 final PackageStats stats = new PackageStats(null, -1); 20176 synchronized (mInstaller) { 20177 for (int userId : installedUserIds) { 20178 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20179 freezer.close(); 20180 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20181 "Failed to measure package size"); 20182 } 20183 } 20184 } 20185 20186 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20187 + stats.dataSize); 20188 20189 final long startFreeBytes = measurePath.getFreeSpace(); 20190 final long sizeBytes; 20191 if (moveCompleteApp) { 20192 sizeBytes = stats.codeSize + stats.dataSize; 20193 } else { 20194 sizeBytes = stats.codeSize; 20195 } 20196 20197 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20198 freezer.close(); 20199 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20200 "Not enough free space to move"); 20201 } 20202 20203 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20204 20205 final CountDownLatch installedLatch = new CountDownLatch(1); 20206 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20207 @Override 20208 public void onUserActionRequired(Intent intent) throws RemoteException { 20209 throw new IllegalStateException(); 20210 } 20211 20212 @Override 20213 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20214 Bundle extras) throws RemoteException { 20215 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20216 + PackageManager.installStatusToString(returnCode, msg)); 20217 20218 installedLatch.countDown(); 20219 freezer.close(); 20220 20221 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20222 switch (status) { 20223 case PackageInstaller.STATUS_SUCCESS: 20224 mMoveCallbacks.notifyStatusChanged(moveId, 20225 PackageManager.MOVE_SUCCEEDED); 20226 break; 20227 case PackageInstaller.STATUS_FAILURE_STORAGE: 20228 mMoveCallbacks.notifyStatusChanged(moveId, 20229 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20230 break; 20231 default: 20232 mMoveCallbacks.notifyStatusChanged(moveId, 20233 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20234 break; 20235 } 20236 } 20237 }; 20238 20239 final MoveInfo move; 20240 if (moveCompleteApp) { 20241 // Kick off a thread to report progress estimates 20242 new Thread() { 20243 @Override 20244 public void run() { 20245 while (true) { 20246 try { 20247 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20248 break; 20249 } 20250 } catch (InterruptedException ignored) { 20251 } 20252 20253 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20254 final int progress = 10 + (int) MathUtils.constrain( 20255 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20256 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20257 } 20258 } 20259 }.start(); 20260 20261 final String dataAppName = codeFile.getName(); 20262 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20263 dataAppName, appId, seinfo, targetSdkVersion); 20264 } else { 20265 move = null; 20266 } 20267 20268 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20269 20270 final Message msg = mHandler.obtainMessage(INIT_COPY); 20271 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20272 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20273 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20274 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20275 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20276 msg.obj = params; 20277 20278 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20279 System.identityHashCode(msg.obj)); 20280 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20281 System.identityHashCode(msg.obj)); 20282 20283 mHandler.sendMessage(msg); 20284 } 20285 20286 @Override 20287 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20288 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20289 20290 final int realMoveId = mNextMoveId.getAndIncrement(); 20291 final Bundle extras = new Bundle(); 20292 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20293 mMoveCallbacks.notifyCreated(realMoveId, extras); 20294 20295 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20296 @Override 20297 public void onCreated(int moveId, Bundle extras) { 20298 // Ignored 20299 } 20300 20301 @Override 20302 public void onStatusChanged(int moveId, int status, long estMillis) { 20303 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20304 } 20305 }; 20306 20307 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20308 storage.setPrimaryStorageUuid(volumeUuid, callback); 20309 return realMoveId; 20310 } 20311 20312 @Override 20313 public int getMoveStatus(int moveId) { 20314 mContext.enforceCallingOrSelfPermission( 20315 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20316 return mMoveCallbacks.mLastStatus.get(moveId); 20317 } 20318 20319 @Override 20320 public void registerMoveCallback(IPackageMoveObserver callback) { 20321 mContext.enforceCallingOrSelfPermission( 20322 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20323 mMoveCallbacks.register(callback); 20324 } 20325 20326 @Override 20327 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20328 mContext.enforceCallingOrSelfPermission( 20329 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20330 mMoveCallbacks.unregister(callback); 20331 } 20332 20333 @Override 20334 public boolean setInstallLocation(int loc) { 20335 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20336 null); 20337 if (getInstallLocation() == loc) { 20338 return true; 20339 } 20340 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20341 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20342 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20343 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20344 return true; 20345 } 20346 return false; 20347 } 20348 20349 @Override 20350 public int getInstallLocation() { 20351 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20352 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20353 PackageHelper.APP_INSTALL_AUTO); 20354 } 20355 20356 /** Called by UserManagerService */ 20357 void cleanUpUser(UserManagerService userManager, int userHandle) { 20358 synchronized (mPackages) { 20359 mDirtyUsers.remove(userHandle); 20360 mUserNeedsBadging.delete(userHandle); 20361 mSettings.removeUserLPw(userHandle); 20362 mPendingBroadcasts.remove(userHandle); 20363 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20364 removeUnusedPackagesLPw(userManager, userHandle); 20365 } 20366 } 20367 20368 /** 20369 * We're removing userHandle and would like to remove any downloaded packages 20370 * that are no longer in use by any other user. 20371 * @param userHandle the user being removed 20372 */ 20373 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20374 final boolean DEBUG_CLEAN_APKS = false; 20375 int [] users = userManager.getUserIds(); 20376 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20377 while (psit.hasNext()) { 20378 PackageSetting ps = psit.next(); 20379 if (ps.pkg == null) { 20380 continue; 20381 } 20382 final String packageName = ps.pkg.packageName; 20383 // Skip over if system app 20384 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20385 continue; 20386 } 20387 if (DEBUG_CLEAN_APKS) { 20388 Slog.i(TAG, "Checking package " + packageName); 20389 } 20390 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20391 if (keep) { 20392 if (DEBUG_CLEAN_APKS) { 20393 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20394 } 20395 } else { 20396 for (int i = 0; i < users.length; i++) { 20397 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20398 keep = true; 20399 if (DEBUG_CLEAN_APKS) { 20400 Slog.i(TAG, " Keeping package " + packageName + " for user " 20401 + users[i]); 20402 } 20403 break; 20404 } 20405 } 20406 } 20407 if (!keep) { 20408 if (DEBUG_CLEAN_APKS) { 20409 Slog.i(TAG, " Removing package " + packageName); 20410 } 20411 mHandler.post(new Runnable() { 20412 public void run() { 20413 deletePackageX(packageName, userHandle, 0); 20414 } //end run 20415 }); 20416 } 20417 } 20418 } 20419 20420 /** Called by UserManagerService */ 20421 void createNewUser(int userId) { 20422 synchronized (mInstallLock) { 20423 mSettings.createNewUserLI(this, mInstaller, userId); 20424 } 20425 synchronized (mPackages) { 20426 scheduleWritePackageRestrictionsLocked(userId); 20427 scheduleWritePackageListLocked(userId); 20428 applyFactoryDefaultBrowserLPw(userId); 20429 primeDomainVerificationsLPw(userId); 20430 } 20431 } 20432 20433 void onBeforeUserStartUninitialized(final int userId) { 20434 synchronized (mPackages) { 20435 if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20436 return; 20437 } 20438 } 20439 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20440 // If permission review for legacy apps is required, we represent 20441 // dagerous permissions for such apps as always granted runtime 20442 // permissions to keep per user flag state whether review is needed. 20443 // Hence, if a new user is added we have to propagate dangerous 20444 // permission grants for these legacy apps. 20445 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20446 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20447 | UPDATE_PERMISSIONS_REPLACE_ALL); 20448 } 20449 } 20450 20451 @Override 20452 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20453 mContext.enforceCallingOrSelfPermission( 20454 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20455 "Only package verification agents can read the verifier device identity"); 20456 20457 synchronized (mPackages) { 20458 return mSettings.getVerifierDeviceIdentityLPw(); 20459 } 20460 } 20461 20462 @Override 20463 public void setPermissionEnforced(String permission, boolean enforced) { 20464 // TODO: Now that we no longer change GID for storage, this should to away. 20465 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20466 "setPermissionEnforced"); 20467 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20468 synchronized (mPackages) { 20469 if (mSettings.mReadExternalStorageEnforced == null 20470 || mSettings.mReadExternalStorageEnforced != enforced) { 20471 mSettings.mReadExternalStorageEnforced = enforced; 20472 mSettings.writeLPr(); 20473 } 20474 } 20475 // kill any non-foreground processes so we restart them and 20476 // grant/revoke the GID. 20477 final IActivityManager am = ActivityManagerNative.getDefault(); 20478 if (am != null) { 20479 final long token = Binder.clearCallingIdentity(); 20480 try { 20481 am.killProcessesBelowForeground("setPermissionEnforcement"); 20482 } catch (RemoteException e) { 20483 } finally { 20484 Binder.restoreCallingIdentity(token); 20485 } 20486 } 20487 } else { 20488 throw new IllegalArgumentException("No selective enforcement for " + permission); 20489 } 20490 } 20491 20492 @Override 20493 @Deprecated 20494 public boolean isPermissionEnforced(String permission) { 20495 return true; 20496 } 20497 20498 @Override 20499 public boolean isStorageLow() { 20500 final long token = Binder.clearCallingIdentity(); 20501 try { 20502 final DeviceStorageMonitorInternal 20503 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20504 if (dsm != null) { 20505 return dsm.isMemoryLow(); 20506 } else { 20507 return false; 20508 } 20509 } finally { 20510 Binder.restoreCallingIdentity(token); 20511 } 20512 } 20513 20514 @Override 20515 public IPackageInstaller getPackageInstaller() { 20516 return mInstallerService; 20517 } 20518 20519 private boolean userNeedsBadging(int userId) { 20520 int index = mUserNeedsBadging.indexOfKey(userId); 20521 if (index < 0) { 20522 final UserInfo userInfo; 20523 final long token = Binder.clearCallingIdentity(); 20524 try { 20525 userInfo = sUserManager.getUserInfo(userId); 20526 } finally { 20527 Binder.restoreCallingIdentity(token); 20528 } 20529 final boolean b; 20530 if (userInfo != null && userInfo.isManagedProfile()) { 20531 b = true; 20532 } else { 20533 b = false; 20534 } 20535 mUserNeedsBadging.put(userId, b); 20536 return b; 20537 } 20538 return mUserNeedsBadging.valueAt(index); 20539 } 20540 20541 @Override 20542 public KeySet getKeySetByAlias(String packageName, String alias) { 20543 if (packageName == null || alias == null) { 20544 return null; 20545 } 20546 synchronized(mPackages) { 20547 final PackageParser.Package pkg = mPackages.get(packageName); 20548 if (pkg == null) { 20549 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20550 throw new IllegalArgumentException("Unknown package: " + packageName); 20551 } 20552 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20553 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20554 } 20555 } 20556 20557 @Override 20558 public KeySet getSigningKeySet(String packageName) { 20559 if (packageName == null) { 20560 return null; 20561 } 20562 synchronized(mPackages) { 20563 final PackageParser.Package pkg = mPackages.get(packageName); 20564 if (pkg == null) { 20565 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20566 throw new IllegalArgumentException("Unknown package: " + packageName); 20567 } 20568 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20569 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20570 throw new SecurityException("May not access signing KeySet of other apps."); 20571 } 20572 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20573 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20574 } 20575 } 20576 20577 @Override 20578 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20579 if (packageName == null || ks == null) { 20580 return false; 20581 } 20582 synchronized(mPackages) { 20583 final PackageParser.Package pkg = mPackages.get(packageName); 20584 if (pkg == null) { 20585 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20586 throw new IllegalArgumentException("Unknown package: " + packageName); 20587 } 20588 IBinder ksh = ks.getToken(); 20589 if (ksh instanceof KeySetHandle) { 20590 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20591 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20592 } 20593 return false; 20594 } 20595 } 20596 20597 @Override 20598 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20599 if (packageName == null || ks == null) { 20600 return false; 20601 } 20602 synchronized(mPackages) { 20603 final PackageParser.Package pkg = mPackages.get(packageName); 20604 if (pkg == null) { 20605 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20606 throw new IllegalArgumentException("Unknown package: " + packageName); 20607 } 20608 IBinder ksh = ks.getToken(); 20609 if (ksh instanceof KeySetHandle) { 20610 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20611 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20612 } 20613 return false; 20614 } 20615 } 20616 20617 private void deletePackageIfUnusedLPr(final String packageName) { 20618 PackageSetting ps = mSettings.mPackages.get(packageName); 20619 if (ps == null) { 20620 return; 20621 } 20622 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20623 // TODO Implement atomic delete if package is unused 20624 // It is currently possible that the package will be deleted even if it is installed 20625 // after this method returns. 20626 mHandler.post(new Runnable() { 20627 public void run() { 20628 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20629 } 20630 }); 20631 } 20632 } 20633 20634 /** 20635 * Check and throw if the given before/after packages would be considered a 20636 * downgrade. 20637 */ 20638 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20639 throws PackageManagerException { 20640 if (after.versionCode < before.mVersionCode) { 20641 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20642 "Update version code " + after.versionCode + " is older than current " 20643 + before.mVersionCode); 20644 } else if (after.versionCode == before.mVersionCode) { 20645 if (after.baseRevisionCode < before.baseRevisionCode) { 20646 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20647 "Update base revision code " + after.baseRevisionCode 20648 + " is older than current " + before.baseRevisionCode); 20649 } 20650 20651 if (!ArrayUtils.isEmpty(after.splitNames)) { 20652 for (int i = 0; i < after.splitNames.length; i++) { 20653 final String splitName = after.splitNames[i]; 20654 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20655 if (j != -1) { 20656 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20657 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20658 "Update split " + splitName + " revision code " 20659 + after.splitRevisionCodes[i] + " is older than current " 20660 + before.splitRevisionCodes[j]); 20661 } 20662 } 20663 } 20664 } 20665 } 20666 } 20667 20668 private static class MoveCallbacks extends Handler { 20669 private static final int MSG_CREATED = 1; 20670 private static final int MSG_STATUS_CHANGED = 2; 20671 20672 private final RemoteCallbackList<IPackageMoveObserver> 20673 mCallbacks = new RemoteCallbackList<>(); 20674 20675 private final SparseIntArray mLastStatus = new SparseIntArray(); 20676 20677 public MoveCallbacks(Looper looper) { 20678 super(looper); 20679 } 20680 20681 public void register(IPackageMoveObserver callback) { 20682 mCallbacks.register(callback); 20683 } 20684 20685 public void unregister(IPackageMoveObserver callback) { 20686 mCallbacks.unregister(callback); 20687 } 20688 20689 @Override 20690 public void handleMessage(Message msg) { 20691 final SomeArgs args = (SomeArgs) msg.obj; 20692 final int n = mCallbacks.beginBroadcast(); 20693 for (int i = 0; i < n; i++) { 20694 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20695 try { 20696 invokeCallback(callback, msg.what, args); 20697 } catch (RemoteException ignored) { 20698 } 20699 } 20700 mCallbacks.finishBroadcast(); 20701 args.recycle(); 20702 } 20703 20704 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20705 throws RemoteException { 20706 switch (what) { 20707 case MSG_CREATED: { 20708 callback.onCreated(args.argi1, (Bundle) args.arg2); 20709 break; 20710 } 20711 case MSG_STATUS_CHANGED: { 20712 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20713 break; 20714 } 20715 } 20716 } 20717 20718 private void notifyCreated(int moveId, Bundle extras) { 20719 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20720 20721 final SomeArgs args = SomeArgs.obtain(); 20722 args.argi1 = moveId; 20723 args.arg2 = extras; 20724 obtainMessage(MSG_CREATED, args).sendToTarget(); 20725 } 20726 20727 private void notifyStatusChanged(int moveId, int status) { 20728 notifyStatusChanged(moveId, status, -1); 20729 } 20730 20731 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20732 Slog.v(TAG, "Move " + moveId + " status " + status); 20733 20734 final SomeArgs args = SomeArgs.obtain(); 20735 args.argi1 = moveId; 20736 args.argi2 = status; 20737 args.arg3 = estMillis; 20738 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20739 20740 synchronized (mLastStatus) { 20741 mLastStatus.put(moveId, status); 20742 } 20743 } 20744 } 20745 20746 private final static class OnPermissionChangeListeners extends Handler { 20747 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20748 20749 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20750 new RemoteCallbackList<>(); 20751 20752 public OnPermissionChangeListeners(Looper looper) { 20753 super(looper); 20754 } 20755 20756 @Override 20757 public void handleMessage(Message msg) { 20758 switch (msg.what) { 20759 case MSG_ON_PERMISSIONS_CHANGED: { 20760 final int uid = msg.arg1; 20761 handleOnPermissionsChanged(uid); 20762 } break; 20763 } 20764 } 20765 20766 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20767 mPermissionListeners.register(listener); 20768 20769 } 20770 20771 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20772 mPermissionListeners.unregister(listener); 20773 } 20774 20775 public void onPermissionsChanged(int uid) { 20776 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20777 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20778 } 20779 } 20780 20781 private void handleOnPermissionsChanged(int uid) { 20782 final int count = mPermissionListeners.beginBroadcast(); 20783 try { 20784 for (int i = 0; i < count; i++) { 20785 IOnPermissionsChangeListener callback = mPermissionListeners 20786 .getBroadcastItem(i); 20787 try { 20788 callback.onPermissionsChanged(uid); 20789 } catch (RemoteException e) { 20790 Log.e(TAG, "Permission listener is dead", e); 20791 } 20792 } 20793 } finally { 20794 mPermissionListeners.finishBroadcast(); 20795 } 20796 } 20797 } 20798 20799 private class PackageManagerInternalImpl extends PackageManagerInternal { 20800 @Override 20801 public void setLocationPackagesProvider(PackagesProvider provider) { 20802 synchronized (mPackages) { 20803 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20804 } 20805 } 20806 20807 @Override 20808 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20809 synchronized (mPackages) { 20810 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20811 } 20812 } 20813 20814 @Override 20815 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20816 synchronized (mPackages) { 20817 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20818 } 20819 } 20820 20821 @Override 20822 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20823 synchronized (mPackages) { 20824 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20825 } 20826 } 20827 20828 @Override 20829 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20830 synchronized (mPackages) { 20831 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20832 } 20833 } 20834 20835 @Override 20836 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20837 synchronized (mPackages) { 20838 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20839 } 20840 } 20841 20842 @Override 20843 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20844 synchronized (mPackages) { 20845 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20846 packageName, userId); 20847 } 20848 } 20849 20850 @Override 20851 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20852 synchronized (mPackages) { 20853 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20854 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20855 packageName, userId); 20856 } 20857 } 20858 20859 @Override 20860 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20861 synchronized (mPackages) { 20862 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20863 packageName, userId); 20864 } 20865 } 20866 20867 @Override 20868 public void setKeepUninstalledPackages(final List<String> packageList) { 20869 Preconditions.checkNotNull(packageList); 20870 List<String> removedFromList = null; 20871 synchronized (mPackages) { 20872 if (mKeepUninstalledPackages != null) { 20873 final int packagesCount = mKeepUninstalledPackages.size(); 20874 for (int i = 0; i < packagesCount; i++) { 20875 String oldPackage = mKeepUninstalledPackages.get(i); 20876 if (packageList != null && packageList.contains(oldPackage)) { 20877 continue; 20878 } 20879 if (removedFromList == null) { 20880 removedFromList = new ArrayList<>(); 20881 } 20882 removedFromList.add(oldPackage); 20883 } 20884 } 20885 mKeepUninstalledPackages = new ArrayList<>(packageList); 20886 if (removedFromList != null) { 20887 final int removedCount = removedFromList.size(); 20888 for (int i = 0; i < removedCount; i++) { 20889 deletePackageIfUnusedLPr(removedFromList.get(i)); 20890 } 20891 } 20892 } 20893 } 20894 20895 @Override 20896 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20897 synchronized (mPackages) { 20898 // If we do not support permission review, done. 20899 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20900 return false; 20901 } 20902 20903 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20904 if (packageSetting == null) { 20905 return false; 20906 } 20907 20908 // Permission review applies only to apps not supporting the new permission model. 20909 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20910 return false; 20911 } 20912 20913 // Legacy apps have the permission and get user consent on launch. 20914 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20915 return permissionsState.isPermissionReviewRequired(userId); 20916 } 20917 } 20918 20919 @Override 20920 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20921 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20922 } 20923 20924 @Override 20925 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20926 int userId) { 20927 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20928 } 20929 20930 @Override 20931 public void setDeviceAndProfileOwnerPackages( 20932 int deviceOwnerUserId, String deviceOwnerPackage, 20933 SparseArray<String> profileOwnerPackages) { 20934 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20935 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20936 } 20937 20938 @Override 20939 public boolean isPackageDataProtected(int userId, String packageName) { 20940 return mProtectedPackages.isPackageDataProtected(userId, packageName); 20941 } 20942 } 20943 20944 @Override 20945 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20946 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20947 synchronized (mPackages) { 20948 final long identity = Binder.clearCallingIdentity(); 20949 try { 20950 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20951 packageNames, userId); 20952 } finally { 20953 Binder.restoreCallingIdentity(identity); 20954 } 20955 } 20956 } 20957 20958 private static void enforceSystemOrPhoneCaller(String tag) { 20959 int callingUid = Binder.getCallingUid(); 20960 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20961 throw new SecurityException( 20962 "Cannot call " + tag + " from UID " + callingUid); 20963 } 20964 } 20965 20966 boolean isHistoricalPackageUsageAvailable() { 20967 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20968 } 20969 20970 /** 20971 * Return a <b>copy</b> of the collection of packages known to the package manager. 20972 * @return A copy of the values of mPackages. 20973 */ 20974 Collection<PackageParser.Package> getPackages() { 20975 synchronized (mPackages) { 20976 return new ArrayList<>(mPackages.values()); 20977 } 20978 } 20979 20980 /** 20981 * Logs process start information (including base APK hash) to the security log. 20982 * @hide 20983 */ 20984 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20985 String apkFile, int pid) { 20986 if (!SecurityLog.isLoggingEnabled()) { 20987 return; 20988 } 20989 Bundle data = new Bundle(); 20990 data.putLong("startTimestamp", System.currentTimeMillis()); 20991 data.putString("processName", processName); 20992 data.putInt("uid", uid); 20993 data.putString("seinfo", seinfo); 20994 data.putString("apkFile", apkFile); 20995 data.putInt("pid", pid); 20996 Message msg = mProcessLoggingHandler.obtainMessage( 20997 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20998 msg.setData(data); 20999 mProcessLoggingHandler.sendMessage(msg); 21000 } 21001} 21002